I want to use connection pooling with Jetty 6, but so far it is giving my a lot of troubles.
I do
InitialContext context = new InitialContext();
It doesn't throw an exception, but when I inspect the context variable I see this, which is kinda suspect:
Notice the defaultInitCtx=null.
The line after I try to get a datasource with:
Datasource dataSource = (DataSource)context.lookup("java:comp/env/MySQLDB");
and now I get an exception saying that there is no initial context:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
Obviously, I must be doing something wrong, but I just can't find what...
If anyone could help, I would appreciate it!
Here is my jetty.xml:
<Configure id="Server" class="org.mortbay.jetty.Server">
... (all default except those lines I added)
<Call name="setAttribute">
<Arg>org.eclipse.jetty.webapp.configuration</Arg>
<Arg>
<Array type="java.lang.String">
<Item>org.eclipse.jetty.webapp.WebInfConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.MetaInfConfiguration</Item>
<Item>org.eclipse.jetty.webapp.FragmentConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JettyWebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.TagLibConfiguration</Item>
</Array>
</Arg>
</Call>
</Configure>
My WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Test</display-name>
<servlet>
<description></description>
<display-name>Default</display-name>
<servlet-name>Default</servlet-name>
<servlet-class>Default</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Default</servlet-name>
<url-pattern>/Default</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>MySQLDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
My WEB-INF/jetty-env.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
<Configure class="org.mortbay.jetty.webapp.WebAppContext">
<Set name="ConfigurationClasses">
<Ref id="plusConfig"/>
</Set>
<!-- MySql datasource -->
<New id="MySQLDB" class="org.mortbay.jetty.plus.naming.Resource">
<Arg></Arg>
<Arg>MySQLDB</Arg>
<Arg>
<New class="org.apache.commons.dbcp.BasicDataSourceFactory">
<Set name="driverClassName">com.mysql.jdbc.Driver</Set>
<Set name="url">jdbc:mysql://host_ip</Set>
<Set name="username">username</Set>
<Set name="password">password</Set>
<Set name="auth">Container</Set>
<Set name="maxActive">-1</Set>
<Set name="maxIdle">30</Set>
<Set name="maxWait">10000</Set>
<Set name="minEvictableIdleTimeMillis">600000</Set>
<Set name="name">MySQLDB</Set>
<Set name="removeAbandoned">true</Set>
<Set name="removeAbandonedTimeout">5000</Set>
<Set name="timeBetweenEvictionRunsMillis">10000</Set>
<Set name="type">javax.sql.DataSource</Set>
</New>
</Arg>
</New>
You have to create jndi.properties file with values for factory to be used for initializing and put the file in the class path.
If you are using jetty 7, the properties will be
java.naming.factory.url.pkgs=org.eclipse.jetty.jndi
java.naming.factory.initial=org.eclipse.jetty.jndi.InitialContextFactory
PS: I have also come across with the problem and fixed it this way. I was using jetty 7 for my purpose. If you are using older versions, just identify the values for the same(if they are different).
For jetty 6, I believe the properties should be (look at the API) (I haven't tested this)
java.naming.factory.url.pkgs=org.mortbay.naming
java.naming.factory.initial=org.mortbay.naming.InitialContextFactory
Later in your client code, you can check whether the factory is initialized properly
try {
InitialContext ic = new InitialContext();
return (DataSource) ic.lookup("java:comp/env/MySQLDB");
} catch (NamingException e) {
logger.error("JNDI error while retrieving datasource" , e);
throw new Exception(e);
}
Related
I'm trying to configure a jetty-servlet in java using maven. I've create a jetty.xml file with the following entries
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<Set name="ThreadPool">
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<Set name="minThreads">10</Set>
<Set name="maxThreads">200</Set>
<Set name="detailedDump">false</Set>
</New>
</Set>
</Configure>
upon running the server
mvn jetty:run
I see the error
[WARNING] Config error at <Set name="ThreadPool">
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool"><Set
name="minThreads">10</Set><Set name="maxThreads">200</Set><Set
name="detailedDump">false</Set></New>
</Set>
but cannot figure out what the problem actually is. I've also included jetty-util as a dependency in the pom.xml file. I'm using jetty version 9.4.12.v20180830 and java 8. Thanks for any help!
ThreadPool is a constructor argument for Server.
See: Javadoc for org.eclipse.jetty.server.Server
It's not a field and/or setter on Server, so you cannot use the <Set name="ThreadPool"> syntax.
Instead of replacing the threadpool, just "Get" the existing one and change settings on it.
Eg:
<Get name="ThreadPool">
<Set name="minThreads" type="int">10</Set>
<Set name="maxThreads" type="int">200</Set>
<Set name="detailedDump">false</Set>
</Get>
I have set up Jetty 9.3 with two XML context configurations. One for static content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
<Set name="contextPath">/static</Set>
<Set name="handler">
<New class="org.eclipse.jetty.server.handler.ResourceHandler">
<Set name="resourceBase">/home/user/static</Set>
<Set name="directoriesListed">true</Set>
</New>
</Set>
</Configure>
and one for a web application (WAR file):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/webapp</Set>
<Set name="war">/home/user/webapp.war</Set>
</Configure>
I then used this answer to set up Jetty to forward HTTP requests to HTTPS. More specifically, I added the following to jetty/etc/webdefault.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>Everything</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
and added the following to my HttpConfiguration in jetty/etc/jetty.xml:
<Call name="addCustomizer">
<Arg>
<New class="org.eclipse.jetty.server.SecureRequestCustomizer" />
</Arg>
</Call>
This works perfectly for my web application (i.e. accessing the server through HTTP at '/webapp' will redirect to HTTPS), but doesn't seem to affect the static content served under '/static'. I assume this is because the setting added to webdefault.xml only applies to web applications since they have an applicable web.xml file.
How can I set up HTTP requests to redirect to HTTPS for all my pages served as static content?
As far as I could tell (e.g., based on this SO and this SF and the Jetty Docs) it's not configurable for static content, only for webapps.
What you could do (that does not mean that you should do it this way) is that you create a custom #PreMatching filter if you are using JAX-RS or a custom MessageHandler if you are using JAX-WS which does the redirection programatically (e.g., through returning an HTTP 301).
I have a Spring Hibernate webapp with HikariCP running on Jetty with the following context file located in the base webapps folder:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure id='testServer' class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/myServer</Set>
<Set name="war">C:\mypath\myServer.war</Set>
<New id="testDataSource" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid="testServer"/></Arg>
<Arg>jdbc/myDB</Arg>
<Arg>
<New class="com.zaxxer.hikari.HikariDataSource">
<Arg>
<New class="com.zaxxer.hikari.HikariConfig">
<Set name="connectionTestQuery">SELECT 1</Set>
<Set name="dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</Set>
<Set name="maximumPoolSize">20</Set>
<Set name="connectionTimeout">30000</Set>
<Set name="username">user</Set>
<Set name="password">password</Set>
<Call name="addDataSourceProperty">
<Arg>url</Arg>
<Arg>jdbc:mysql://localhost/mydb?zeroDateTimeBehavior=convertToNull</Arg>
</Call>
<Call name="addDataSourceProperty">
<Arg>user</Arg>
<Arg>user</Arg>
</Call>
<Call name="addDataSourceProperty">
<Arg>password</Arg>
<Arg>password</Arg>
</Call>
<Call name="addDataSourceProperty">
<Arg>cachePrepStmts</Arg>
<Arg>true</Arg>
</Call>
<Call name="addDataSourceProperty">
<Arg>prepStmtCacheSize</Arg>
<Arg>250</Arg>
</Call>
<Call name="addDataSourceProperty">
<Arg>prepStmtCacheSqlLimit</Arg>
<Arg>2048</Arg>
</Call>
<Call name="addDataSourceProperty">
<Arg>useServerPrepStmts</Arg>
<Arg>true</Arg>
</Call>
</New>
</Arg>
</New>
</Arg>
</New>
</Configure>
In my applicationContext.xml file I am able to successfully lookup and use the datasource using the following:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/myDB"/>
The problem I am having is that when I hot deploy a new war file, the HikariCP datasource connection pool is left open, and the connections to the database remain.
I am trying to lookup and close the datasource in the contextDestroyed() method of a ServletContextListener using something like the following code:
try
{
initContext = new InitialContext();
envContext = (Context) initContext.lookup("java:comp/env");
ds = (DataSource) envContext.lookup("jdbc/myDB");
if (ds.getConnection() == null)
{
throw new RuntimeException("Failed to find the JNDI Datasource");
}
logger.info("JNDI HikariDataSource : " + System.identityHashCode(ds.getClass()));
logger.info("Local HikariDataSource: " + System.identityHashCode(HikariDataSource.class));
HikariDataSource hds = (HikariDataSource) ds;
hds.close();
} catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
However I am getting the following exception when trying to cast the DataSource to a HikariDataSource:
java.lang.ClassCastException: com.zaxxer.hikari.HikariDataSource cannot be cast to com.zaxxer.hikari.HikariDataSource
I am also getting different identityHashCodes above which leads me to believe that I have 2 classloaders that have loaded separate instances of the HikariDataSource class. We would like the datasource to be specific to the webapp's context and to close it on hot deployment. What do I need to change to make this happen?
I'm trying to set up a JNDI DataSource in Jetty. In the start.ini file I have add the jetty-plus.xml file and the Options look like this:
OPTIONS=Server,resources,websocket,ext,plus,annotations
Then I'm adding the resource in my context file:
<New id="Traildevils" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg/>
<Arg>jdbc/Traildevils</Arg>
<Arg>
<New class="org.postgresql.ds.PGConnectionPoolDataSource">
<Set name="User">recom</Set>
<Set name="Password">recom</Set>
<Set name="DatabaseName">Traildevils</Set>
<Set name="ServerName">localhost</Set>
<Set name="PortNumber">5432</Set>
</New>
</Arg>
</New>
The postgresql-9.1-901.jdbc4.jar file is in the WEB-INF/lib of my war file.
When I'm now trying to start the jetty I get the following error:
2012-04-12 12:58:09.723:WARN:oejx.XmlConfiguration:Config error at
<New id="Traildevils" class="org.eclipse.jetty.plus.jndi.Resource"><Arg/>
<Arg>jdbc/Traildevils</Arg>
<Arg>|???<New class="org.postgresql.ds.PGConnectionPoolDataSource">
<Set name="User">recom</Set>
<Set name="Password">recom</Set>
<Set name="DatabaseName">Traildevils</Set>
<Set name="ServerName">localhost</Set><Set name="PortNumber">5432</Set></New>|??</Arg></New>
java.lang.ClassNotFoundException: org.postgresql.ds.PGConnectionPoolDataSource
What did I miss?
You need to add postgresql-9.1-901.jdbc4.jar to $JETTY_HOME/lib/ext.
This is because jetty initializes the JNDI context before it loads the classes from your WAR.
UPDATE: Well, it seems that this is a problem only when I try to debug locally. When published on Jetty (not the same machine) it works great. Is it possible to configure the jetty.xml file used by Run-Jetty-Run when debugging locally?
I just wasted an afternoon trying to find the cause of this, but with no success...
I'm setting up a connection pool with c3p0 for my application. I'm using Jetty 7, by the way. The problem is that when I do a context.lookup get a datasource, I get this exception:
javax.naming.NameNotFoundException; remaining name 'env/jdbc/DSTest'
at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:634)
at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:665)
at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:680)
at org.eclipse.jetty.jndi.java.javaRootURLContext.lookup(javaRootURLContext.java:113)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at com.see.metrics.SqlHelper.Initialize(SqlHelper.java:68)
at com.see.metrics.Metrics.Initialize(Metrics.java:45)
at com.see.game.GameProducer.generateMetadata(GameProducer.java:223)
at org.odata4j.producer.mongodb.MongoProducer.initMongo(MongoProducer.java:98)
at org.odata4j.producer.mongodb.MongoProducerFactory.create(MongoProducerFactory.java:55)
at org.odata4j.producer.resources.ODataProducerProvider.newProducerFromFactory(ODataProducerProvider.java:66)
at org.odata4j.producer.resources.ODataProducerProvider.getInstance(ODataProducerProvider.java:48)
at org.odata4j.producer.resources.ODataProducerProvider.getInstance(ODataProducerProvider.java:1)
at com.sun.jersey.core.impl.provider.xml.LazySingletonContextProvider.get(LazySingletonContextProvider.java:80)
at com.sun.jersey.core.impl.provider.xml.LazySingletonContextProvider.access$000(LazySingletonContextProvider.java:52)
at com.sun.jersey.core.impl.provider.xml.LazySingletonContextProvider$1.getValue(LazySingletonContextProvider.java:69)
at com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable$1.getValue(AbstractHttpContextInjectable.java:100)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:43)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:119)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:166)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:259)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:83)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:133)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:71)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:990)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:941)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:932)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:384)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:451)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:632)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:538)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:478)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:517)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:225)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:937)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:406)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:183)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:871)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
at org.eclipse.jetty.server.Server.handle(Server.java:346)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:589)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1048)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:601)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:214)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:411)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:535)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:529)
at java.lang.Thread.run(Thread.java:662)
I have a jndi.properties file to configure my InitialContext (located in my resource folder src/main/resources)
java.naming.factory.url.pkgs=org.eclipse.jetty.jndi
java.naming.factory.initial=org.eclipse.jetty.jndi.InitialContextFactory
I also have a jetty-env.xml file in the webapp/WEB-INF folder:
<Configure class="org.mortbay.jetty.webapp.WebAppContext">
<!--<Set name="ConfigurationClasses">
<Ref id="plusConfig"/>
</Set> -->
<!-- MySql datasource org.eclipse.jetty.plus.jndi.Resource Factory-->
<New id="DSTest" class="org.mortbay.jetty.plus.naming.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.mchange.v2.c3p0.ComboPooledDataSource">
<Set name="driverClassName">com.mysql.jdbc.Driver</Set>
<Set name="url">jdbc:mysql://host/</Set>
<Set name="username">username</Set>
<Set name="password">password</Set>
<Set name="checkoutTimeout">5000</Set>
<Set name="initialPoolSize">10</Set>
<Set name="maxIdleTime">30</Set>
<Set name="maxPoolSize">160</Set>
<Set name="minPoolSize">10</Set>
<Set name="maxStatements">200</Set>
<Set name="maxConnectionAge">0</Set>
<Set name="acquireIncrement">15</Set>
</New>
</Arg>
</New>
</Configure>
And I added those lines in my web.xml file:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/DSTest</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I seem to have followed all the required steps, but I still get a javax.naming.NameNotFoundException when doing the lookup...
Any hints?
Thanks!
EDIT:
I forgot to put how I do my lookup.
InitialContext ctx = new InitialContext();
DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/DSTest");
Stupid question but this page http://docs.codehaus.org/display/JETTY/JNDI#JNDI-resref states that using JNDI with Jetty is an optional feature that needs to be enabled.
Specifically it says The class that does this is org.mortbay.jetty.plus.webapp.Configuration, and we specify its name in the list of configurations to be applied to the webapp when we define the org.mortbay.jetty.webapp.WebAppContext for it.