NPE SpringLookupInitializer createLookup Spring-Vaadin 19+ - spring

In trying to update to the latest version of Vaadin (20 at time of question), my application will not start due to NPE in the SpringLookupInitializer. When I was using Vaadin 19, which is where SpringLookupInitializer first started being used and I first started encountering the error I had to always use Spring-Vaadin 12.4.0 for the application to start up. The error seems to be coming from this change...
In 12.4.0 there is code in SpringLookupInitializer defined as:
#Override
protected Lookup createLookup(VaadinContext context,
Map<Class<?>, Collection<Class<?>>> services) {
WebApplicationContext appContext = getApplicationContext(context);
return new SpringLookup(appContext,
(spi, impl) -> instantiate(appContext, spi, impl), services);
}
private WebApplicationContext getApplicationContext(VaadinContext context) {
VaadinServletContext servletContext = (VaadinServletContext) context;
WebApplicationContext appContext = WebApplicationContextUtils
.getWebApplicationContext(servletContext.getContext());
if (appContext == null) {
// Spring behavior is always unbelievably surprising: under some
// circumstances {#code appContext} may be null even though the app
// context has been set via ApplicationContextAware: no idea WHY
ApplicationContextWrapper wrapper = context
.getAttribute(ApplicationContextWrapper.class);
appContext = wrapper == null ? null : wrapper.appContext;
}
return appContext;
}
It works this way because it is doing a check and correcting it before proceeding (basically what the comment says). In the newest version the getApplicationContext is removed and the check no longer performed
#Override
protected Lookup createLookup(VaadinContext context,
Map<Class<?>, Collection<Class<?>>> services) {
WebApplicationContext appContext = WebApplicationContextUtils
.getWebApplicationContext(
((VaadinServletContext) context).getContext());
return new SpringLookup(appContext,
(spi, impl) -> instantiate(appContext, spi, impl), services);
}
I am not using spring boot just MVC and everything works fine with the older spring-vaadin version. Is there a reason it no longer performs this check or something else that has been implemented that I can do to stop this from happening?
Thanks

Thanks for the report - it seems that those changes (in PR #740) have been overlooked for the latest versions of the Vaadin Spring add-on. We're going through the changes and making sure those get forward-ported and will be released soon for Vaadin 20 too.
For similar cases, when updating the Vaadin version breaks something, it is recommended to just directly open a new issue to the corresponding repository (like vaadin/spring or vaadin/flow) so it will be noticed immediately by the development team. Thanks
EDIT: The fix has been released in the Vaadin Spring add-on version 17.0.1. You can specify your project to explicitly use that version of vaadin-spring artifact. It will be included in Vaadin 20.0.2 release which is coming by next Monday 14th of June at latest.

Related

ehcache-clustered not working in OSGi when project is installed several times

Having troubles with clustered ehcache in osgi/aem. Only with first project build/installation it works fine, but with second build/installation it stops working, generate a lot of errors. It looks like terracotta connection, cachemanager or something third is not properly closed.
Even after deleting bundles it tries connect to terracotta.
ok log, errors in log
I'm installing ehcache and ehcache-clustered as standalone bundles in osgi. Also tried with embedding them into my bundle. Ehcache and ehcache-clustered are set as dependencies, also tried with org.apache.servicemix.bundles.javax-cache-api (embedding, not sure if it's needed)
First time all ehcache and ehcache-clustered services are active, 2nd time are satisfied.
Ehcache bundle, ehcache-clustered bundle, javax-cache-api bundle, my project bundle
pom.xml
Same code I have tired as standalone java app and it works perfectly fine (https://github.com/ehcache/ehcache3-samples/blob/master/clustered/src/main/java/org/ehcache/sample/ClusteredXML.java)
So not sure what I have missed (dependencies, import packages..)?
ehcache config, terracotta config
#Activate
private void activate() {
LOGGER.info("Creating clustered cache manager from XML");
URL myUrl = ClusteredService.class.getResource("/com/myco/services/ehcache-clustered-local2.xml");
Configuration xmlConfig = new XmlConfiguration(myUrl);
try (CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig) ) {
cacheManager.init();
org.ehcache.Cache<String, String> basicCache = cacheManager.getCache("basicCache4", String.class, String.class);
LOGGER.info("1. Putting to cache");
basicCache.put("1","abc");
LOGGER.info("1. Getting from cache");
String value = basicCache.get("1");
LOGGER.info("1. Retrieved '{}'", value);
LOGGER.info("cache manager status2, " + cacheManager.getStatus().toString());
}
}
You have to also create a #Deactivate method where you do a cacheManager.shutdown();
I guess if you call your code in a non OSGi project twice you would also experience the same error.

JAX-RS: How to run a method on start (without servlets)

I have a JAX-RS (Jersey) server with which I register and bind my stuff.
I want to print a banner when the server starts up. I want to do this using the JAX-RS framework not the web server's platform (i.e., no Jetty, Netty, Thorntail, etc hooks).
I saw the following which mentions the tried and true Servlet way of doing things:
Jax rs: How can I run a method automatically everytime my server restarts? , but that does not work because I am not running a servlet container in my server so that lifecycle call is never made.
I figured there must be a JCA-ish type object that I can register with Application/ResourceConfig that has such a lifecycle call, but I am unable to even find any kind of list of the things you can actually register.
Not to complain (but I will), but I cannot decide if this is so difficult because when they moved the project to eclipse, they broke every hyperlink to the old official documentation or that it is simply so implicit, like Spring, that it only works by github'ing other people's code and realizing, 'oh, I did not know you could do that'.
Jersey has Event Listeners. You'll want to use the ApplicationEventListener and the ApplicationEvent.Type you'll probably want to listen for to print the banner is the INITIALIZATION_FINISHED
public class MyApplicationEventListener
implements ApplicationEventListener {
#Override
public void onEvent(ApplicationEvent event) {
switch (event.getType()) {
case INITIALIZATION_FINISHED:
printBanner();
break;
}
}
#Override
public RequestEventListener onRequest(RequestEvent requestEvent) {
return null;
}
}

JerseyTest and Spring and creating a ServletContext

I'm working on migrating from Jersey 1.16 to Jersey 2.7. I have the application running and working, but I'm having trouble with the tests.
Some things to note:
The application uses Spring and is configured by a class, ApplicationConfiguration.class.
The application does not have a web.xml - the Jersey servlet and filters are configured programmatically.
I am using the jersey-spring3 library.
Related to using the jersey-spring3 library, I have to add a workaround to my onStartup method
// The following line is required to avoid having jersey-spring3 registering it's own Spring root context.
// https://java.net/jira/browse/JERSEY-2038
servletContext.setInitParameter("contextConfigLocation", "");
Here's the issue:
When the test is starting up, SpringComponentProvider, tries to initialize Spring with a dangerous assumption that I can't figure out how to correct - xml based configuration. Looking at the code, the trouble is this block
ServletContext sc = locator.getService(ServletContext.class);
if(sc != null) {
// servlet container
ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
} else {
// non-servlet container
ctx = createSpringContext();
}
Running a JUnit test, ServletContext is null, and createSpringContext is called.
Here's the question:
Is there a way to run a test and specify a ServletContext/ServletContainer?
I believe this issue is covered by https://java.net/jira/browse/JERSEY-2259.
In short: they removed this functionality from Jersey 2.x and are treating it as a Feature Request (instead of regression) so it's not considered a high-priority item.

WebApplicationInitializer being called repeatedly

I have a Spring 3.1 based application hosted under Tomcat 7.x (latest version). The application is configured exclusively with Java (no web.xml, no Spring XML configuration). All unit tests are passing, including ones using the Spring Java configuration (#ContextConfiguration).
The problem is that when the application is deployed, the WebApplicationInitializer implementation is being called multiple times. Repeated registrations of filters and listeners causes exceptions and the application never starts.
I was not expecting WebApplicationInitializer.onStartup() to be called repeatedly and would like to eliminate that behavior if possible. If anyone has suggestions on why this might be happening, and how to stop it, I'd really appreciate it.
Update I believe the problem is external to the initialization class itself, but here it is in case I am mistaken...
public class DeploymentDescriptor implements WebApplicationInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("org.ghc.web-app-initializer");
#Override
public void onStartup (ServletContext servletContext) throws ServletException {
// This is the programmatic way of declaring filters. This allows you to order
// Filters. The order of these security filters DOES MATTER!
FilterRegistration.Dynamic mockSecurityFilter = servletContext.addFilter ("mockSecurityFilter", "org.ghc.security.MockSecurityFilter");
mockSecurityFilter.addMappingForUrlPatterns (EnumSet.of (REQUEST), true, "/*");
FilterRegistration.Dynamic siteMinderSecurityFilter = servletContext.addFilter ("siteMinderSecurityFilter", "org.ghc.security.SiteMinderSecurityFilter");
siteMinderSecurityFilter.addMappingForUrlPatterns (EnumSet.of (REQUEST), true, "/*");
FilterRegistration.Dynamic userDetailsStoreFilter = servletContext.addFilter ("userDetailsStoreFilter", "org.ghc.security.UserDetailsStoreFilter");
userDetailsStoreFilter.addMappingForUrlPatterns (EnumSet.of (REQUEST), true, "/*");
// Static resource handling using "default" servlet
servletContext.getServletRegistration ("default").addMapping ("*.js", "*.css", "*.jpg", "*.gif", "*.png");
// Map jspf files to jsp servlet
servletContext.getServletRegistration ("jsp").addMapping ("*.jspf");
// Spin up the Spring 3.1 class that can scan a package tree for classes
// annotated with #Configuration. See org.ghc.spring3.ControllerConfiguration for
// this example.
final AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext ();
dispatcherContext.setServletContext (servletContext);
dispatcherContext.register(ScProviderDirectory.class);
dispatcherContext.refresh ();
// Spin up the Spring DispatcherServlet (just like before) passing the just built
// application context. Load it like the regular Servlet that it is!
final ServletRegistration.Dynamic servlet = servletContext.addServlet ("spring", new DispatcherServlet(dispatcherContext));
servlet.setLoadOnStartup (1);
servlet.addMapping ("/"); // Make sure this is NOT "/*"!
}
}
Update 2 This is just weird. The Tomcat logs appear to identify two instances of my DeploymentDescriptor class. I verified that there is only one instance of this class in my .war file though. I have no idea where the second (phantom) instance is coming from, but at least this explains why the class is being scanned twice...
logs/localhost.2012-10-09.log:INFO: Spring WebApplicationInitializers detected on classpath: [org.ghc.configuration.DeploymentDescriptor#3b29642c]
logs/localhost.2012-10-09.log:INFO: Spring WebApplicationInitializers detected on classpath: [org.ghc.configuration.DeploymentDescriptor#432c4c7a]
The problem here was a Maven Overlay dumping crap a Spring xml configuration file into my application. For whatever reason this caused the WebApplicationInitializer.onStartup() to be called twice. Probably an initialization for the application context, and for the servlet context. Killed off the overlay, application is initializing as expected.
I had the same problem. The issue was that I had multiple spring-web*.jar like Biju K. suggested (one as part of the war, the other in shared/tomcat library).
I had the same problem. Running mvn clean in the web app module's directory and then starting up Tomcat solved it for me.

Automatic configuration reinitialization in Spring

In Log4j, there is a feature wherein the system can be initialized to do a configure and watch with an interval. This allows for the log4j system to reload its properties whenever the property file is changed. Does the spring framework have such a Configuration Observer facility wherein the Configuration is reloaded when it changed. The Configuration that needs reloading is not the Springs's applicationContext.xml but various other configuration files that are initialized using the Spring initialization beans.
I found a utility that does something similar to Log4J here. It's basically an extension to PropertyPlaceholderConfigurer that reloads properties when they change.
AFAIK Spring does not provide such a utility. However there is a 3rd party tool, JRebel that enables you to update an entire web application (including the Spring configuration) without requiring a server restart.
A free trial is available, and the purchase price is fairly inexpensive.
I would be extra cautious with reloading spring application context.
What do you expect to happen with singleton beans? If an object has a reference to singleton bean, should it be updated?
I develop using JRebel and I would be very wary of expecting it to refresh your configuration. Works fine with Java, not with Spring though.
If you would like to add context, I have done that in the following way :
public class ApplicationContextUtil
{
static String[] configFiles = {"applicationContextParent.xml"};
private static ApplicationContext context = null;
static
{
context = new ClassPathXmlApplicationContext ( configFiles );
}
public static void addContext( String[] newConfigFiles )
{
// add the new context to the previous context
ApplicationContext newContext = new ClassPathXmlApplicationContext ( newConfigFiles, context );
context = newContext;
}
public static ApplicationContext getApplicationContext ()
{
// return the context
return context;
}
}
This is your context provider class. For details, you can look at my blog

Resources