Execute code after Glassfish Web Deployment [duplicate] - java

This question already has an answer here:
Using special auto start servlet to initialize on startup and share application data
(1 answer)
Closed 7 years ago.
I'm trying to run a java web service on Glassfish. There is some initialization code that sets a few variables and retrieves some information from the Glassfish environment itself.
I have that code in a static initializer inside the #WebService class, however this code appears to be called too early, it gets run as soon as the WebService endpoint is deployed, whereas I need it to run once the whole web service is successfully deployed.
I tried moving the code into the constructor of the WebService class, however then that code was only run when I went into the Tester web page and sent some data to make the web methods run.
Is there any way to set up some initialization code to be run as soon as the whole web service deployment is completed?

Option 1: In Glassfish you have the Lifecycle modules
Option 2:
You also have the ability to code a ServletContextListener to be triggered when the context is loaded:
public class MyServlet implements ServletContextListener {
public void contextInitialized(ServletContextEvent e) {
// implementation code
}
public void contextDestroyed(ServletContextEvent e) {
// implementation code
}
}
Reference:
About Life Cycle Modules
Example of ServletContextListener

Yes #Jaynathan Leung, with soapUI can you deployment the web services and testing your programming with input and output data. I hope help you. :)

Related

JBoss AS 7 - After Startup initialization

Is there any way to catch an event/implements a Class, or something like that, to detect that JBoss (AS7) is up and running and all applications has been deployed ?
I made a StartupServlet (which extends HttpServlet) because i need to call a local web service to initialize the system. But because my application is not fully deployed my call for the web service (in the StartupServlet) ends in a "404 Not Found error".
I tried to use a <listener>...</listener> on the web.xml but it's not working.
You can try using a Startup EJB, like explained here:
#Singleton
#Startup
public class StartupBean {
#PostConstruct
private void startup() { ... }
#PreDestroy
private void shutdown() { ... }
}
However the bean will not detect whether your applications are deployed, only that the current application - the one containing the bean - is deployed and started. Since the #PostConstruct method is called very early, you cannot rely on any other beans or services being available.
EDIT: Jboss also has a native management API. AFAIK it can also be used to query deployments. Unfortunately it's documentation is not really impressive, but perhaps you can figure it out.
According to my understanding, you do not need to detect when all application was deployed, you need to understand only if your application was deployed. To do it you should define ServletContextListener:
http://docs.oracle.com/javaee/5/api/javax/servlet/ServletContextListener.html#contextInitialized%28javax.servlet.ServletContextEvent%29
Than you can catch when it deployed:
public void contextInitialized(ServletContextEvent sce)
{
servletContext = sce.getServletContext();
}

How to mock/stub Java container in unit testing?

I have an object that implements ServletContextListener which, according to the Java EE servlet spec, is invoked by the servlet container at deployment/startup time via its contextInitialized(ServletContext) method.
I am trying to write a unit test that simulates a servlet container starting up and deploying my ServletContextListener (so that I can determine if the app is initializing correctly).
Is this possible, and if so, how? Is it container-specific? If so I am using OGS. Looking for code that looks something like this:
#Test
public void shouldBootstrapAppAtDeployTime() {
// Given
GlassFishContainer container = new GlassFishContainer(); // ha!
MyApp app = mock(MyApp.class); // MyApp implements ServletContextListener
// When - deploy app to container
// Causes app.contextInitialized(ServletContext) to be called
container.deploy(app);
// Then - verify the method was called with any ServletContext
mock.verify(app.contextInitialized(Matchers.any());
}
This is sloppy pseudo-code with some poorly-implemented Mockito sprinkled in for demo purposes (just to get my intentions across). Thanks in advance!
Maybe you can solve this with Arquillian: http://arquillian.org/features/
From the web page:
Arquillian brings your test to the runtime, giving you access to container resources, meaningful feedback and insight about how the code really works.
I think your approach is slightly mistaken. What your unit test pseudocode does is testing the container logic that it correctly calls your ServletContextListener - I would trust the container doing that properly.
What I would do is testing your listener class directly, instantiate it, call the contextInitialized() method with a mock ServletContext (I see you're familiar with Mockito, an excellent tool for the job!), and do your assertions if your ServletContextListener did its job as expected.
Not sure if there is such testing framework. Even if it exists, it will not be testing in the real environment(which might be different from the testing environment).
The best way to write this kind of testcases is :
Deploy the war using ANT, the server you are using might be providing an MBean or something to deploy the application
Your listener might be doing some functionality when contextInitialized() method was invoked.
Write a client which makes a request to server and checks if the step 2 was successful or not.

Deploying Terminal Base Java Application

I'm migrating from .net to java and I'm not yet used in java application deployment. I'm used in deploying console base application that acts as a stand alone application , a mixed of tcp and udp servers with custom protocol.
I have a requirement that my ported .net application to java must be deployed inside tomcat or glass fish ( no embedding stuff ). I really don't know what technology I must used. I've been searching the net but my understanding is that tomcat is like IIS and for web application only and glass fish is somewhat an application server for hosting web application too. Can I really run my java console base application inside tomcat or glass fish? Can someone point out a good tutorials for this kind of stuff? Thanks!
EDIT 1
Ok got the reason why I need to deploy my app in tomcat/glassfish. I need to provide a web ui for my application since I'm currently using the console for user input. Now my application will not just support a custom tcp/udp server inside but also web functionality for management. Any suggestion how I can implement this is greatly appreciated, I just don't know yet what java api/technology to start with.
I am not sure why your requirement says that you need to run an application using a servlet container . I don't think at least based on your description your application fits servlet container programming model.
As long as you create an entry point, I think you can launch your application from command line either using java or javaw,
But If you are unable to change the requirement on the deployment to tomcat, You can do this by using a servlet to launch your application, I would read up on these things
Servlet
Deploying Servlet to tomcat
Here is one way you could do using a servlet and deploy this to tomcat
public class LaunchServlet extends HttpServlet
{
private static final long serialVersionUID = 4277145689972356257L;
//this method is run as tomcat starts up this servlet
public void init() throws ServletException
{
try
{
System.out.println("Launching my application...");
new Thread(new ApplicationLauncher()).start();
System.out.println("Launched my application successfully. ");
}
catch(Exception e)
{
throw new RuntimeException("Fail Fast: Unable to launch exception.");
}
}
class ApplicationLauncher implements Runnable
{
public void run()
{
//start you applicaton here
}
}
}

Deploying Java Application As Servlet

I have a java application that up until now was run as a stand alone java application (i.e. executable jar). I now need to deploy it in Tomcat as a servlet. It doesn't need to actually process any HTTP requests though, but it needs to be started using tomcat.
What are the steps required to convert the project so that it can be deployed in Tomcat? I'm using maven as a build tool and Java 1.5.
I understand that you want to run this app on server's startup. The best way would be implementing ServletContextListener and run the app in the contextInitialized() method. E.g.
public class Config implements ServletContextListener {
private YourApp yourApp;
public void contextInitialized(ServletContextEvent event) {
yourApp = new YourApp();
yourApp.start();
}
public void contextDestroyed(ServletContextEvent event) {
yourApp.shutdown();
}
}
Register this in web.xml as follows:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
That's it. No need to wrap it in flavor of a HttpServlet as you aren't going to fire HTTP requests on it.
You however need to ensure that it runs in its own thread, otherwise it would block the startup. If it doesn't, then wrap it in a Runnable and execute it using ExecutorService.
I'm assuming that your app is continuously running and you have an app/web server already (e.g. Tomcat/Jetty), such that it's making your life easy to deploy into it. Given that, you need to:
extend an AbstractHttpServlet class and in particular the init() method. This would start your app.
build a web.xml that references this and sets the load-on-startup attribute to 1 (or at least non-zero)
build a .war from this and deploy it
Step 2 ensures that the init() method is called upon deployment/server reboot, and so you don't have to respond to HTTP requests (a normal startup trigger for a servlet).
It may be simpler and more appropriate to use something like javaservicewrapper, and wrap it up to be a Windows service or similar.

Spring: Is there a simple non-web tutorial?

I'm attempting to create a Spring application (NOT web application) to perform some simple tasks. Eventually they will hook up with some other Spring apps around the network, but for now I'm keeping it simple. I have a CheckForNewItems class (extending Timer) which is configured to run every 10 seconds.
I can confirm it runs by calling it programmatically:
public class Tester {
public static ApplicationContext context;
private void loadContext() {
String filename = "beans.xml";
context = new FileSystemXmlApplicationContext(filename);
}
public static void main(String[] args) {
Tester test = new Tester();
test.loadContext();
CheckNewItemsTask task = (CheckNewItemsTask)context.getBean("checkNewItemsTask");
}
}
Running this works as expected, task.run() gets called every 10 seconds. Now I need to work out how to deploy this to either a JBoss or Tomcat server, in such a way that it automatically starts running the task.
Most of the tutorials I've found only describe how to get Spring MVC and servlets running, not a standalone application. Does anyone know better?
Cheers, Rob.
You don't need JBoss or Tomcat to do that. If the app is headless and you have no intention of adding a UI, consider jsvc for unix or procrun on windows. If you need the ability to monitor and control an app and do not need a proper UI for doing that, you might want to look at JMX. This will work on a daemon without the rest of the Java EE stack.
If you have a maven project and want an easy way to turn it into a deployable daemon app, you can use maven appassembler to automate the process of creating a deployable daemon, setting up a directory structure of the app, scripts to start and stop, libraries and config files.
You need a servlet that is set to autostart on deployment. The servlet can then call into your "Tester" class to trigger your "standalone" initialization process.
If you don't have a servlet (or potentially some other server related process) reference your code, then your initialization process will never be run.

Categories