Spring boot embedded tomcat get resource issue - java

I'm in the process of migrating my project as a spring boot application (mostly for the embedded tomcat solution) from a WAR that was previously deployed on tomcat.
So I encountered a problem with the embedded tomcat container that I hope someone can perhaps offer a solution, perhaps through spring or maven instead of modifying my dependency jars that my project uses to work around this issue.
I have two data model jars that contain xsd files and each one has a catalog file in "/catalog/jaxb-catalog.xml". I found that when one of my libraries call:
Class loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("/catalog/jaxb-catalog.xml");
It would only one xml file and ignore the second xml file as confirmed when i printed out the "url". It seems the container is "TomcatEmbeddedWebappClassLoader" However, when my application is deployed in a standalone tomcat container, the "url" would include both and the container is WebAppClassLoader.

You can read all resources with a name using
org.springframework.core.io.support.PathMatchingResourcePatternResolver
its a normal 'java' class so you can create an instance with new
to find all resources use
resolver.findResources("classpath*:catalog/jaxb-catalog.xml"
have a look at the javadoc of PathMatchingResourcePatternResolver it contains some valuable information.

Related

Want to change the context path in Spring boot application in an external Tomact server version 9

I want to deploy a Spring boot application in an external Tomcat server version 9. I am able to deploy it and working the endpoints also. But properties I have set in application.properties file those are not working. Like server.servlet.context-path=/myapp is is not working instead the context path which I am getting is http://localhost:8080/myapp-0.0.1-SNAPSHOT/api/ping.
I am using 2.3.10.RELEASE and Java 1.8 and Tomcat version 9.0.46 Can anyone please help me out with this.
But everything is perfectly working on embedded tomcat. Thanks in advance and any suggestion, comment is highly appreciated.
Can anyone please help me with how I can do this - My war file name would be myapp-0.1.war but the context path of the application would be like this localhost:8080/myapp/api/ping
Use finalName property in your build file (pom.xml for maven)
<finalName>myapp</finalName>
When you run a Spring Boot application in an external servlet container, the server.* properties do not apply.
If you are willing to change the naming convention you can drop a WAR file named myapp##0.1.war in the $CATALINA_BASE/webapps directory and benefit from parallel deployment (cf. parallel deployment).
If you want to stick to your naming convention, you can create a folder for your WAR files (e.g. $CATALINA_BASE/webapps-available) and create a deployment descriptor $CATALINA_BASE/conf/<engine_name>/<host_name>/<context_path>.xml (in your case probably $CATALINA_BASE/conf/Catalina/localhost/myapp.xml) with the following content:
<Context docBase="${catalina.base}/webapps-available/myapp-0.1.war" />

JDBC driver not found (servlet, DAO, mariaDB) [duplicate]

I developer a web application using Java. When I deploy it to my application server (Jetty, Tomcat, JBoss, GlassFish, etc.) throws an error. I can see this error message in the stacktrace:
java.lang.ClassNotFoundException
Or
java.lang.NoClassDefFoundError
What does this mean and how can I fix it?
What does this mean?
First, let's see the meaning of java.lang.ClassNotFoundException:
Thrown when an application tries to load in a class through its string name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader.
The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.
Usually, this happens when trying to open a connection manually in this form:
String jdbcDriver = "...'; //name of your driver
Class.forName(jdbcDriver);
Or when you refer to a class that belongs to an external library and strangely this class cannot be loaded when the application server tries to deploy the application.
Let's see the meaning of java.lang.NoClassDefFoundError (emphasis mine):
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
The last part says it all: the class existed at compile time i.e. when I compiled the application through my IDE, but it is not available at runtime i.e. when the application is deployed.
how can I fix it?
In Java web applications, all third party libraries used by your application must go in WEB-INF/lib folder. Make sure that all the necessary libraries (jars) are placed there. You can check this easily:
- <webapp folder>
- WEB-INF
- lib
+ jar1
+ jar2
+ ...
- META-INF
- <rest of your folders>
This problem usually arises for JDBC connectivity jars (MySQL, Derby, MSSQL, Oracle, etc.) or web MVC frameworks libraries like JSF or Spring MVC.
Take into account that some third party libraries rely on other third party libraries, so you have to add all of them in WEB-INF/lib in order to make the application work. A good example of this is RichFaces 4 libraries, where you have to download and add the external libraries manually.
Note for Maven users: you should not experience these problems unless you have set the libraries as provided, test or system. If set to provided, you're responsible to add the libraries somewhere in the classpath. You can find more info about the dependency scopes here: Introduction to the Dependency Mechanism
In case the library must be shared among several applications that will be deployed on your application server e.g. MySQL connector for two applications, there's another alternative. Instead of deploying two war files each with their own MySQL connector library, place this library in the common library folder of the server application, this will enable the library to be in the classpath of all the deployed applications.
This folder vary from application server.
Tomcat 7/8: <tomcat_home>/lib
JBoss 7/Wildfly: <jboss_home>/standalone/lib
The class must exist under WEB-INF/classes or be inside a .jar file under WEB-INF/lib. Make sure it does.
Same problem happen with me.
Might be possible one of your libraries are using some classes internal which is not available
in your lib or maven dependency pom.xml.
Thats means you have analyze your error logs and identify these classes and then import all dependencies in maven or lib folder.
I have fixed this error by the same way.
because some of my libraries are using activation.jar and json.jar internally.

NoSuchMethodError: org.hibernate.SessionFactory.openSession()

I'm having hibernate3.jar and hibernate-core-4.2.0.CR1.jar in my classpath and I'm using Spring 3.1.3 version. Code got compiles sucessfully but while runtime I'm getting following error
2014-10-28 10:51:25,174 DEBUG [RMI TCP Connection(2)-10.126.30.203] -
Target method failed for RemoteInvocation: method name
'getPriceByKeys'; parameter types [java.util.List, java.util.Date]
java.lang.NoSuchMethodError:
org.hibernate.SessionFactory.openSession()Lorg/hibernate/Session;
I google it but not find any solution. Please note : My project needs hibernate3.jar but at the same time my project dependent on some other 3rd party jar which inturn using hibernet4.2.0 jar.
Any help Pls ??
You need to remove multiple hibernate JAR files from your classpath. Without doing this, your application may not work as you expect; which means you need to migrate the hibernate version of your application from 3 to 4.1.
Although Spring 3.1 uses Hibernate 3 JAR files, you can still migrate to Hibernate 4. Check out Spring blog gives a small tutorial to do so.
Migrating to Spring 3.1 and Hibernate 4.1
As part of the Core-Spring course, we have a lab application that we
use to show how to integrate Spring and JPA/Hibernate together. We
have just upgraded it to Spring 3.1 / Hibernate 4.1, and thought we
should share a few tips.
Just an update. The cause of problem is , I'm having two spring-context xml files in project (one of my project and one related to another module that I'm integrating). I'm loading context xmls from two different classes. So one of the DAO class loaded by one of spring-context xml not getting the hibernate Session.
Later on using import tag, I included 2nd spring application context file in 1st application context file and then loaded a Single application context file from the class. It solved the error.
Thanks,

Failed to import bean definitions from URL location [classpath:applicationContext-core.xml]

I'm working on a java project with spring on eclipse using Maven, and running on a Tomcat server v6.0. Everything was working fine since yesterday morning.
Here his my problem : I'm building my project, I got a build success. Then I start my Tomcat server and got this error :
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:applicationContext- core.xml]
Offending resource: ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext-core.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext-core.xml] cannot be opened because it does not exist
I found out similar problem on some website but none of them give me a solution that worked for me.
It seems that eclipse isn't able to find applicationContext-core.xml when I'm doing this :
<import resource="classpath:applicationContext-core.xml" />
However, I do have the needed jar file nad-core-0.0.1-SNAPSHOT.jar in WEB-INF/lib containing applicationContext-core.xml.
I even tried to add it manually to the classpath but I was still having the same problem.
I keep on looking for a solution, when suddendly it work again once after restarting Eclipse and building while Eclipse was still updating indexes and my project was having this strange status Hg status pending instead of default. Surprised by this result I decide to build again my project after restarting Eclipse and I got the error again and I enable to make it work again. It's quite annoying...
This looks to be a really random problem.
Thanks a lot for your help :)
As you've not specified you web application structure. I assume you've a simple web application at hand with the following structures
webapp
WEB-INF/classes/applicationContext.xml
WEB-INF/lib/nad-core-0.0.1-SNAPSHOT.jar/applicationContext-core.xml
Application context.xml refers to the applicationContext-core.xml file using the import tag. I did encounter a similar situation in my web application, here're the check lists that you should go through and may be one of them can apply to your situation.
Check the generated snapshot jar file for the applicationContext-core.xml file and make sure it is in the root directory of the jar. As silly as it sounds, this was the root cause of the issue I faced in my deployment.
Make sure your Maven Pom.xml file is configured to include this XML file from the resources folder. You can use the resource tags in the build phase of Maven to package them within the jar file itself.
You can try removing the import tag from application context.xml file and instead load both of them from Spring's webapplication context itself.
Add a context loader listener class from spring org.springframework.web.context.ContextLoaderListener
Add context-param contextConfigLocation with value classpath:applicationContext-core.xml,classpath:applicationContext.xml. Spring has the ability to dynamically sort out the dependencies before initiating the bean factory.
Hope this check list helps.
I get pretty much the same config, six years later, I got the same error.
I also restart Eclipse, and it solved the issue.

Controlling the classpath in a servlet

My servlet application includes a number of library .jars, some of which contain embedded log4j.xml or log4j.properties files. I'd like to ensure that log4j finds my log4j.xml first! I've tried searching for some specification of the priorities of the various classpath elements in a servlet (e.g. does WEB-INF/classes always precede WEB-INF/lib?), or some way to configure or tweak the servlet's classloader so that a given resource directory appears early in the classpath. So far, I've drawn a blank. Any suggestions on ensuring that a servlet .war file loads the correct log4j.xml via the classloader?
Tomcat 8.5
Ditto Tomcat 8.0.
See documentation: Class Loader HOW-TO.
Tomcat 8.0
The answer is simple, taken from the Tomcat documentation page, Class Loader HOW-TO. In particular notice the use of the /WEB-INF/ directory/folder.
Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
Bootstrap classes of your JVM
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
System class loader classes (described above)
Common class loader classes (described above)
If the web application class loader is configured with <Loader delegate="true"/> then the order becomes:
Bootstrap classes of your JVM
System class loader classes (described above)
Common class loader classes (described above)
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
Tomcat 6
Excerpted from Tomcat 6 page, Class Loader HOW-TO.
Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
Bootstrap classes of your JVM
System class loader classes (described above)
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
$CATALINA_HOME/lib
$CATALINA_HOME/lib/*.jar
As far as I understand the resource selection from the classpath is non-deterministic (from the point of view of the app developer). Even if the same file is loaded consistently the behaviour could change:
1. When you upgrade the version of your current container.
2. If you switch containers.
The simplest solution will be to remove embedded log4j config files from library jars. It is almost never a good idea to embed log4j config's as it leads to the problem you are seeing here...
Are they third party jars or jars you developed?
We the Spring Log4jConfigListener in our web.xml file.
You can specify as a context parameter the location of the log4j config file, i.e. you could set it as /WEB-INF/log4j.xml
Would this be an option for you? If you're not using Spring I know that you can set the Log4j location programatically which might also work.
In my experience, WEB-INF/classes typically takes precedence over jars in WEB-INF/lib, however, that also depends on the servlet container you use (I could never figure out the behavior of JRun, for instance). It would help immensely if you could tell me which container you're using.
Also, are you certain that the offending log4j configuration is in a jar in WEB-INF/lib? Typically, when I've run into classpath problems in a servlet container situation, it's because of libraries that reside outside of the web app.
The servlet specs recommend that web app classloaders load their own classes before delegating to the container's classloader (SRV.9.7.2), but since this is counter to the Java spec, not all vendors do this by default (in fact Tomcat is the only container I've used that does this by default). With that said, it's always possible to configure your container's web app classloading behavior. If you tell me which container you're using, I may be able to help you (specifically, I have done this successfully before on WebLogic, WebSphere, Glassfish and JRun)).
If you're unable to control the classpath, since Tomcat is setting it for you, are you at least able to set a system property for log4j.configuration? I believe that location pointed to by that property can be set outside of the classpath.
If not, another approach, although an ugly one, would be to explicitly run one of the configurators yourself in your application code.
You need to have log4j.properties in your CLASSPATH. The best place is under WEB-INF/classes.
You also have to make sure that you use your version of log4j.jar. So, put it in WEB-INF/lib, just to make sure you are not using one from tomcat folders, since it may cause strange classloading issues.

Categories