We are facing a weird issue in production. Ours is a web application deployed in Tomcat 7. We are using Antisamy-1.5.3.jar for XSS prevention.Each user request is intercepted by a filter which scans the requests for any malicious content.
This setup was all fine in Tomcat 6 for more than a year. We migrated to Tomcat 7. Users get NoClassDefFoundError on and off when they open the app(not consistent) but when Tomcat is restarted it works fine.
Below is the flow where exception is thrown
User request is intercepted by AntiSamyFilter and scan method on owasp.validator.html.AntiSamy class(AntiSamy internal class) is called.
Below is the code for scan method
public CleanResults scan(String taintedHTML, Policy policy)
throws ScanException, PolicyException
{
return new AntiSamyDOMScanner(policy).scan(taintedHTML);
}
When AnitSamyDOMScanner class is referenced in the code above, static init block of super class of AntiSamyDOMScanner – AbstractAntiSamyScanner is called which is as below
private static ResourceBundle getResourceBundle() {
try {
return ResourceBundle.getBundle("AntiSamy", Locale.getDefault()); }
catch (MissingResourceException mre) {
}
return ResourceBundle.getBundle("AntiSamy", new Locale("en", "US"));
}
This is where the exception is thrown because, tomcat for some reason can’t load resource bundle – AntiSamy_en_US.properties file present inside the jar file at the root level.
Since this is error in static block, ExceptionInInitializer is thrown ultimately leading to NoClassDefFoundError.
Below are the two exception when looked at together – we can see that NoClassDefFoundError is caused due to exception in static init block of AbstractAntiSamyScanner.
SEVERE: Servlet.service() for servlet [jsp] in context with path [/app] threw exception [javax.servlet.ServletException: java.lang.NoClassDefFoundError: Could not initialize class org.owasp.validator.html.scan.AntiSamyDOMScanner] with root cause
java.lang.NoClassDefFoundError: Could not initialize class org.owasp.validator.html.scan.AntiSamyDOMScanner
at org.owasp.validator.html.AntiSamy.scan(AntiSamy.java:93)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:124)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
java.lang.NoClassDefFoundError: Could not initialize class org.owasp.validator.html.scan.AntiSamyDOMScanner StackTrace: javax.servlet.ServletException: java.lang.NoClassDefFoundError: Could not initialize class org.owasp.validator.html.scan.AntiSamyDOMScanner at
WE have tried copying the Antisamy.properties under Tomcat lib and also WEB-INF/classes but it didnt work.
Any thoughts on what could cause the AbstractAntiSamyScanner not find the resource bundle within the jar?
Related
I have a Java Application that uses Armeria for a Web Service. When I create my Hibernate SessionFactory in the main method it works fine. But I am trying to create the SessionFactory when a certain Http Endpoint is called. In the handler method the session factory can not be created
Exception in thread "Thread-1" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
Caused by: javax.xml.bind.JAXBException
- with linked exception:
[java.lang.ClassNotFoundException: com/sun/xml/bind/v2/ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:226)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:441)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
... 17 more
Caused by: java.lang.ClassNotFoundException: com/sun/xml/bind/v2/ContextFactory
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:577)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:224)
... 21 more
All I could find about this error is that JaxB is not provided for Java > 8 but i am using Java 8 and it works fine if I just create it at Application launch.
I believe it's some sort of class path conflict. In Java 8, the following code fails with ClassNotFoundException: com/sun/xml/bind/v2/ContextFactory, as reported in the question:
public class MyService {
#Get("/start")
public HttpResponse start() throws Exception {
final StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder().configure();
...
}
}
However, the problem goes away after upgrading to a newer Java version, such as Java 11.
Fortunately, the problem can be worked around by specifying the context class loader explicitly:
#Get("/start")
public HttpResponse start() throws Exception {
Thread.currentThread().setContextClassLoader(MyService.class.getClassLoader());
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
final StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder().configure();
...
}
I am working on an application where in a bean's post construct method i am adding some logic to create an object. Now , what I want to do is, if there is an exception and the creation of the object has some error, then do not let the application start up. Yes, I can see an exception being thrown on the console when it starts up, if there is any issue with the construction of an object, but I would like something better than that to inform me that construction of an object has failed, and what better criteria than application failing to start up.
Any help is much appreciated.
Thank you in advance.
You can look for FailureAnalyzer for this type of requirements where additional information will given in case application start failes. If any exception raised during application start, all the FailureAnalyzer classes will be invoked in a sequence. If any of the FailureAnalyzer class returning FailureAnalysis object then the exception won't be propagated to further FailureAnalysis classes.
Please make sure you register your FailureAnalysis class in resource/META-INF/spring.factories file.
#Component
public class SomeObject {
#PostConstruct
public void init() throws Exception {
throw new Exception("SomeObject init threw exception");
}
}
public class ObjConstructionFailureAnalyzer extends
AbstractFailureAnalyzer<BeanCreationException> {
#Override
protected FailureAnalysis analyze(Throwable rootFailure,
BeanCreationException cause) {
System.out.println("\n===>ObjConstructionFailureAnalyzer::analyze()\n");
String desciption = "Object creation failed, [Reason]: " +
cause.getMessage();
String action = "Please handle exceptions in your init methods";
return new FailureAnalysis(desciption, action, cause);
}
}
In spring.factories file
org.springframework.boot.diagnostics.FailureAnalyzer=examples.stackoverflow.ObjConstructionFailureAnalyzer
Exception stacktrace
===>ObjConstructionFailureAnalyzer::analyze()
2018-02-21 10:16:59.552 ERROR 9500 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Object creation failed, [Reason]: Error creating bean with name
'someObject': Invocation of init method failed; nested exception is
java.lang.Exception: SomeObject init threw exception
Action:
Please handle exceptions in your init methods
You can additionally visit here for code sample.
I'm working with Play framework 1.4.3 and my problem is that i created a new folder inside in the controllers folder and in this new folder added new controllers class and I did the same with a folder of the views but when in my html , i tried to declared in the href of a tag ancla the route , this not it found my controller created, only found the controller for default "Application.java".
Example:
This is my folder hierarchy
I can use a controller inside a folder in the controllers folder with Play Framework 1.4.3?
This is my MyServicesControlle:
package controllers.myServices;
import play.mvc.Controller;
public class MyServicesController extends Controller {
public static void index() {
render();
}
}
when i write the whole path in a tag ancla:
my services
throws this exception:
19:11:34,868 ERROR ~
#73mb1o6aa
Internal Server Error (500) for request GET /application/index
Oops: PatternSyntaxException
An unexpected error occured caused by exception PatternSyntaxException: group redeclaration controller; use ({=name}...) for group reassignments
play.exceptions.UnexpectedException: Unexpected Error
at play.Invoker$Invocation.onException(Invoker.java:245)
at play.Invoker$Invocation.run(Invoker.java:307)
at Invocation.HTTP Request(Play!)
Caused by: jregex.PatternSyntaxException: group redeclaration controller; use ({=name}...) for group reassignments
at jregex.Term.makeTree(jregex/Term.java:299)
at jregex.Term.makeTree(jregex/Term.java:219)
at jregex.Term.makeTree(jregex/Term.java:206)
at jregex.Pattern.compile(jregex/Pattern.java:164)
at jregex.Pattern.<init>(jregex/Pattern.java:150)
at jregex.Pattern.<init>(jregex/Pattern.java:108)
at play.mvc.Router$Route.compute(Router.java:828)
at play.mvc.Router.getRoute(Router.java:142)
at play.mvc.Router.appendRoute(Router.java:126)
at play.mvc.Router.parse(Router.java:208)
at play.mvc.Router.parse(Router.java:173)
at play.mvc.Router.load(Router.java:53)
at play.mvc.Router.detectChanges(Router.java:232)
... 1 more
first it was necessary to reference the folder where the controller was located, followed by the name of the controller and then the action.
Following the previous example:
my services
I've spent most of my day on something that supposedly is very simple on EJB 3 in Tomee.
I have a Test.jar in the apps folder, and in it, there is a stateless bean with a method called testMethod().
Bean: TestBean.java
Remote Interface: Test.java
In web application TestClient.java:
public String testMethod(){
try {
InitialContext ctx = new InitialContext();
Test test = (Test) ctx.lookup("Test");
test.testMethod();
//System.out.println("Output from JavaClient");
} catch (NamingException e){
e.printStackTrace();
}
}
and a JSP, which calls the TestClient class for execution.
I get the following error: javax.naming.NameNotFoundException: Name [Test] is not bound in this Context. Unable to find [Test].
I have tried TestBean/remote in the context object with similar results.
Both the jar and the war are running in the same tomee container. If somebody can shed some light on what I am doing wrong, it will be greatly appreciated.
the correct jndi name is in the logs (look for "Jndi(").
will likely be java:global//TestBean!Test or something like that
I have a web-app (Tomcat 6, log4j 1.2.16), which starts with a listener. Undeploying the application throws the following exception:
INFO (HqListener.java:28) - HqListener exited!
log4j:ERROR log4j called after unloading, see http://logging.apache.org/log4j/1.2/faq.html#unload.
java.lang.IllegalStateException: Class invariant violation
at org.apache.log4j.LogManager.getLoggerRepository(LogManager.java:199)
at org.apache.log4j.LogManager.getLogger(LogManager.java:228)
at org.apache.log4j.Logger.getLogger(Logger.java:117)
at com.mchange.v2.log.log4j.Log4jMLog.getMLogger(Log4jMLog.java:51)
at com.mchange.v2.log.MLog.getLogger(MLog.java:145)
at com.mchange.v2.sql.SqlUtils.<clinit>(SqlUtils.java:37)
at com.mchange.v2.c3p0.DataSources.pooledDataSource(DataSources.java:290)
at com.mchange.v2.c3p0.DataSources.pooledDataSource(DataSources.java:316)
at org.hibernate.connection.C3P0ConnectionProvider.configure(C3P0ConnectionProvider.java:181)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:143)
at org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:51)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:90)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2863)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2859)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at net.hq.util.Db.init(Db.java:15)
at net.hq.process.ConnectionGateway.run(ConnectionGateway.java:89)
at java.lang.Thread.run(Thread.java:662)
Exception in thread "HQ Gateway Thread" java.lang.NullPointerException
at net.hq.process.ConnectionGateway.run(ConnectionGateway.java:129)
at java.lang.Thread.run(Thread.java:662)
Jul 3, 2011 3:03:53 AM org.apache.catalina.core.StandardContext stop
HqListener.java is my listener and it reports a successful shutdown.
How do I get rid of this exception message?
Check this jira bug for your solution: http://java.net/jira/browse/GLASSFISH-16767
Similar resolved issue on stackoverflow here: Undeploying a Grails App from Glassfish gets a Class invariant violation
Setting the property
<jvm-options>
-Dorg.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false
</jvm-options>
in the domain.xml file in Glassfish resolves the issue; not certain where to set this in Tomcat, perhaps server.xml?
The way I solved this problem (in glassfish environment) is to avoid declaring the logger as static, e.g.
private static final Logger logger = LoggerFactory.getLogger(BootStrapListener.class);
If you remove static from the above declaration, you will no longer get the above error.