Spring 4 mvc: trigger an event when the web application is ready - java

I have a Spring 4 mvc application and I would like to make a GET request to another node.js service when the web application is available.
The client is build with React.js and served by Spring.
I already tried the following Spring Listeners:
ServletContextListener
ApplicationListener
ContextLoaderListener
The node application when receives the call takes a screenshot of the homepage. The result is a white page because the event fires too soon.
I suppose that the problem could be the react js bundle taking more time to load.
Is there a away to solve this? Maybe I miss the right Listener.
Thank you

Sorry, this is for spring boot not simply spring-web.
You need the ApplicationReadyEvent as documented here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-spring-application.html#boot-features-application-events-and-listeners
If your spring boot app is defined as follows, here's a possible implementation:
#SpringBootApplication
public class YourMainClass {
public static void main(String[] args) throws Exception {
SpringApplication.run(YourMainClass.class, args);
}
#EventListener(ApplicationReadyEvent.class)
public void EventListenerExecute(){
System.out.println("App is ready for requests");
}
}

Related

Configure Swagger UI + Jersey 2 with JdkHttpServerFactory

I am attempting to set up Swagger + Swagger UI in a pre-build project which uses neither the Jersey 2 container Servlet nor the Filter configuration (with web.xml) as stated in the official docs.
My main class looks like this:
public class Application {
public static void main(String[] args) {
URI uri = UriBuilder.fromUri("//localhost/").scheme("http").port(8080).build();
ResourceConfig resourceConfig = new ResourceConfig();
final HttpServer httpServer = JdkHttpServerFactory.createHttpServer(uri, resourceConfig, false);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
httpServer.stop(0);
}));
httpServer.start();
}
}
I want to use package scanning and the Swagger UI to keep track of my API. All answers i found stated you should either extend the Application class or use a Filter configuration with a web.xml file. Please give me a hint on how to add Swagger to the existing project which was given to me.
I am new to JAX-RS and a bit confused... so I ask for understanding. :)
You could try to just extend the Application class in your existing one.
You can also do this operation without using any api. Just call the report with the parameters you want with REST call to your jasper server.

SpringBoot: Control Async behaviour from #RequestMapping analogous to an AsyncWebServlet?

I am working with Spring Boot 2 and I would like my requests to be handled asynchronously.
In Java EE, one can use Asynchronous Processing for Asynchronous Servlets as in this link. The following is a related example:
#WebServlet(urlPatterns={"/asyncservlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet { ... }
and the above allows to use AsyncContext.
But in Spring Boot, I have the following #RequestMapping. How do I make it handle requests in Asynchronous mode and also supporting AsyncContext? How do I leverage the use of an Asynchronous Web Servlet?
#RestController
public class myRestController {
#RequestMapping("{resource}/**")
public void resourceRequest (#PathVariable("resource") String resource) {
// example:
// ... some long running calls such as database communication
// ... convert request through AsyncContext ctx = req.startAsync();
// etc
}
}
Note that returning void is intentional.
I found the following SO answer How to register a servlet with enabled "async-supported" in Spring-Boot? saying that "Spring Boot will automatically register any Servlet beans in your application context with the servlet container. By default async supported is set to true so there's nothing for you to do beyond creating a bean for your Servlet." but I am not using any #WebServlet annotations anywhere in my program, just the #RestController annotation. So how do I ensure that I am benefitting from asyncSupported option?

Running both Springboot and Rest endpoints in one project/application Java

I'm getting very confused over whether you can or can't run spring boot stuff and REST endpoints in one application. At the moment I have them in separate project directories, running the springboot UI one with:
#SpringBootApplication
public class LeagueProjectUiApplication {
public static void main(String[] args) {
SpringApplication.run(LeagueProjectUiApplication.class, args);
}
}
and the REST rest endpoints with:
mvn tomcat7:run
and my jersey and tomcat stuff are declared in my pom.xml
Rest:
#Path("/university")
public class University {
#GET
#Path("/{universitycode}")
#Produces(MediaType.APPLICATION_JSON)
public Response returnSingleSummoner(
#PathParam("universitycode") String universityCode) {
}
What's the best way of running both SpringBoot and REST endpoints at the same time, or am I getting completely confused!
Thanks.
When you say REST endpoints, do you mean Jersey endpoints?
Spring Boot supports Jersey,as you can see, for example, here, so nothing theoretically should stop you for putting everything in one application as long as request paths are different.

How can I close a SpringBoot WebSocket server?

I imagine it's incredibly simple but I've been unsuccessful in my googling of how-to's, reading of documentation, and perusing of Spring classes.
Spring's doc on their websocket api has been useful and I can see that the project I'm familiarizing myself with uses what it describes to start a server:
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
#Autowired
private MyWebSocketHandler webSocketHandler;
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketHandler, "/");
}
}
So it's easy enough to start, but I have no idea how to make it stop or pause. I'd like to add a feature to the application that takes down the server (and re-establishes it later) with a click of a button. But I have no ideas about how to stop or pause the server and the documentation doesn't seem to offer anything.
the initialization/management/shutdown of websocket/http connections are handled by spring and tomcat (default). I don't think it's a good idea to deal with it on your own.
a solution would be to decouple (with two springboot apps) the websocket service (which can be started/stopped manually) from the one (which is always up and running) with the "click of a button" page.

Can I write a module/filter that gets fired before the web app get's run in Tomcat?

Can I write a module/filter that gets put into the processing pipleline in Tomcat BEFORE the web application even gets run?
Something that I could turn on/off for each web application that tomcat is handling.
is this possible?
So basically it would be a re-usable filter that hooks into the web pipeline that could alter the requests behavior or perform/modify the requests. One example would be to log all ip's, or redirect based on the url, block the request, etc.
If you are using Servlet 3.0 you can. What you do is implement either a ServletContextListener or a ServletContainerInitializer. The code below shows withServletContextListener
#WebListener("auto config listeners")
public class MyListenerConfigurator implements ServletContextListener {
public void contextInitialized(ServletContextEvent scEvt) {
ServletContext ctx = scEvt.getServletContext();
FilterRegistration.Dynamic reg = ctx.addFilter("myFilter", "my.listener.class.MyListener");
...
}
See EE6 docs here. Perhaps the only drawback is that you can add but you cannot remove. And you can only at when the application starts up.
Note: code not tested
Have you considered a ServletContextListener in web.xml?

Categories