Architecture of Website based on java - java

I've just started programming with Java, so might appear as silly question, but I was not able to find simple answer on the internet. This is "big" question which I have to answer before getting too deep into development, so you can help me to save a lot of time on trying different approaches.
I am currently creating a website using Java. Important feature of this website would be realized through separate Java thread (like daemon) which must be run in background for as long as the user is on the website. At the sametime, website applets must have means of communication with this thread.
I see three potential solutions to this:
Create traditional multipage website with stand-alone java applets in each separate page. I am not sure if it is possible, the following questions arise:
is it possible for java thread created by java applet to continue execution after user navigated to another webpage (on the same website)? I assume that yes.
is it possible for newly launched java applet to communicate with java thread already running in background? (I've seen part of documentation covering communication between java applets through JavaScript, not sure that this can be used in my case. Any other options?)
Create single-page website, with one single java applet, responsible for all navigation and rendering all pages. This solves the problem with background daemon, which becomes easy to implement and communicate with, as part of single applet, but raises one more questions:
I know that applet can modify current webpage. Is it feasible to use this feature to simulate navigation between different pages?
Create Java Webstart application, basically by taking the single java applet from p.2 and converting it into stand alone application.
I want the whole thing to have a look and feel of website, so I would prefer option 3 over option 2 and option 1 over option 2.
Thank you for any thoughts you share.
UPDATE:
Does anybody know answers specifically to the two questions under p1? If it is possible to work with java threads the way described?
Now I would most probably opt for making a Java Webstart Application. This should be the least painful way.
UPDATE 2:
I finally decided to work on single java applet, which can be easily converted to JWS application if needed. Nature of my project is that I need to make impression of working with website, that's why I am putting additional efforts to make it appear as a website. For knowledgeable people it will be obvious, that it is more like a local application.
Solution I chose has following benefits in my situation:
- easily convertable from JWS application to Java applet and back.
- no problems with running background thread and communicating with it.
- more reliable security (meaning that I don't need to use any mechanisms to pass over session ids from one applet to the other)
Contras:
- if size gets large, start up will be slow - I hope to avoid this.
- Security issues - I tried signing the applet and it helped a lot.
- Work of navigation buttons in browser (back and forth) - I hope to be able to replicated it in applet. Think applet should be able to catch this event.

Java thread [...] which must be run in background for as long as the user is on the website
If the thread being forked is to preserve state while the client is logged in then I would use a database, memory cache, or some other persistance layer to hold the client session state. This is a much more typical model. You can also have multiple frontends that share session information across the network.
If you are not talking to a browser then creating a stand-alone web application may be the best choice. You can still use HTTP as your transfer protocol in which case I'd recommend using a Java web implementation like Jetty. This would involve significantly less technology and complexity.
If you need to implement web pages, I would certainly use proper frontend models and technology. You should separate your pages into multiple applets -- or multiple controllers/views in the MVC model. Using the applets should be fine. They (or the controllers) should call a centralized service which starts, communicates with, and stops the background threads depending on the information flow.
I would also certainly have another background thread running to time out your client threads in case a client never returns. Your worker threads could just exit after a certain amount of waiting.
Hope this helps.
is it possible for java thread created by java applet to continue execution after user navigated to another webpage (on the same website)? I assume that yes.
Yes. Threads that are forked will continue to run until they terminate or (if daemon) the process terminates.
is it possible for newly launched java applet to communicate with java thread already running in background?
Sure. What they need is some mechanism to be able to share data. For example, your background thread service could keep a Map of the thread objects with the key being some sort of client-id. Whenever a thread wanted to talk to it's background thread then it could call the service to lookup the thread by id. Something like:
BackgroundStream thread = threadService.getThread(clientId);
thread.callMethod(...);
If there was some sort of synchronous question/response then you'd need to have a condition variable or something. Read up on Java threads for more information.

There's an architecture used in Website applications in Java, it's called a Model-View-Controller. Frameworks such as Java Server Faces (Standard on Java EE 5 and higher), Struts (1.x or 2.x), Spring, Apache Wicket, etc. were designed to create web applications using MVC model. The question is, would you prefer the component-based architecture of the framework (such as JSF) or not (which you shouldn't be worried about at this moment)
Applets is defnitely a bad choice as applets are downloaded to client side. Some browsers don't support Applets especially in mobile web browsers and its difficult to apply security settings to untrusted applets, plus you may not know if the client has blocked the applet or not.

Applets are a bad choice because of 2 reasons:
1) First, they are executed on client's browser and not on server. Therefore you cannot perform any backend processing(Business logic or fetching data from server database) using applets.
2) Applets are very buggy and have security issues. That's why applets are out of fashion these days.
Now coming to how you can create website using java technology, for that you need to start understand Java Server Side programming. Start learning about Java Servlets and Java Server Pages. To put it in simple terms, they are java programs which are executed on a web-server or application server.
then start reading about Java Enterprise Edition.
refer this tutorial for Java Enterprise Edition

Related

How to build a distributed java application?

First of all, I have a conceptual question, Does the word "distributed" only mean that the application is run on multiple machines? or there are other ways where an application can be considered distributed (for example if there are many independent modules interacting togehter but on the same machine, is this distributed?).
Second, I want to build a system which executes four types of tasks, there will be multiple customers and each one will have many tasks of each type to be run periodically. For example: customer1 will have task_type1 today , task_type2 after two days and so on, there might be customer2 who has task_type1 to be executed at the same time like customer1's task_type1. i.e. there is a need for concurrency. Configuration for executing the tasks will be stored in DB and the outcomes of these tasks are going to be stored in DB as well. the customers will use the system from a web browser (html pages) to interact with system (basically, configure tasks and see the outcomes).
I thought about using a rest webservice (using JAX-RS) where the html pages would communicate with and on the backend use threads for concurrent execution.
Questions:
This sounds simple, But am I going in the right direction? or i should be using other technologies or concepts like Java Beans for example?
2.If my approach is fine, do i need to use a scripting language like JSP or i can submit html forms directly to the rest urls and get the result (using JSON for example)?
If I want to make the application distributed, is it possible with my idea? If not what would i need to use?
Sorry for having many questions , but I am really confused about this.
I just want to add one point to the already posted answers. Please take my remarks with a grain of salt, since all the web applications I have ever built have run on one server only (aside from applications deployed to Heroku, which may "distribute" your application for you).
If you feel that you may need to distribute your application for scalability, the first thing you should think about is not web services and multithreading and message queues and Enterprise JavaBeans and...
The first thing to think about is your application domain itself and what the application will be doing. Where will the CPU-intensive parts be? What dependencies are there between those parts? Do the parts of the system naturally break down into parallel processes? If not, can you redesign the system to make it so? IMPORTANT: what data needs to be shared between threads/processes (whether they are running on the same or different machines)?
The ideal situation is where each parallel thread/process/server can get its own chunk of data and work on it without any need for sharing. Even better is if certain parts of the system can be made stateless -- stateless code is infinitely parallelizable (easily and naturally). The more frequent and fine-grained data sharing between parallel processes is, the less scalable the application will be. In extreme cases, you may not even get any performance increase from distributing the application. (You can see this with multithreaded code -- if your threads constantly contend for the same lock(s), your program may even be slower with multiple threads+CPUs than with one thread+CPU.)
The conceptual breakdown of the work to be done is more important than what tools or techniques you actually use to distribute the application. If your conceptual breakdown is good, it will be much easier to distribute the application later if you start with just one server.
The term "distributed application" means that parts of the application system will execute on different computational nodes (which may be different CPU/cores on different machines or among multiple CPU/cores on the same machine).
There are many different technological solutions to the question of how the system could be constructed. Since you were asking about Java technologies, you could, for example, build the web application using Google's Web Toolkit, which will give you a rich browser based client user experience. For the server deployed parts of your system, you could start out using simple servlets running in a servlet container such as Tomcat. Your servlets will be called from the browser using HTTP based remote procedure calls.
Later if you run into scalability problems you can start to migrate parts of the business logic to EJB3 components that themselves can ultimately deployed on many computational nodes within the context of an application server, like Glassfish, for example. I don think you don't need to tackle this problem until you run it to it. It is hard to say whether you will without know more about the nature of the tasks the customer will be performing.
To answer your first question - you could get the form to submit directly to the rest urls. Obviously it depends exactly on your requirements.
As #AlexD mentioned in the comments above, you don't always need to distribute an application, however if you wish to do so, you should probably consider looking at JMS, which is a messaging API, which can allow you to run almost any number of worker application machines, readying messages from the message queue and processing them.
If you wanted to produce a dynamically distributed application, to run on say, multiple low-resourced VMs (such as Amazon EC2 Micro instances) or physical hardware, that can be added and removed at will to cope with demand, then you might wish to consider integrating it with Project Shoal, which is a Java framework that allows for clustering of application nodes, and having them appear/disappear at any time. Project Shoal uses JXTA and JGroups as the underlying communication protocol.
Another route could be to distribute your application using EJBs running on an application server.

How do I decide between a using a Swing GUI or a light-weight web client for the user front end of my Java application?

I always seem to have this internal struggle when it comes to user interface. I build up an application "engine" and tend to defer user interface to after I get my algorithms working. Then I go back and forth trying to decide how to let a user interact with my program. Personally, I'm a fan of the command line, but I can't expect that of my users generally.
I really like what's possible in the browser in the age of web 2.0 and ajax. On the other hand it's not so hard to make a Swing front-end either, and you can generally count on a more consistent presentation to the user (though using a good javascript framework like YUI or jQuery goes a long way toward normalizing browsers).
Clearly both approaches have their merits and drawbacks. So, what criteria / parameters / situations should lead me to use a lightweight (e.g. web-based) GUI? What criteria / parameters / situations should lead me to use a heavier (e.g. Swing-based) GUI?
It is not my intent to start a flame war, merely interested in the community's constructive/objective opinions.
Edit #1
In light of the first few responses, I would like to clarify that I would like to deploy my application regardless, not host it on some internet server necessarily. So I would have to deploy with a light-weight web-server infrastructure a la Jetty/Tomcat or similar.
It depends on the application and this is essentially a usability driven question (though there are considerations like data storage and platform requirements). Think of the pros and cons.
Pros of a lightweight Web UI:
Ease of distribution
Platform independent
Ease of maintenance
Cons of a lightweight Web UI:
Less environmental control
Markup standards vary between browsers
Requires a web server and everything that goes with it
Pros of an executable UI
More environmental control (i.e.: full screen applications, etc)
Not necessarily subject to latency and outages
Cons of an executable UI
Pushing updates may be more difficult
Requires installation
Potential platform requirements (frameworks, packages, etc)
Potentially requires knowledge of advanced networking topics (web services, etc)
One small factor you may want to consider is that the user will have go through some type of installation (albeit minimal) if you distribute a swing application.
Also a web application will allow you to accurately track the usage of your application (via google analytics or something similar). Not sure if that's a concern but it may be useful to you in the future.
If it is a client-server application I would normally go for a web frontend for the application.
You will save yourself of countless problems with things like installed JRE versions, distributing upgrades, application permissions, disappeared shortcuts...
You need to break the requirements of the application down to decide this...
Do the users have Java of sufficient version installed? It will need to be, to run a Swing GUI.
Do you have a web server?
Do you need the flexibility of a Swing GUI or the accessibility of the web interface?
Is Java Webstart and option, if so, you can distribute a Swing GUI via the web.
Does your application perform extensive calculations or processing? If so, a client app may be the answer.
There are a million questions such as these. I would suggest a brain storming session and keeping track of all the pros and cons of each, adding a point score, than throwing it all away and going with your gut feeling :)
If you anticipate there being frequent updates to the app then web based may be better since the user would not have to update the client or install a new client containing the updates.
If you think that the user may need the ability to use the app while not conencted to the internet then swing would be better.
Just two things off the top of my head.
Think about the users and use cases of your project.
Do users expect to have access to it when they're disconnected from the Internet (for example, on an airplane or in a coffee shop with no Internet access)? Use Swing.
Do you want users to be able to access the same tool from different computers (for example, both at work and at home)? Use a web UI.
Also consider whether the user needs to save and load data, and whether the tool produces data files that some might consider sensitive (if so, storage on the web might be an issue).
Do make a quick guess I often try to ask myself/customers if the application has a high "write" demand.
For a mostly read-only application a thin-client solution is perfectly well suited.
But if a lot write actions are needed then a swing desktop application has more flexibility.
Personally I always prever a swing desktop application. It can easily deployed using Java Webstart.
Not knowing anything about your application I can not give the best recommendation possible. However I can state from personal/professional experience that installing an application on clients machines is a LOT more of a pain in the ass than it seems.
With AJAX/web you really only have to worry about supporting like three browsers. Installation messes/updates are only felt once when you deploy the product to the web server.
With like a stand-along Swing app, you get to deal with the really really big mess that is installing the application onto unknown systems. This mess was so bad that things like AJAX were really pushed along to make web apps behave/feel like a real native app.

Multiplayer browser game [Java]

I've been developing a small card game which is called "Tarneeb". The game itself looks like Bridge card game but with different rules. Anyway, i finished the entire game as a standalone desktop application using Java 6. This is a picture of the game. Anyway, i now need to transform that into a web app with multiplayer capabilities, so the users can for an example make a new room and join existing rooms where the game is played.
Unfortunately, I have no idea on networking in Java but i searched quite a lot and i found some other Java products that may help me (JavaFX, JSP, GlassFish) but i still couldn't figure out what i exactly needed to accomplish my task. All i need right now is the direction to head to and i will do my research and hopefully learn the new skills needed.
Other answers have already pointed you to some resources.
But the biggest problem you will likely have is that it is usually impossible (or extremely time consuming up to a complete rewrite) to "add" multiplayer capabilities afterwards if you didn't plan the architecture accordingly.
As you might have a lot of interaction and a lot of updates which I should - correct me if I'm wrong - be at the client as fast as possible, I'd suggest having a look at Cometd which keeps the http connection open to each client and pushes the updates from the server to the client. If you're using jetty as webserver (and thus its "continuations") it's even highly scalable.
The thing is, there isn't one standard way of doing this which you need to read up on.
How do you want to implement this web application? As an applet? Using standard web pages? As a web start application which people have to download?
The last option would allow you to re-use most of your existing code. If you go with that option it may be worth you looking into RMI as that will probably fit in with your existing architecture.
But otherwise, as S.Lott pointed out, you need to go and learn how to make web applications before doing anything else. Those tutorials would be a good start, also you should definitely learn (X)HTML, JavaScript, and a Java web technology such as JSPs, JSF, or Struts. Exactly what you need will depend on your requirements, without more details it's diffiult to recommend one.
First, learn what a "web site" and "web application" are.
Do the tutorials: http://java.sun.com/developer/onlineTraining/index.jsp
Watch the Glassfish Tutorials: http://java.sun.com/javaee/overview/screencasts.jsp
Once you've done all the tutorials, you will have built a web application.
After you've built the tutorial web application, you can build your web application.
Web apps are very badly suited for the kind of realtime interaction you have in a card game. Yes, it can be done, but it will involve dirty hacks and you'll always have problems with high latency and broken connections. And of course you'll have to completely rewrite most of your app.
If there a possibility of running the game as a Java applet? That would make your job much easier (enable much more reuse) and the end result more usable.
There is no way to port a client based app into a web app quickly. Depending on how you want to go about it, it sounds like you either need to pursue a JSP/Javascript solution or a JavaFX solution. JavaFX actually allows for smoother (smoother than JSP/Javascript, but still going to take more than an afternoon =D ) porting of client based apps, but it has a steeper learning curve than JSP/Javascript technology in general. An interesting note here is that JavaFX isn't just a web app language. If you had coded your initial client based app in JavaFX, you would have about 50% of the work done.
JavaFX
Use Java NIO, it is quite simple and if you will grasp the basics, there would be no real need in all these countless libraries... or anyway you would know their internals. One of the important things however, mentioned here already, is that the game structure has to be adapted for networking from the start. It may be a complete rewrite in the worst case. Basically, you will have to create clients database, socket connections, and from the server side, every connection (represented by a SelectorKey object), should be encapsulated into an object, representing a "joined client". Then read/write operations would be performed to the key's socket. But there is more. The server will have to be the center of your application link, so that you will have to develop an entire network messages protocol for your game (over TCP, there is no need in UDP in this kind of game). Also - read more about the protocols (TCP/UDP/sockets, ethernet), the more you read - the better.
Also! Pay attention to the HTML5 websockets stuff. It is a great thing!!!

Java Web Start - Popularity

I recently used a Java Web Start application. I launched it from my web browser using an embedded jnlp link in the page I was viewing. The application was downloaded, launched and worked just fine. It had access to my local file-system and remembered my preferences between restarting it.
What I want to know is why are Java Web Start applications not a more popular delivery format for complex applications on the web? Why do developers often spend considerable time & energy replicating desktop functionality in html/javascript when the power of a desktop application could be delivered more easily using Java & Java Web Start?
I know that in some corporate environments, e.g banking, they are relatively popular ways of delivering complex trading applications to clients, but why are they not pervasive across the web as a whole?
(For the sake of discussion let's assume a world where: download sources are "trusted" & applications are "signed" (i.e. no security concerns), download speeds are fast (load time is quick) and developers know Java (in the numbers they know html/js/php)).
I think the reason is not security nor startup time of the app. Let's understand what's behind the scene before we find out the root cause.
Java Control Panel has settings that allow users to use the default browser's proxy settings or to override them. In other words, infrastructure teams are able to customize the Windows or OS installation images to have JVM pre-installed with enterprise proxy settings. So I believe this is not an issue at all.
Java Web Start actually caches all apps with customizable settings in Java Control Panel. Once the app is cached, the app is "installed" just like other apps. Although first time execution may be slow, the second time will be fast due to JVM's smart memory allocation technique. So start up time could be an issue but a lot of web sites (even enterprise internal) are now migrated to portal. A web portal normally contains lots of unused libraries for development purposes due to the fact that the portal itself does not anticipate what kinds of portlets are built and deployed on a specific page. Therefore, downloading a single portal page could consume up to MBs and complete a page in more than 5 seconds; this is only one page and caching helps up to 30% but there are still lots of HTML/Javascript/CSS components required to download every time. With this, I am sure Java Web Start is an advantage here.
Java Web Start does not download again if it is cached as long as the server copy is NOT upgraded. Therefore, if, e.g. a project management software like MS Project, is completed using SmartClient (similar to JWS), the information exchange between the client and server would be purely data without presentation like browser's full page refresh. Even with the help of Ajax, it doesn't eliminate full page download entirely. Besides, a lot of companies consider Ajax to be immature and unsecured still. That is why Ajax is a hot topic in the circles of developers but not within enterprise software yet. With that in mind, JWS apps definitely have more advantages such as how JWS apps are deployed and executed in sandboxes, signed, and have much more interactive GUI.
Other advantages include faster development (easier to debug in code and performance), responsive user interface (does not require Comet Servers to provide PUSH functionality), and executing faster (for sure because client computers renders GUI without translation like HTML/Javascript/CSS, and less data processing).
After all these, I haven't touched the question yet, why JWS is not so famous?
My opinion is that it is the same as Brian Knoblauch's comment, it's without awareness.
IT folks are too attracted by the hype of Web Technologies, Ajax PUSH, GWT, and all those buzz words make them bias towards the fun of using different technologies or to resolve technical challenges instead of what's really working for the clients.
Take a look at Citrix. I think Citrix is actually a great idea. Citrix allows you to build your own app farms behind the scene. There are tons of upgrade and implementation strategies you can go for without impact to client experience. Citrix deployment is extremely easy, stable and secure. Enterprises are still using it. However, I think JWS is even better than Citrix. The idea of JWS is to run apps on client machines instead of hosting tons of server farms where client machines are capable of running these apps themselves. This saves a company a lot of money!!! With JWS, development team can still build business logic and data on server side. However, without the web processing unit and let the client computers do the rendering process, it greatly reduces the amount of network consumption and server processing power.
Another example of why JWS is an amazing idea is Blackberry MDS. Blackberry apps are actually Java apps translated from Javascript. With BB's MDS studio, you use the GUI tool to build BB app GUI, coding GUI logic in Javascript. Then apps are then translated and deployed on a BES server. Then the BES server will distribute these apps to BB. On each BB, it runs a thin Java App with GUI rendering and networking capability only. Whenever the app requires data, it communicates with the BES through web services to consume services from other servers. Isn't this just JWS BB version? It's been extremely successful.
Finally I think JWS is not popular because of how Sun advertises it. BB never advertises how good their BB Java apps are, they believe clients won't even care what is it. BB advertises the benefits of using MDS to develop apps: Fast, Cost Saving, Business Return.
Just my, a bit long, 2 cents... :)
A major roadblock for Java Webstart is probably that you still need to have a JVM installed before it can even attempt to download and start your application. Everyone has a browser. Not everyone has a JVM.
Edit:
I've since acquired some hands-on webstart experience and can now add these two points:
The Deployment Toolkit script and the modularized JVM released somewhere around Java 1.6u10 make the JVM requirement less problematic since it can automatically download a JVM and the API core and start the program wile downloading the rest.
Web Start is seriously buggy. Even among the Java 1.6 releases there was one which downloaded the entire app every time, and another which downloaded it and then failed with an obscure error message. All in all, I cannot really recommend relying on such a fragile system.
I think it's mostly due to a lack of awareness. It works very well. Quite seamless. App only downloads if it's the first time, there's been an upgrade, or if the end-user has cleared the cache. Great way to deploy full-blown desktop apps that user won't have to worry about manually upgrading!
The problem with Webstart is, that you actually have to 'start' something which isn't at all that fast even with a fast connection, while with a webapp you enter the URL and the app is there.
Also a lot of things can go wrong with webstart. Maybe the intended user doesn't have the privileges needed, or the proxy of webstart is configured wrong, or something went wrong with jre dependencies or there is simply no java installed in the first place. So for the average john doe in the internet it is not at all pleasent.
In controlled environments like a company it is a good and easy solution in many cases.
I've worked on a JWS-deployed application for a few years over a user base of a few thousands and its automatic upgrades are actually a huge pain.
On every update for some reason dozens of users get "stuck in the middle". All you get is the "class not found" exception (if you're lucky), or uninformative "unable to launch" from JWS before it even gets to your code. Looks like the update is half-downloaded. Or, in other words, it does not download and apply the update atomically AND has poor caching so that relaunching the app from the same URL does not fix anything.
There's no way to resolve it other than clearing JWS cache or providing a different URL (e.g. append ?dummyparam=jwssucks at the end). Even I as a developer hit it sometimes and don't see a way around.
When it works, it works. But too often it doesn't, and then it's a huge pain for you and your helpdesk. I would not recommend it for enterprise or mission-critical use.
There is a very big issue namely that it doesn't allow for "start the program instantly and THEN check for and download any updates in the background" deployments, which is what the defacto behaviour of applications are converging to.
I consider this personally so big an annoyance that we are actively looking for another technology which provides that.
From these posts it looks like when using Web start, it is important to make a good care about the server. The "huge pain" of downloading application on every startup may be caused by incorrect time stamp delivered from the server. Here not the application but the server must be configured to use caching properly and not just to disable it. About buggy start, I am not that much sure, but it seems to me that this also may be caused by unreliable connection.
Important advantage of Web start is that it works nicely with OpenJDK under Linux. Clients of some happy developers use Windows only but my clients do not.
HTML and JavaScript, mentioned in the initial question, are lighter approaches that work fine with smaller tasks like animated buttons or even interactive tables. Java niche seems around much more complex tasks.
Java Web Start is kind a successor of Java Applets, and applets got burned around the new millenium.
But, I still think Java Applets are way better than GWT or Javascript hell.
Java Web Start vs Embedded Java Applet

Running Java on a Web Server

I have written a standalone Java application that I've packaged into a jar file that takes in some command line arguments, does some hardcore computations, and then writes out the result to a file along with some output to the default output stream pointing to where the file with the results are.
I now want to create a website around this technology. The idea is that the user can fill in an html form, post it to a webpage, which would then call the Java application, parse the results from the Java app, and display it to the user.
Currently, I am using a little bit of PHP to collect the data from the post request, and then just using an exec call: java -jar -Xmx128m myapplication.jar command-line-arguments
Is this bad?
I do have several thousand visits to my website each day and each execution of the Java application can take upwards of 30 seconds to a minute, so I don't want to be overly inefficient. It seems like there would be a better solution than having to call Java directly for every request.
I keep hearing things like java servlets, beans, tomcat, glassfish, etc., but I don't understand what they are and how they would benefit me. What do these get me? Faster results because the Java JVM doesn't have to be created each time I run the application? Less memory usage? I obviously want it to run as fast as possible with as little memory footprint as possible.
So, what is the best approach that I can take here? I don't want to do any serious rewriting of my application as there is a lot of code (so rewriting it to C or C++ is out of the question).
Thanks.
Ok, servlets are smalish applications that are designed to run inside of a container. They provide an extension point for you to insert your java code into either a simple servlet container like tomcat, or a more fully featured application server like glassfish. You want to do this because the application server does the heavy lifting of dealing with the http interaction and provides other features like security, logging, session management, error handling, and more (see the servlet specification).
When you make your application live within an application conatiner (web server with all those other extra features), you can also manage the lifecycle of your application better. You'll be able to start and stop the application without shutting down the web server, redeploy, start more instances, etc. Plus, when you come up with that great second application, its easy to drop it in right next to the first one. Or, you can cluster several machines together for easy redundancy and load balancing, features of the application server.
This is just a start, there are many more features, technologies, and frameworks out there to help you make container based applications. Servlet tutorial.
[Do these get me] "Faster results because the Java JVM doesn't have to be created each time I run the application?"
Yes.
And -- bonus -- you can replace PHP so your entire site is in a single language: Java.
Further, you can consider revising your use cases so it isn't a painful 30-60 seconds in one shot, but perhaps a series of quicker steps executed interactively with the user.
Run your code inside a servlet container.
Assuming that you need to keep your website in PHP and as you already have java installed on your machine, simply install a free servlet container (such as Apache Tomcat, or Jetty). Configure to run the servlet container on an unused port. (8080) is their default.
These servlet containers are really java based webservers, just like Apache, however specialized in serving java code.
The most obvious advantage of using a java webserver rather than a new java.exe invocation for each request, is that your java virtual machine (jvm) will always be "hot", up and running. Each new start of the java.exe (jvm) will give you those extra seconds of waste.
The second advantage of using a servlet container, is that the container will enable your code to run in a new thread, inside the jvm, for each new request. You will have no problem providing your service to your thousands of users a day. Most likely, your machine will crash if you were to start hundreds of java instances rather than one.
Place your code inside a servlet. It really is easy even for a newcomer. You will talk to the servlet via HTTP (doGet or doPost methods of the servlet). Pass the php request form to this servlet and have the servlet give you back whatever: a page, a json object, xml or plain text.
You probably don't want to invoke the java app directly from the website. Like you said, if the java process takes 30 seconds to run, your web server is going to get way bogged down, especially if your site is getting pounded.
You may want to look into web-services (and possibly a message queue) for dispatching back-end processing requests. The PHP page could call the web-service on the server, which could then put a processing request on a queue, or just kick off the java app in an asynchronous fashion. You don't want the HTTP request to wait for the java app to finish, because, while it's processing, the user will just have a hung browser, and the HTTP request might timeout.
Once the java app finishes, it could update a database table, which the user could then access from the website.
The easiest thing to start with would be to embed a webserver in you application. Have a look at Jetty.

Categories