#Resource annotation doesn't work in Tomact 10.0.10 - java

Recently I tried Tomcat 10.0.10 and when trying to inject the connection pool as a JNDI resource find out that the #Resource annotation doesn't work.
Then I tried obtain it programmatically by creating a InitialContext and it worked. Initially I thought it was only for the java:comp/env/jdbc so I tried with a simple bean like below and tried to inject it with the #Resource annotation it didn't work again. When I try to obtain it programmatically by creating a InitialContext and it works. Then I check whether the #PostConstruct or #PreDestroy annotation works and found out that they also don't work.
package lk.ijse.test.tomcatdbcp;
public class Something {
}
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="bean/Something" auth="Container"
type="lk.ijse.test.tomcatdbcp.Something"
factory="org.apache.naming.factory.BeanFactory"
/>
</Context>
<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="false" xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<resource-env-ref>
<resource-env-ref-name>bean/Something</resource-env-ref-name>
<resource-env-ref-type>lk.ijse.test.tomcatdbcp.Something</resource-env-ref-type>
</resource-env-ref>
</web-app>
package lk.ijse.test.tomcatdbcp;
import java.io.*;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
#WebServlet(name = "helloServlet", value = "/hello", loadOnStartup = 1)
public class HelloServlet extends HttpServlet {
private String message;
#Resource(name= "java:comp/env/bean/Something")
private Something something;
#PostConstruct
public void doSomething(){
System.out.println("Does it work?");
}
public void init() {
message = "Hello World!";
try {
InitialContext ctx = new InitialContext();
Something lookup = (Something) ctx.lookup("java:comp/env/bean/Something");
System.out.println(lookup);
System.out.println(something); // null
} catch (NamingException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
public void destroy() {
}
}
To reproduce the same issue, I created a sample repo here: https://github.com/sura-boy-playground/play-with-tomcat10
(Complete code can be found there)
At first, I had used javax.annotation.Resource annotation, so I thought that was the reason because of the javax.* to jakarta.* namespace change. Then I tried it with jakarta.annotation.Resource but the result was same.
I tried the same application with Tomcat 9.0.41 plus javax.* namespace, it works perfectly.
Is there any extra stuff that I need to do on Tomcat 10.0.10 to enable these annotations? I dug the Tomcat 10 documentation but I wasn't able to find out any thing related to my issue.
I found out that there was a similar case in Tomcat 7 previously, but I don't like that kind of workaround now.
Tomcat #Resource annotations API annotation stops working in Tomcat 7

You should declare the scope of your jakarta.annotation dependency as provided:
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.0.0</version>
<scope>provided</scope>
</dependency>
If you have two copies of jakarta.annotation.Resource (one in the common classloader and one in your application's classloader), the two classes are different. The InstanceManager will look for fields annotated with the common classloader's copy of #Resource, while the something field is annotated with your webapp's copy of #Resource.
Edit: this problem was fixed in Tomcat 10.0.17 (cf. changelog), 9.0.59 and 10.1.0-M11.
Remark: You will have the same problem in Tomcat 9.0 if you use Java 11 or later. Before Java 11 the javax.annotation.* classes where included in the JRE. Servlet containers are required to look in the bootstrap/JRE classloader before looking in the webapp classloader (overriding javax.* classes is a breach of Java's licence), therefore Tomcat would never find the additional copy of the classes.

Related

#Resource error: "Naming binding already exists for foo.NewServlet/userName in namespace"

I am looking at using the "#Resource String ..." injection available in servlet 3.0+ containers for providing configuration parameters easily to servlets. I would like for the defaults to work and fail if the key is not present in JNDI (indicating a configuration error)
I have toyed with a simple servlet in Netbeans 8.2 with Glassfish 4.1.1 where I would like to have the userName field, and the setFullName(String fullName) set:
package foo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {
#Resource(description="user name")
String userName;
private String fullname;
#Resource()
public void setFullName(String fullName){
this.fullname = fullName;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("Full name = " + fullname);
out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
out.println("Username = " + userName);
out.println("</body>");
out.println("</html>");
}
}
// Autogenerated stuff omitted
}
Without "web.xml" the fields are just null (and no failure). I have then played around with "web.xml" to see how I could define this. The "java:comp/env/foo:NewServlet/fullName" name is what Glassfish 4.1.1 appears to create as the name for the fullName setter.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<env-entry >
<env-entry-name>java:comp/env/foo.NewServlet/fullName</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>!BAR!</env-entry-value>
</env-entry>
<env-entry >
<env-entry-name>java:comp/env/foo.NewServlet/userName</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>!USERNAME!</env-entry-value>
</env-entry>
</web-app>
This then fails with
Severe: Exception while deploying the app [WebApplication4] : Naming binding already exists for foo.NewServlet/userName in namespace {java:module/env/foo.NewServlet/userName=Env-Prop: java:comp/env/foo.NewServlet/userName#Non-Injectable Resource#java.lang.String#!USERNAME!##, java:module/env/foo.NewServlet/fullName=Env-Prop: java:comp/env/foo.NewServlet/fullName#Non-Injectable Resource#java.lang.String#!BAR!##}
There is nothing else but these two files in the project. Apparently I am misunderstanding something basic, but reading the Java EE tutorial and searching for suggestions did not help me. I would really like two things:
Either not providing any hints to the #Resource-tag using the container generated defaults or just a key like "our.application.fullName".
Fail loudly if anything is wrong, including the key-value not being present.
Suggestions? A good answer will give a 500 point bounty.
You have really only missed two important details:
When specifying the name of a resource in a deployment descriptor (such as the web.xml), whether it be an env-entry-name, resource-env-ref-name or ejb-ref-name, etc, the java:comp/env part of the JNDI name is always implicit. Therefore, if you want a resource defined by an env-entry to appear in JNDI at java:comp/env/foo, then you specify its env-entry-name as:
<env-entry-name>foo</env-entry-name>
The Java EE specification (§EE.5.2.5) modifies the rules for the "default" name applied to #Resource annotations:
A field of a class may be the target of injection. The field must not be final. By default, the name of the field is combined with the fully qualified name of the class and used directly as the name in the application component’s naming context. For example, a field named myDatabase in the class MyApp in the package com.example would correspond to the JNDI name java:comp/env/ com.example.MyApp/myDatabase. The annotation also allows the JNDI name to be specified explicitly. When a deployment descriptor entry is used to specify injection, the JNDI name and the field name are both specified explicitly. Note that, by default, the JNDI name is relative to the java:comp/env naming context.
In other words, if the fully qualified name of your servlet is com.p45709634.NewServlet, then the JNDI name of the userName field is going to be java:comp/env/com.p45709634.NewServlet/userName. Therefore its env-entry-name is going to be:
<env-entry-name>com.p45709634.NewServlet/userName</env-entry-name>
So, if you use these fully qualified names in your web.xml file then you can happily declare the annotated fields as you have requested:
#Resource
private String userName;
private String fullname;
#Resource
public void setFullName(String fullName){
this.fullname = fullName;
}
Now that same chapter of the specification states:
If the container fails to find a resource needed for injection, initialization of the class must fail, and the class must not be put into service.
However this does not seem to happen in practice (at least on GlassFish for you and WildFly for me). This may be due to some deferment to the CDI spec for injection, which does not seem to have much to say about failure to locate resources for injection.
Consequently we may be stuck with validating these fields in the init method or an #PostConstruct annotated method.

#PostConstruct Wrong deploy in GlassFish

My project is based in Spring 4.2.3.RELEASE
Before a use Tomcat, but last migration project has one problem with ClassLoader, then change Tomcat 8 for GlassFish 4.1!
In project has one #Component("i18N")
in my Object call i18N has one method
But i'm to deploy in GlassFish the file site-1.3.0.0.war
Has put a wrong error
In other project has same problem, but i'm dont have time to solve this problem, at now i'm need solved this.
Error occurred during deployment: Exception while deploying the app
[site-1.3.0.0] : The lifecycle method [init] must not throw a checked exception. Related annotation information: annotation
[#javax.annotation.PostConstruct()] on annotated element [public void com.sys.resolver.SysResourceBundleRead.init() throws java.lang.IllegalAccessException,java.lang.InstantiationException,java.io.IOException,org.apache.taglibs.standard.lang.jstl.ELException] of type
[METHOD]. Please see server.log for more details.
add the method class
**
#PostConstruct
public void init() throws Exception{
}
**
As the error message says, a method with #PostConstruct must not throw checked Exceptions.
So remove throws Exception from your method and catch it in the method body:
#PostConstruct
public void init() {
try {
// bla
} catch (Exception x) {
// do something
}
}
Here
I already made work around that worked in my case.
You can solve this issue first by adding a web.xml with metadata-complete="true". Next you will want to make sure your context are in the Web root Directory /WEB-INF/.
With this glassfish can load all #PostConstructSpring dependencies.
I solved by adding the metadata-complete="true" in the web.xml like:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" metadata-complete="true">

Tomcat 7 Datasource injection mechanism

I am trying to create simple web-app. And stuck on datasource injection. There seems to be several problems. So I will start from my confusion. As I understand there's 2( at least) ways to inject the DataSource into Servlet:
web.xml
#Resource
web.xml sample
<resource-ref>
<res-ref-name>jdbc/MyDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<injection-target>
<injection-target-class>ua.test.TestServlet</injection-target-class>
<injection-target-name>dataSource</injection-target-name>
</injection-target>
</resource-ref>
#Resource sample
public class TestServlet extends HttpServlet{
#Resource
private DataSource dataSource;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
My confusion : web.xml doesn't work in Tomcat 7 on my simple project. In my opinion, web.xml option should work since there were no annotations before Java 5. Please explain.
Update:
Datasource configuration
<Resource name="jdbc/MyDB"
type="javax.sql.DataSource"
auth="Container"
username="SA"
password=""
driverClassName="org.hsqldb.jdbcDriver"
url="jdbc:hsqldb:file:~/database/my_db"
/>
Try taking out the injection-target entry in web.xml and using the name attribute on the #Resource annotation:
public class TestServlet extends HttpServlet {
#Resource(name = "jdbc/MyDB")
private DataSource dataSource;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
That worked in my local testing with Tomcat 7.0.50. If you're looking for the annotation-less way of doing it, I haven't gotten that to work, even though it should given their changelog1.
EDIT
I still haven't found a solution, but I was curious why this doesn't work so I took a look at the injection-target code. I found that it loads the context.xml entry first, and does pick up the settings from web.xml, but chooses not to override the configuration it found in context.xml because it already sees a jdbc/MyDB entry. I'm not sure how to get the injection-target settings into context.xml or the DB settings like driverClassName into web.xml.
As far as I know, tomcat is a nice servlet container, but it is not a full Java EE container. From The BalusC Code: How to install CDI in Tomcat?, I think that out of the box tomcat is not able to do any dependency injection. Tomcat alone works perfectly associated with Spring, because it is lightweight.
If you do not want to use Spring, the link I wrote above should give you some ways to do CDI with tomcat (TomEE instead of tomcat, Weld or OpenWebBeans).
EDIT:
Apparently, recent versions of tomcat 7 should accept DI - see below the link in comment from davidfmatheson.

Context is read only

Helo masters, I have to create a JNDI Datasource dynamically, I tried to do it with a listener called SetupApplicationListener. Here is the beginning of WEB-LIB/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee">
<display-name>pri-web</display-name>
<!-- Listeners -->
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<listener>
<listener-class>myapp.SetupApplicationListener</listener-class>
</listener>
The code of the listener:
public class SetupApplicationListener implements ServletContextListener {
public static Log LOG = null;
public void contextInitialized(ServletContextEvent ctx){
try {
createOracleDataSource();
.....
}
}
private void createOracleDataSource() throws SQLException, NamingException {
OracleDataSource ds = new OracleDataSource();
ds.setDriverType(...);
ds.setServerName(...);
ds.setPortNumber(...);
ds.setDatabaseName(...);
ds.setUser(...);
ds.setPassword(...);
new InitialContext().bind("java:comp/env/jdbc/myDS", ds);
}
.....
}
And there is the error:
[ERROR] 29/01/2013 09:44:50,517 (SetupApplicationListener.java:86) -> Error
javax.naming.NamingException: Context is read only
at org.apache.naming.NamingContext.checkWritable(NamingContext.java:903)
at org.apache.naming.NamingContext.bind(NamingContext.java:831)
at org.apache.naming.NamingContext.bind(NamingContext.java:171)
at org.apache.naming.NamingContext.bind(NamingContext.java:187)
at org.apache.naming.SelectorContext.bind(SelectorContext.java:186)
at javax.naming.InitialContext.bind(InitialContext.java:359)
at myapp.SetupApplicationListener.createOracleDataSource(SetupApplicationListener.java:102)
Can I set the read-only properties of the Context to "true"? Thanks! :)
Tomcat 6.0
Oracle 11g
jdk1.5
EDIT: Don't need to be dynamically, i have to define a jndi datasource internally I can't modify the server files because it is a shared server. It must be jndi because other modules use it in that way, thanks.
If you need to create a datasource dynamically is there really any need for a JNDI lookup? JNDI is designed to make the connection external to the application, while in your scenario its tightly coupled to the application due to a legitimate requirement. Why not just use a JDBC connection?
You need to create a ServletContextListener and there you can make the InitialContext writable - it's not the way it should be done, but if you really need it, this is one way you can do it.
This also works with Java Melody!
protected void makeJNDIContextWritable(ServletContextEvent sce) {
try {
Class<?> contextAccessControllerClass = sce.getClass().getClassLoader().loadClass("org.apache.naming.ContextAccessController");
Field readOnlyContextsField = contextAccessControllerClass.getDeclaredField("readOnlyContexts");
readOnlyContextsField.setAccessible(true);
Hashtable readOnlyContexts = (Hashtable) readOnlyContextsField.get(null);
String context = null;
for (Object key : readOnlyContexts.keySet()) {
String keyString = key + "";
if (keyString.endsWith(sce.getServletContext().getContextPath())) {
context = keyString;
}
}
readOnlyContexts.remove(context);
} catch (Exception ex) {
ex.printStackTrace();
}
}
I haven't got this problem before since I usually defined JNDI in application server(tomcat, weblogic and etc). Just like what Kevin said, this is exactly what JNDI was designed for; separating datasource config from your source code and retrieving JNDI resources through lookup and inject;
Back to your question, I think tomcat has every strict rules on modifying JNDI at runtime. In another word, you cannot re-bind or remove jndi from Context. If you go through the tomcat specification you will probably see some thing about jndi lookup but no re-bind.
From section EE.5.3.4 of the EE 6 platform specification (JSR 316):
The container must ensure that the application component instances
have only read access to their naming context. The container must
throw the javax.naming.OperationNotSupportedException from all the
methods of the javax.naming.Context interface that modify the
environment naming context and its subcontexts.
Note that "their naming context" in this section is referring to java:comp.
I solved this problem when found that I was closing environmentContext object
For example:
Context context=new InitialContext();
Context environmentContext=(Context) context.lookup("java:comp/env");
And my code was:
environmentContext.close();
After removing close function from environmentContext problem was solded for me;
I also had this problem, but being new to Tomee, I didn't know that there is a simple solution. When I deployed my web app to the webapps folder, the app worked fine, but when I deployed it to a service folder, I got the same abort. The problem was that the folder name did not match the war name (minus the .war). Once I fixed that, the app worked fine. Make sure the war name, folder name and service name are identical. This problem produces several different errors, including Context is read only and Error merging Java EE JNDI entries.
I solved this issue by setting useNaming="false" in my context.xml.
From the documentation:
useNaming : Set to true (the default) to have Catalina enable a JNDI InitialContext for this web application that is compatible with Java2 Enterprise Edition (J2EE) platform conventions.

Weblogic Bea 10.0 M1 and WorkManager

I have to execute long running threads in a WebLogic Bea 10.0 M1 server environment. I tried to use WorkManagers for this. Using an own WorkManager allows me to specify my own thread timeout (MaxThreadStuckTime) instead of adjusting the timeout for the whole business application.
My setup is as follows:
weblogic-ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/90" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-ejb-jar.xsd">
<weblogic-enterprise-bean>
<ejb-name>TestBean</ejb-name>
<resource-description>
<res-ref-name>myWorkManager</res-ref-name>
<jndi-name>wm/myWorkManager</jndi-name>
</resource-description>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
weblogic-application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic xmlns="http://www.bea.com/ns/weblogic/90" xmlns:j2ee="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/90
http://www.bea.com/ns/weblogic/90/weblogic.xsd">
<work-manager>
<name>myWorkManager</name>
<ignore-stuck-threads>1</ignore-stuck-threads>
</work-manager>
</weblogic>
and the Bean:
import javax.annotation.Resource;
import javax.ejb.Stateful;
import weblogic.work.WorkManager;
#Stateful(mappedName = "TestBean")
public class TestBean implements TestBeanRemote {
#Resource(name = "myWorkManager")
private WorkManager myWorkManager;
public void test() {
myWorkManager.schedule(new Runnable() {
public void run() {
while (true) {
System.out.println("test: +++++++++++++++++++++++++");
try {
Thread.sleep(45000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
When I try to deploy this things, the server gives me the following exceptions:
[EJB:011026]The EJB container failed while creating the java:/comp/env namespace for this EJB deployment.
weblogic.deployment.EnvironmentException: [EJB:010176]The resource-env-ref 'myWorkManager' declared in the ejb-jar.xml descriptor has no JNDI name mapped to it. The resource-ref must be mapped to a JNDI name using the resource-description element of the weblogic-ejb-jar.xml descriptor.
I try to figure out how to access / use WorkMangers for days now, and still get this or that as an exception. Very frustrating!
Thanks in advance!
You need to remove the WorkManager refrence from your weblogic-ejb-jar.xml, this refenece should go to ejb-jar.xml.
Infact I doubt if Weblogic schema definition "weblogic-ejb-jar.xsd" will allow you to add a reference element, you must be getting xsd validation errors.
anyways, get rid of the element
resource-description from weblogic-ejb-jar.xml
<weblogic-enterprise-bean>
<ejb-name>TestBean</ejb-name>
<resource-description>
<res-ref-name>myWorkManager</res-ref-name>
<jndi-name>wm/myWorkManager</jndi-name>
</resource-description>
</weblogic-enterprise-bean>
it will look like this
weblogic-ejb-jar.xml
<weblogic-enterprise-bean>
<ejb-name>TestBean</ejb-name>
</weblogic-enterprise-bean>
your workManager reference will go to ejb-jar.xml like this.
ejb-jar.xml
<enterprise-beans>
<session>
<ejb-name>TestBean</ejb-name>
<ejb-class>com.xxx.TestBean</ejb-class> <!-- your package com.xxx-->
<resource-ref>
<res-ref-name>myWorkManager</res-ref-name>
<res-type>commonj.work.WorkManager</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</session>
</enterprise-beans>
Now to get WorkManager from JNDI I'm doing
InitialContext ctx = new InitialContext();
this.workManager = (WorkManager) ctx.lookup("java:comp/env/myWorkManager");
but I belive annotation will work equally well.
#Resource(name = "myWorkManager")
my weblogic-application.xml looks same as shared above
<weblogic>
<work-manager>
<name>myWorkManager</name>
<ignore-stuck-threads>1</ignore-stuck-threads>
</work-manager>
This is working for me .. let me know if needed I can share my full code.
you can view your WorkManager and load on it by going to Weblogic Admin Console
Home—>Deployments—>yourApp—>Monitoring(Tab)—>WorkLoad(Tab)”
You need to name your work manager. The way we do it is in our Ear project EarContent/META-INF/weblogic-application.xml
<wls:work-manager>
<wls:name>wmBatch</wls:name>
<wls:ignore-stuck-threads>true</wls:ignore-stuck-threads>
</wls:work-manager>
(which you appear to have done)
and then we use the annotations to set the manager:
#MessageDriven(ejbName =..., dispatchPolicy = "wmBatch")
And then there is no coding around getting the work manager. This might work for you.
BEA (together with IBM) have developed a framework specifically for managing long-running tasks in a Java EE environment. Take a look at CommonJ.
The Spring Framework offers some convenience classes around this framework.

Categories