Is PHP Java Bridge having same performance as JSP->Java? - java

I am building a website which will have a rigorous database access. It should also have a good exception handling mechanism and be fast.
To avoid DB access, I want to load some of the values in RAM using Java.
Inorder to handle MySQL DB handles issue, I am creating a pool of DB handles and accessing them using threads in Java.
The Java shall provide interfaces to access the values present in RAM as well as provide user management and some other interfaces.
I need detailed error handling and exception handling is great in Java as compared to PHP.
Now my problem is:
Accessing Java objects in PHP is an issue because it does not have a great system to store values in PHP.
Also, PHP access to Java is required through PHP bridge.
So, Should I use JSP? But JSP is not available on all servers, so thats a dilemma for me.
Is PHP -> Java bridge a good solution? Is it scalable and has good performance as compared to JSP->Java combination

This is actually a common situation. While not necessarily in Java, it is common practice to have compiled back-ends to a pseudo-interpreted (I know PHP isn't an interpreted language) front end. Then, you get the benefits of speed and thread-persistence in a language such as Java with the iterative capabilities (read: no compilation necessary) of a PHP front end.
My advice would be for you to check out the Apache Thrift project. This will generate common interfaces between a Java server and PHP client which allow you to execute service calls from your PHP environment and pass them off to Java.
Basically, in PHP, you establish a TCP connection to your Java server. Java does the database call, loads the data, whatever else it needs to do, and returns the object back to you in PHP. Thrift will help you create consistent objects and interfaces and keep them in sync between the two environments.

Related

Fetching data outside of JVM

I'm curious to know if it's possible to fetch data from other applications to my Java program. I know java is running in a virtual environment, hence JVM and therefore have problems communicating with other applications unless you were to use the Robot class or so forth.
What I would like to do, for starters as educational purposes is to take let's say a music application like Spotify/iTunes, fetch the playlist (text data) and send/display it in a text file. I've tried a few things so far, and the only thing I've come close to is by using the Robot class, opening the application, doing Ctrl+A, pasting it in to a text document and so forth but that's more like a macro. I would like to make a java application that would do this automatically. Is that possible in any sense with Java or are you just better off changing languages? I wish to do it with Java though because it's the language I've studied for the past year and what I'm trying to master. (Sorry for the long explanation.)
It's nothing to do with Java and the JVM. Any language has the same problems and solutions for this sort of situation.
The thing you need to talk to has to provide you a way to talk to it. You need to talk to it using that way.
Methods include pipes, custom network protocols, SOAP and Restful web services, etc.
Just because an application runs in a virtual machine doesn't mean it cannot access external data through an API provided by an external program. For example, iTunes has a COM-based API for accessing playlists, and here is an example of using it from C#. You'll need something which allows accessing COM objects from Java.
(Please note I know nothing about this topic, this is just what I found with a little searching...)
You need to know which data interfaces provides the application you want to connect to.
As an example, maybe the application writes files to disk or stores some info in a database.
Then with Java you can read files, query the database, use an API (web services, REST, etc..) and so on...

Is a Java to PHP Bridge neccessary for this situation?

We are dealing with an API that sends us a significant amount of data. I'm still in the architecture phase of the application, but my strategy is going to be to use PHP for the frontend portion and then for dealing with the API Id use a set of java classes and access them through calling a java file from the exec function in php. There's too much data for PHP to deal with this, which is why I am deciding to use Java, but I was curious if it would be ideal instead to use a java-to-php bridge? It says that using this bridge is significantly better for performance, but it would take some time to figure out how to install it and get it working.
Truthfully, I just want to call java classes with exec but if initiating a new JVM seems to be considerably intensive than I need to rethink my strategy.
Any thoughts?
Java Bridge could be one option: using Quercus or IBM's WebSphere sMash might be another. I've used all three options, but my personal preference is using an API. Calling java via exec isn't really an API

How can I communicate between PHP and a Java program?

I'm working on a web application that frequently requires a calculation intense query to be run, the results of which are stored in a separate table. Using MySQL, this query takes about 500ms (as optimized as possible, believe me). To eliminate this bottleneck, I've created a Java program that loads the relevant DB data into memory and performs the query itself; it takes about 8ms (something I'm a little bit proud of). I'd like to use this Java program to get the results, and if it fails or is unavailable, failover to having PHP run a MySQL query.
Since loading the data into the Java application takes some time, it's going to load it once and remain running as a background process. Now, the question is how do I communicate with this Java application via PHP?
Keep in mind:
Multiple instances of PHP may need to communicate with this Java process simultaneously.
If the Java instance cannot be found (eg: it crashes for some reason) PHP should progress by using the older and slower MySQL method.
An intermediary process, such as Memcache, is acceptable.
Ideally, the solution would withstand race conditions.
I would preferably not like to use MySQL as the intermediary.
I was going to use Memcache, where PHP would write to a known key and poll until that key changed to "completed", meanwhile Java would poll that key and once it found something perform the job and set it to "completed". However, this wouldn't work for two reasons. First, both PHP and Java read/write to Memcache using serialized objects, and there's no way to change that, and I don't want Java to unserialize PHP objects and vice/versa -- it's too messy. Second, this is not ACID compliant -- if a queue built up there would be race conditions.
For now, I'm stuck with polling MySQL "selects" to see if a job is off the queue or not, which is far from an optimal solution because the poll time will need to be slower so MySQL doesn't get pinged too frequently. I need a better solution!
Thanks.
Edit: Duh. It looks like I will be using some sort of SocketServer in Java, which I'm unfamiliar with. An example might help :)
I'm using socket server on the Java end, and PHP sockets on the PHP end. Works great.
There's no need to overcomplicate things with PHP/Java bridge, and no need for overhead of creating a web server.
Sockets work great, and I'm actually a bit ashamed I even asked the question to begin work.
My suggestion is to use WebServices... Write and run webservice in Java, and then request it in php by using f.e. NuSOAP. This solution have one more advantage - your webservice can be used easily in other applications like f.e. .NET ones...
Another option which might be easier if you have small number of methods is to build Servlet in Java which will take the parameters as GET request.
Both those solutions are strictly web-based, and both of them are working on separate threads so they guarantee you good performance.

Connect PHP code to Java backend

I am implementing a website using PHP for the front end and a Java service as the back end. The two parts are as follows:
PHP front end listens to http requests and interacts with the database.
The Java back end run continuously and responds to calls from the front end.
More specifically, the back end is a daemon that connects and maintain the link to several IM services (AOL, MSN, Yahoo, Jabber...).
Both of the layers will be deployed on the same system (a CentOS box, I suppose) and introducing a middle layer (for instance: using XML-RPC) will reduce the performance (the resource is also rather limited).
Question: Is there a way to link the two layers directly? (no more web services in between)
Since this is communication between two separate running processes, a "direct" call (as in JNI) is not possible. The easiest ways to do such interprocess communcation are probably named pipes and network sockets. In both cases, you'll have to define a communication protocol and implement it on both sides. Using a standard protocol such as XML-RPC makes this easier, but is not strictly necessary.
There are generally four patterns for application integration:
via Filesystem, ie. one producers writes data to a directory monitored by the consumer
via Database, ie. two applications share a schema or table and use it to swap data
via RMI/RPC/web service/any blocking, sync call from one app to another. For PHP to Java you can pick from the various integration libraries listed above, or use some web services standards like SOAP.
via messaging/any non-blocking, async operation where one app sends a message to another app.
Each of these patterns has pros and cons, but a good rule of thumb is to pick the one with the loosest coupling that you can get away with. For example, if you selected #4 your Java app could crash without also taking down your PHP app.
I'd suggest before looking at specific libraries or technologies listed in the answers here that you pick the right pattern for you, then investigate your specific options.
I have tried PHP-Java bridge(php-java-bridge.sourceforge.net/pjb/) and it works quite well. Basically, we need to run a jar file (JavaBridge.jar) which listens on port(there are several options available like Local socket, 8080 port and so on). Your java class files must be availabe to the JavaBridge in the classpath. You need to include a file Java.inc in your php and you can access the Java classes.
Sure, there are lots of ways, but you said about the limited resource...
IMHO define your own lightweight RPC-like protocol and use sockets on TCP/IP to communicate. Actually in this case there's no need to use full advantages of RPC etc... You need only to define API for this particular case and implement it on both sides. In this case you can serialize your packets to quite small. You can even assign a kind of GUIDs to your remote methods and use them to save the traffic and speed-up your intercommunication.
The advantage of sockets usage is that your solution will be pretty scalable.
You could try the PHP/Java integration.
Also, if the communication is one-way (something like "sendmail for IM"), you could write out the PHP requests to a file and monitor that in your Java app.
I was also faced with this problem recently. The Resin solution above is actually a complete re-write of PHP in Java along the lines of JRuby, Jython and Rhino. It is called Quercus. But I'm guessing for you as it was for me, tossing out your Apache/PHP setup isn't really an option.
And there are more problems with Quercus besides: the free version is GPL, which is tricky if you're developing commercial software (though not as tricky as Resin would like you to believe (but IANAL)) and on top of that the free version doesn't support compiling to byte code, so its basically an interpreter written in Java.
What I decided on in the end was to just exchange simple messages over HTTP. I used PHP's json_encode()/json_decode() and Java's json-lib to encode the messages in JSON (simple, text-based, good match for data model).
Another interesting and light-weight option would be to have Java generate PHP code and then use PHP include() directive to fetch that over HTTP and execute it. I haven't tried this though.
If its the actual HTTP calls you're concerned about (for performance), neither of these solutions will help there. All I can say is that I haven't had problems with the PHP and Java on the same LAN. My feeling is that it won't be a problem for the vast majority of applications as long as you keep your RPC calls fairly course-grained (which you really should do anyway).
Sorry, this is a bit of a quick answer but: i heard the Resin app server has support for integrating java and PHP.
They claim they can smash php and java together: http://www.caucho.com/resin-3.0/quercus/
I've used resin for serving J2ee applications, but not for its PHP support.
I'd be interested to hear of such adventures.
Why not use web service?
Make a Java layer and put a ws access(Axis, SpringWS, etc...) and the Php access the Java layer using one ws client.
I think it's simple and useful.
I've come across this page which introduces a means to link the two layers. However, it still requires a middle layer (TCP/IP). Moreover, other services may exploit the Java service as well because it accepts all incoming connections.
http://www.devx.com/Java/Article/20509
[Researching...]

How can I call a method in an object from outside the JVM?

I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.
I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine Update: the caller I have in mind is not another JVM; thanks #Dave Ray
My implementation considerations are typical
performance
ease of implementation and maintenance (simplicity?)
reliability
flexibility (i.e. can I call from a remote machine, etc.)
Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?
(Stuff people have actually done and can provide real-life feedback on would be great!)
Ok. Here's another try now that I know the client is not Java. Since you want out-of-process access and possibly remote machine access, I don't think JNI is what you want since that's strictly in-process (and a total hassle). Here are some other options:
Raw Sockets : just set up a listener socket in Java and accept connections. When you get a connection read the request and send back a response. Almost every language can use sockets so this is a pretty universal solution. However, you'll have to define your own marshalling scheme, parsing, etc.
XML-RPC : this isn't as hip these days, but it's simple and effective. There are Java libraries as well as libraries in most other languages.
CORBA : as mentioned above, CORBA is an option, but it's pretty complicated and experts are getting harder to come by.
Web Server : set up an embedded web server in your app and handle reqests. I've heard good things about Jetty or you can use the one provided with Java. I've used the latter successfully to server KML files to Google Earth from a simulation written in Java. Most other languages have libraries for making HTTP requests. How you encode the data (XML, text, etc) is up to you.
Web Services : This would be more complicated I think, but you could use JAX-WS to expose you objects as web services. NetBeans has pretty nice tools for building Web Services, but this may be overkill.
Will you be calling from another JVM-based system, or is the client language arbitrary? If you're calling from another JVM, one of the simplest approaches is to expose your object as an MBean through JMX. The canonical Hello World MBean is shown here. The pros are:
Really easy to implement
Really easy to call from other JVMs
Support for remote machines
jconsole allows you to manually test your MBean without writing a client
Cons:
Client has to be on a JVM (I think)
Not great for more complicated data structures and interactions. For example, I don't think an MBean can return a reference to another MBean. It will serialize and return a copy.
Since your callers are not Java apps and you're already foreseeing networked callers, RMI-IIOP (CORBA) might be an option. Though it's definitely not easy to implement, it has the advantage of being a widely-recognized standard.
Since your caller is not JVM-based, this is a question of inter-process communication with JVM. The options I have in mind are:
Communicate over a socket: make your JVM listen to incoming connections and caller send commands
Communicate using shared files (caller writes to file, JVM polls and updates)
Using JNI, start JVM inside a callers process and then use RMI/MBeans to communicate with the first ("server") JVM. Caller will have access to results using JNI
Option 3 IMO is the most "Java" way of doing this, and is the most complex/error-prone.
Option 2 is ugly but simple
Option 1 is moderately easy (java part) and otherwise ok.
For ease of use, I would use Spring Remoting. If you are already using Spring in your project, that's a no brainer. If you arent ... well you should have a look anyway.
Spring provides an abstraction that allow you to switch remoting protocols easily. It supports the most widely deployed protocols (SOAP, Hessian, Burlap, RMI, ...). If you are calling from non Java code, Hessian has support in a number of other languages, is known to be more efficient than SOAP and easier than CORBA.
Beanshell is a shell-like java interpreter that can be exposed over a network socket. Basically you do this from java:
i = new bsh.Interpreter();
i.set( "myapp", this ); // Provide a reference to your app
i.eval("server(7000)");
and then you do this from anywhere else:
telnet localhost 7001
myapp.someMethod();
This little utility does remote java invocations much more easily than JNI or RMI ever has.
For more, start at: http://www.beanshell.org/manual/remotemode.html
JNI (Java Native Interface) allows access to java code from C or C++.
I have an Inno Setup script (installing a Java program) which calls some Java methods to perform some operations or check some conditions.
I (actually my predecessor) just instanciate java.exe on each call. Which is, obviously, costly, although not critical in my case (and the Windows cache kicks in, I suppose).
An alternative is to use some inter-language communication/messaging, your Java program acting as a server. Corba comes to mind, as it is language agnostic. But a bit heavy, perhaps. You can use sockets. RPC is another buzzword too, but I haven't much experience in the field.
What you want is the Java Native Interface (JNI), despite the difficulties that it may present. There is no other equivalent technology that will be as easy to implement.
As mentioned in the comments for the preceding answer, the JNI is optimized for calling native code from Java, but it can also be used for the reverse with a little work. In your native code you'll need to implement the JNI entry point--something like SetMapPointer()--then call that function from the Java code once the Map is built. The implementation of SetMapPointer() should save the Java object pointer someplace accessible, then the native code can invoke Java methods on it as needed.
You'll need to make sure that this happens in the right order (i.e. the native code doesn't try to access the Map before it's been built and passed to native code), but that shouldn't be an especially hard problem.
Another alternative to consider if the other process will be on the same machine and the OS is POSIX-compliant (not Windows) is Named Pipes.
The outside process writes the operations, as strings or some other agreed-upon byte encoding, to the named pipe while the Java application is reading from the pipe, parsing up the incoming operations and executing them against your object.
This is the same strategy that you would use for socket connections, just instead of a SocketInputStream you'd be reading from a FileInputStream that is attached to a named pipe.
An alternative to CORBA is ICE, unless the licence is a problem (it's GPL, but you can also buy a commercial licence).
It has pretty much all the benefits of CORBA, but ZeroC, the vendor, provides bindings for many different languages. CORBA vendors tend to only provide one or two language bindings, and then you start finding compatibility problems.
The documentation is also excellent. I wouldn't have said it was particularly easy to pick up, but probably easier than CORBA.
Otherwise, another option I don't think has been mentioned is the new middleware/RPC framework developed by Cisco, now donated to Apache, called Etch. It's still pretty new though, and documentation is sparse.

Categories

Resources