Java EE ClassNotFoundException for MysqlDataSource. What am I doing wrong? - java

I want to connect to my MySQL database, and query some data. I am getting the following error:
2016-02-28 10:42:17,438] Artifact JavaEESecurity:war exploded: Error during artifact deployment. See server log for details. [2016-02-28 10:42:17,438] Artifact JavaEESecurity:war exploded: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"JavaEESecurity_war_exploded.war\".INSTALL"
=> "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"JavaEESecurity_war_exploded.war\".INSTALL: WFLYSRV0153: Failed to process phase INSTALL of deployment \"JavaEESecurity_war_exploded.war\"
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException:
java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource from
[Module \"deployment.JavaEESecurity_war_exploded.war:main\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource from [Module \"deployment.JavaEESecurity_war_exploded.war:main\" from Service Module Loader]"}}
I'm using maven in my project. This is my pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.own.group</groupId>
<artifactId>myOwnArtifactId</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.13</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<data-source>
<name>java:global/JavaEESecurity/myDS</name>
<class-name>com.mysql.jdbc.jdbc2.optional.MysqlDataSource</class-name>
<server-name>localhost</server-name>
<database-name>mncpp</database-name>
<user>root</user>
<transactional>true</transactional>
<initial-pool-size>2</initial-pool-size>
<max-pool-size>10</max-pool-size>
<min-pool-size>5</min-pool-size>
<max-statements>0</max-statements>
</data-source>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
And this is my bean class, in which I'd like to access my database:
#Named("questionListBean")
#RequestScoped
public class QuestionListBean {
List<String> questions;
#Resource(lookup = "java:global/JavaEESecurity/myDS")
DataSource ds;
public List<String> getQuestions() {
try (Connection connection = ds.getConnection()) {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT question FROM questions");
questions = new ArrayList<>();
while(rs.next()) {
questions.add(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return questions;
}
}
Thanks in advance!

The ClassNotFoundException means that the Java runtime (the JVM) that runs your application server (Java EE server) is somehow not able to find the class com.mysql.jdbc.jdbc2.optional.MysqlDataSource. This class is a part of the MySQL JDBC Driver. Since this class is not available when your bean's method getQuestions() is called, the exception is thrown.
There are multiple ways in which you can fix this:
Make your application self contained. This means that you bundle
all the classes that your application needs along with it. This is
the whole point of a Java .ear (enterprise application archive).
Doing this (in theory) means that your application can be ported
rather easily. To do this, you can assemble your app in such a way
that you specify a runtime dependency on MySQL connector (see
mvnrepository
for the snippet and add <scope>runtime</scope>) in a
<dependency> element in your pom.xml. Then you can use the Maven
ear
plugin if you are assembling a .ear or Maven war plugin if you are assembling a .war
to bundle everything up.
Make the MySQL driver jar a part of your application server's classpath. That way, other applications can leverage those classes (you may have more than one app using MySQL, for instance). Application servers have this facility so that these classes are made available to apps. Read up your app server's documentation to see how to do it.

Related

#PostConstruct method called twice when making the module containing the EJB a dependency of another module

My maven project structure looks like this:
test_project-parent
|test_project-ejb.jar
|test_project-depl.jar
|test_project-web.war
|test_project-ear.ear
My 3 modules: ejb, depl and web are packaged into the EAR.
I have an EJB in my ejb module that looks like this:
#Startup
#Singleton
public class StartupBean {
#PersistenceContext
private EntityManager em;
#PostConstruct
private void sayHello () {
System.out.println("HELLO !!!");
}
}
My problem is that that the sayHello() method is executed twice.
Here's the output from the log:
00:16:13,803 INFO [stdout] (ServerService Thread Pool -- 113) HELLO !!!
00:16:13,803 INFO [stdout] (ServerService Thread Pool -- 117) HELLO !!!
My ejb module is a dependency of my web module.
When I remove the dependency it works fine (the method is called once as it should be).
The pom.xml of my web module looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.testing</groupId>
<artifactId>test_project</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>test_project-web</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>test_project-ejb</artifactId>
<version>${test_project.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
</dependency>
</dependencies>
</project>
NOTE: I have read all the related posts and found no answer
I found my error. I needed to change the scope of my dependency to provided, because the way it was the dependency was packaged inside the war archive in it's lib folder. So, basically, my ejb module was deployed twice, and hence the double execution of the #PostConstruct method.
I added <scope>provided</scope> to the ejb dependency inside my web module pom.xml and everything works fine. The ejb module is no longer packaged inside the lib folder of the war archive and the #PostConstruct method is called only once.

Issue with deploying maven project with multiple modules to Tomcat 7.0

So I have two modules, let's call them moduleA and moduleB. My goal is to deploy both of them to Tomcat. Here is what I have done:
parent pom.xml
<project>
....
<artifactId>parentModule</artifactId>
<packaging>pom</packaging>
<modules>
<module>moduleA</module>
<module>moduleB</module>
</modules>
....
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.4.3</version>
</dependency>
</dependencies>
</dependencyManagement>
...
</project>
moduleA pom.xml
<project>
...
<parent>
...
<artifactId>parentModule</artifactId>
</parent>
...
</project>
moduleB pom.xml
<project>
...
<parent>
...
<artifactId>parentModule</artifactId>
</parent>
...
</project>
The directory structure looks like this
Users/swidjaja/dev/parentProject
pom.xml
moduleA
pom.xml
moduleB
pom.xml
These are the steps that I do to deploy it to Tomcat
[On Terminal] mvn clean install
[On Terminal] mvn eclipse:eclipse
[Eclipse] import project
[Eclipse] Create new Tomcat 7.0 server and add the two modules to Resources [Eclipse] Run Tomcat server
Running the Tomcat server, I got the following exception
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'awsCredentials' defined in file [/Users/swidjaja/dev/parentProject/moduleA/target/moduleA-SNAPSHOT/WEB-INF/classes/applicationContext.xml]: null
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:220)
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:84)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:656)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
And here is what the file applicationContext.xml looks like
<beans>
<bean id="awsCredentials" class="com.amazonaws.auth.BasicAWSCredentials">
<constructor-arg index="0" value="accessKey" />
<constructor-arg index="1" value="secretKey" />
</bean>
</beans>
My guess here is that somehow I didn't deploy it correctly. The BasicAWSCredentials class is part of aws-java-sdk which is defined as dependency in parent pom.xml and it looks like this module is not deployed correctly to Tomcat.
What did I do wrong in my steps? What will be the correct way to deploy such project? I've been struggling with this for 2 days now.
Any help is highly appreciated. Many Thanks!

weblogic 12c deployment failure

I'm migrating from Weblogic 11g to 12c, during the deployment process it fails and shows the following error:
Caused by: weblogic.application.naming.ReferenceResolutionException: [J2EE:160199]Error resolving ejb-ref "ejb/BizRuleFacade" from module "BizAgi-ejb.jar" of application "BizAgi-ear-Weblogic". The ejb-ref does not have an ejb-link and the JNDI name of the target bean has not been specified. Attempts to automatically link the ejb-ref to its target bean failed because multiple EJBs in the application were found to implement the "BizAgi.bpm.rules.entities.BizRuleFacade" interface, including BizAgi-war.war/BizRuleFacadeBean, BizAgi-ejb.jar/BizRuleFacadeBean. Specify a qualified ejb-link for this ejb-ref to indicate which EJB is the target of this ejb-ref.
My web.xml file looks like this:
<ejb-local-ref>
<ejb-ref-name>ejb/BAScopeLogFacade</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>BizAgi.PAL.historylog.entities.BAScopeLogFacade</local>
<ejb-link>BizAgi-ejb.jar#BAScopeLogFacadeBean</ejb-link>
</ejb-local-ref>
The BizAgi-ejb.jar is a module inside the ear (BizAgi-ear-Weblogic.ear).
How can i properly deploy my application?
Thank you so much everybody, I've finally found the solution, it is to simply delete/remove the META-INF/MANIFEST.MF file from the .war file. That way the EJBs aren't double referenced.
1.Add below dependency in Ear Pom.xml
<dependency>
<groupId>com.example</groupId>
<artifactId>ejbModel</artifactId>
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
2.In Ear pom.xml in modules add ejb module
<modules>
<ejbModule>
<groupId>com.example</groupId>
<artifactId>ejbModel</artifactId>
<bundleFileName>ejbModel-1.0-SNAPSHOT.jar</bundleFileName>
</ejbModule>
.......
</modules>
3.Change scope of ejbmodel dependency to provided in application pom.xml
<dependency>
<groupId>com.example</groupId>
<artifactId>ejbModel</artifactId>
<version>1.0-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
4.add persistence.xml of ejbmodel application to resource folder
Make sure that the same EJBs are not loaded multiple times in your deployment. You can check this by using the weblogic console (AdminServer) and checking the EJBs of the deployment (by clicking the little "+" sign next to the deployment that is failing int the deployments overview).
In my case I had to fix the maven dependencies (by setting one dependency of one project to "provided") so that it did not load the same EJB twice.
ERROR:
weblogic.management.DeploymentException: weblogic.application.naming.ReferenceResolutionException: [J2EE:160199]Error resolving ejb-ref "com.xxx.xxx.xxx.xxx.xxx.xxx.XXXX/xxxRemote" from module
"XXX-X.X.X.war" of application "XXX-X.X.X". The ejb-ref does not have an ejb-link and the JNDI name of the target Bean has not been specified.
SOLUTION:
1 SOLUTION: pom.xml (Web Project)
<dependencies>
<dependency>
<groupId>co.xx.cxxxx</groupId>
<artifactId>xxxxx-ejb</artifactId>
<version>1.0</version>
<type>ejb</type>
<scope>provided</scope>
</dependency>
<dependencies>
2 SOLUTION: Delete xxxxx-ejb.jar
xxxx.ear > xxxx.war > WEB-INF > lib > xxx-ejb.jar [remove]
3 Conclusion:
This is because there is a double reference to the ejb.jar, therefore the best way to control this is by saying in pom (web) that the is of type EJB, in order to take the (ejb.jar ) from the parent (EAR, where the ejb module is added).
I hope to be of help

Adding Struts2 Filters Causes Blank Page

I'm attempting to get a basic Struts2 application (using tomcat, building with maven) up and running. Tomcat and Maven are both working correctly; the page is served normally until I add some Struts filters into my web.xml (located at src/main/webapp/WEB-INF). Here's the code for my web.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<web-app>
<display-name>app</display-name>
<description>tagline</description>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Additionally, here is the code for my struts.xml (located at src/main/resources:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="app" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
</package>
</struts>
My catalina.log has the following error messages:
12-Jan-2014 15:33:20.256 SEVERE [localhost-startStop-16] org.apache.catalina.core.StandardContext.startInternal Error filterStart
12-Jan-2014 15:33:20.256 SEVERE [localhost-startStop-16] org.apache.catalina.core.StandardContext.startInternal Context [/app] startup failed due to previous errors
I've just noticed another issue present in catalina.log that only shows upon starting up tomcat:
13-Jan-2014 20:19:57.465 SEVERE [main] org.apache.catalina.core.AprLifecycleListener.init An incompatible version 1.1.27 of the APR based Apache Tomcat Native library is installed, while Tomcat requires version 1.1.29
The really weird thing is that the tomcat-native.tar.gz in my apache-tomcat-ver/bin is version 1.1.29.
Additionally, my localhost.log has a mess of errors:
13-Jan-2014 20:20:04.780 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.filterStart Exception starting filter struts2
Unable to load configuration. - bean - jar:file:/usr/local/apache-tomcat/apache-tomcat-8.0.0-RC10/webapps/symIOsis/WEB-INF/lib/struts2-portlet-plugin-2.3.16.jar!/struts-plugin.xml:31:133
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:501)
at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:57)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4646)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5274)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:702)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:699)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1763)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: Unable to load configuration. - bean - jar:file:/usr/local/apache-tomcat/apache-tomcat-8.0.0-RC10/webapps/symIOsis/WEB-INF/lib/struts2-portlet-plugin-2.3.16.jar!/struts-plugin.xml:31:133
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:445)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:489)
... 18 more
Caused by: Unable to load bean: type:org.apache.struts2.components.UrlRenderer class:org.apache.struts2.components.PortletUrlRenderer - bean - jar:file:/usr/local/apache-tomcat/apache-tomcat-8.0.0-RC10/webapps/symIOsis/WEB-INF/lib/struts2-portlet-plugin-2.3.16.jar!/struts-plugin.xml:31:133
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.register(XmlConfigurationProvider.java:245)
at org.apache.struts2.config.StrutsXmlConfigurationProvider.register(StrutsXmlConfigurationProvider.java:102)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:234)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 20 more
Caused by: java.lang.NoClassDefFoundError: javax/portlet/PortletMode
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2493)
at java.lang.Class.getDeclaredConstructors(Class.java:1901)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.register(XmlConfigurationProvider.java:235)
... 23 more
Caused by: java.lang.ClassNotFoundException: javax.portlet.PortletMode
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1286)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1128)
... 27 more
To me this looks like a dependency issue, however struts2-portlet-plugin-2.3.16.java exists in that location. Does anyone know how to resolve this?
Edit: I've also added the struts2-portlet-plugin as a maven dependency in hopes that it would resolve the problem. No avail, the same errors are still appearing.
Also, here's the requested pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company.webapp</groupId>
<artifactId>webapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>app</finalName>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.16</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-portlet-plugin</artifactId>
<version>2.3.16</version>
</dependency>
</dependencies>
</project>
After much headache and plenty of circles, I seem to have figured out the issue. Apparently, when building with maven, I do not need to copy the .jars from the distributed struts-ver/lib into my WEB-INF/lib folder. It's always something simple, eh?

Spring application with embedded jetty can't find webdefault.xml if running from jar

I have spring application which uses embedded Jetty instance.
project
| src
| controller
| webapps
| jsp
| WEB-INF
| web.xml
| applicationContext.xml
| spring-servlet.xml
my jar has the same tree structure but I keep getting
d:\test>java -jar springtest.jar
2011-11-22 15:37:02.576:INFO::jetty-7.x.y-SNAPSHOT
2011-11-22 15:37:02.686:WARN::Failed startup of context o.e.j.w.WebAppContext{/,[file:/C:/Users/me/AppData/Local/Temp/jetty-0.0.0.0-8080-webapps-_-any-/webinf
/, jar:file:/d:/test/springtest.jar!/org/jcvi/webapps/]}
java.io.FileNotFoundException: d:\test\org\eclipse\jetty\webapp\webdefault.xml (The system cannot find
the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:70)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:161)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:653)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
at org.eclipse.jetty.xml.XmlParser.parse(XmlParser.java:188)
at org.eclipse.jetty.xml.XmlParser.parse(XmlParser.java:204)
at org.eclipse.jetty.webapp.Descriptor.parse(Descriptor.java:60)
at org.eclipse.jetty.webapp.WebDescriptor.parse(WebDescriptor.java:140)
at org.eclipse.jetty.webapp.MetaData.setDefaults(MetaData.java:141)
at org.eclipse.jetty.webapp.WebXmlConfiguration.preConfigure(WebXmlConfiguration.java:46)
at org.eclipse.jetty.webapp.WebAppContext.preConfigure(WebAppContext.java:412)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:258)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
at org.jcvi.ServerRunner.startServer(ServerRunner.java:83)
at org.jcvi.MainServer.main(MainServer.java:18)
2011-11-22 15:37:02.748:INFO::Started SelectChannelConnector#0.0.0.0:8080 STARTING
I have following java class which runs jetty server instance
String webDir = this.getClass().getClassLoader().getResource("webapps").toExternalForm();
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setContextPath("/");
context.setResourceBase(webDir);
context.setParentLoaderPriority(true);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
server.setHandler(context);
server.start();
my web.xml looks like
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
this application runs fine if I run inside IDE, but it fails with JAR.
How can I resolve this issue so that I can have single jar file which has the web application in it?
I had a similar problem and I solve it with this main class implementation:
private static final int PORT = 8080;
private static final String WAR_LOCATION = "src/webapps"; //in your case I guess
private static final String CONTEXT_PATH = "/movence"; //change it if you want
public static void main(String[] args) throws Exception {
Server server = new Server();
WebAppContext context = new WebAppContext();
SocketConnector connector = new SocketConnector();
setupConnector(connector);
setupContext(server, context);
setupServer(server, context, connector);
startServer(server);
}
private static void startServer(Server server) throws Exception, InterruptedException {
server.start();
server.join();
}
private static void setupServer(Server server, WebAppContext context, SocketConnector connector) {
server.setConnectors(new Connector[] { connector });
server.addHandler(context);
}
private static void setupConnector(SocketConnector connector) {
connector.setPort(PORT);
}
private static void setupContext(Server server, WebAppContext context) {
context.setServer(server);
context.setContextPath(CONTEXT_PATH);
context.setWar(WAR_LOCATION);
}
It seems that jetty's trying to parse the web.xml (descriptor) file, but thinks its in
.../...../...../webdefault.xml
or something like that.
You should explicitly set the web.xml path:
context.setDescriptor("WEB-INF/web.xml"); `
or, assuming that your jar really does include the aformentioned 'project' dir (which isn't standard jar intrernal layout):
context.setDescriptor("project/src/webapps/WEB-INF/web.xml");
From #Trein's post, setting the WAR_LOCATION is important. I have seen jetty failing to deploy the web app when this is missing.
Assuming that you are using Jetty to test your app, if you are using Maven POM below is how I test my web app
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-servlet-tester</artifactId>
<version>6.1.22</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.19</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>tomcat</id>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.22</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
<contextPath>/</contextPath>
<webAppSourceDirectory>src/main/webapp</webAppSourceDirectory>
<systemProperties>
<systemProperty>
<name>RESOURCE_PATH</name>
<value>${project.build.outputDirectory}</value>
</systemProperty>
</systemProperties>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>9090</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
</configuration>
<executions>
<execution>
<phase>test-compile</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>package</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
To run the webapp you can either run mvn jetty:start or run mvn package. This starts the Jetty server on port 9090 and runs the tests (run your http based tests here) and shutdown the server/webapp.
If you want to run as standalone webapp, use mvn jetty:start and use your webapp just like any webapp container.
This all assumes you are using Maven. The code above provided by #Trein does the same programatically and the one I provided is the maven configuration equivalent of the above.
Note: You shouldn't worry about webdefault.xml as the default is already packaged in the jetty jar file. You should use your own webdefault.xml only when you need to extend/alter the defaults. There is either something wrong with your Jetty jar (if its reporting this or something to do with your CLASSPATH settings)
Found this github project :
https://github.com/steveliles/jetty-embedded-spring-mvc
This gives a basic startup template project based on maven. It embedded jetty with spring mvc.
Good place to start from scratch or to compare and debug what's wrong with current implementation.
The author has done a nice documentation here :
http://steveliles.github.io/setting_up_embedded_jetty_8_and_spring_mvc_with_maven.html
Probably a little bit out-dated. However I recently encountered this problem in the context of embedding Jetty in an Eclipse OSGi application using the version of Jetty packaged with Eclipse (Jetty 8.x).
The way I sorted this out is the following :
Get the URL of the webdefault.xml relative to the org.eclipse.jetty.webapp bundle
Pass this URL to the context default descriptor
Bundle bundle = FrameworkUtil.getBundle(WebAppContext.class);
Enumeration<URL> urls = bundle.findEntries("/", "webdefault.xml", true);
String webdefaultURL = urls.nextElement().toExternalForm(); // Should check returned value
mycontext.setDefaultsDescriptor(webdefaultURL);
Hope it helps
seb
Your webdefault.xml (Jetty) is missing:
java.io.FileNotFoundException: d:\test\org\eclipse\jetty\webapp\webdefault.xml
see "What is webdefault.xml?"
If you have a custom location, you need to add it:
context.setDefaultsDescriptor("/my/path/to/webdefault.xml");

Categories

Resources