request.getServletContext() not found, even with new JAR - java

My compiler is not able to find the HttpServletRequest getServletContext() method.
I am not doing anything too complicated:
public static void setMySortedSet(HttpServletRequest request, SortedSet<String> set)
{
setMySortedSet(request.getServletContext(), set);
}
Some troubleshooting I have tried:
Discovered the method was created in 2.3, so I included a JAR that reflects that (and have it in my Eclipse build path)
I include the JAR in my build.xml classpath.
When I using Eclipse the method is found but when I try to build the classes I see this:
compile:
[javac] Compiling 1 source files to C:\...\workspace\proj\build\WEB-INF\classes
[javac] C:\...\workspace\proj\src\main\Helper.java:26: cannot find symbol
[javac] symbol : method getServletContext()
[javac] location: interface javax.servlet.http.HttpServletRequest
[javac] return getURISet(request.getServletContext());
[javac] ^
[javac] Note: C:\...\workspace\proj\src\main\Helper.java uses unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] 1 error
Any ideas of what I could be missing? I appreciate any responses.

The getServletContext() method is introduced in Servlet 3.0, not 2.3. But if you want to get the ServletContext then an alternative method to get it is:
ServletContext context = request.getSession().getServletContext();
if (username != "" & username != null ) {
context.setAttribute("savedUserName", username);
}
writer.println("Context Parameter : " + (String)context.getAttribute("savedUserName"));
This way you can get the stored Request Parameter Value in different browser....

According to the Javadoc the ServletRequest#getServletContext() method is introduced in Servlet 3.0, not 2.3. You need to install and integrate a Servlet 3.0 compatible container such as Tomcat 7, Glassfish 3, etc in Eclipse and set the Target Runtime of your Dynamic Web Project to that container. When you do that properly, then you do not need to manually fiddle with build paths or build.xml at all, Eclipse will handle it for you automatically. You also do not need to download loose JAR files of an arbitrary servletcontainer of a different make/version and put it in your buildpath. It would only lead to future classpath and portability troubles.
See also:
How do I import the javax.servlet API in my Eclipse project?
Maven dependency for Servlet 3.0 API?

I've had the same trouble recently. In fact it started happening after adding some new jars. Ant found HttpServletRequest class in selenium-server.jar which alphabetically comes first before servlet-api.jar (which was supposed to be used).
So i just renamed selenium-server.jar to x-selenium-server.jar and everything started building OK, as it used to.

This is not a problem with your java compiler. javax is provided by servlet container itself and you must include servlet container jar files to your project setup.
javax.servlet.http and all classes related servlet context and servlet programming is related to your Servlet Container only. So stop worrient about anything else and check if Tomcat libraries are being included in your WEB-APP class path.
If not add them and everything will be fine.
Right Click on your project > Properties > Add Libraries > Server Runtime
and choose your server that is associated with your application.
You are done, this will include Servlet Container libraries to your project and HttpServletRequest & HttpServletResponse classes will be resolved.
Hope it helps, more information about Servlet Architecture and context can be found Here.

Related

How do I use DataNucleus's java agent when deploying a servlet to tomcat?

DataNucleus has a Java agent that performs bytecode enhancement of classes. I added -javaagent:datanucleus-core-5.1.0-m3.jar=-api=JDO (Using the actual jar name and path) to the JVM options used by my IDE to start Tomcat. The agent threw org.datanucleus.exceptions.NucleusUserException: Error : Could not find API definition for name "JDO". Perhaps you dont have the requisite datanucleus-api-XXX jar in the CLASSPATH?, at which point I added -cp datanucleus-api-jdo-5.1.0-m3.jar:. (again using the actual jar name and path), which did not resolve the error. I understand that Tomcat has quirky classpath handling, but the Java agent should be running before Tomcat's main method, meaning none of this trickery should have happened yet. How do I perform runtime bytecode enhancement with DataNucleus on Tomcat?

Java EE server independent way to locate JAR containing javax.persistence classes

I have a Java EE application where you can define variables of a certain type. To validate that the value expression is valid for it's type, I create a string containing a small class:
public class CompilableExpression {
private <type> expression = <expression>;
}
.. and try to compile it using JavaCompiler:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
Iterable<? extends JavaFileObject> compilationUnits =
Arrays.asList(stringContainingCompilableExpression);
CompilationTask task = compiler.getTask(
null, null, diagnostics, options, null, compilationUnits
);
task.call();
This works fine if you are using type: String and expression: "my string", or type: Integer and expression: 10.
I also want to validate types using the #Entity annotation.
When I try to do so I get an error:
Cannot find annotation method name() in type javax.persistence.Table: class file for javax.persistence.Table not found
So, I need to add a JAR containing javax.persistence classes to the class path somehow. Is there a generic way to find this JAR? I'm using GlassFish, and don't want to build a GlassFish only solution.
Or is adding it to my project as a normal (non provided) dependency the way to go?
Update
I'm trying to at least find the location in GlassFish (at ~/glassfish-4.1/glassfish):
find ./ -name '*ee*.jar'
./lib/javaee.jar
./modules/security-ee.jar
./modules/amx-javaee.jar
./modules/javaee-kernel.jar
./modules/autostart/osgi-javaee-base.jar
./modules/autostart/osgi-ee-resources.jar
./modules/deployment-javaee-full.jar
./modules/deployment-javaee-core.jar
./modules/glassfish-ee-api.jar
./modules/javax.management.j2ee-api.jar
My best guess is to use ./lib/javaee.jar, but when I check the contents it's almost empty:
$JAVA_HOME/bin/jar tf ./lib/javaee.jar
META-INF/
META-INF/MANIFEST.MF
META-INF/maven/
META-INF/maven/org.glassfish.main.extras/
META-INF/maven/org.glassfish.main.extras/javaee/
META-INF/maven/org.glassfish.main.extras/javaee/pom.xml
META-INF/maven/org.glassfish.main.extras/javaee/pom.properties
Does anyone know where (in the GlassFish installation) to get the JAR including the javax.persistence classes?
The JAR you are looking for is in $GLASSFISH_HOME/glassfish/modules/javax.persistence.jar
If you are deploying to a JavaEE App Server, the JAR with the #Entity annotation will already be in your application's runtime classpath. You shouldn't have to load any JAR files in code (as you described in your comment).
During development you typically configure your App Server in your IDE and that process should include the JAR with the annotation into your compilation classpath.
You might need to manually include it in the project compile classpath / application server libraries classpath depending on how your IDE handles this. For Glassfish all the API JARs are where you were looking in the modules directory.
Even though this ties your project to finding the JAR for compilation in a specific location relative to the app server install I find it's still a better approach then copying JARs into you project for compilation. This ensures you are compiling against the correct JARs that are deployed to the app server and so long as these are JavaEE APIs your application will deploy fine into any app server.
You could also set up your project to use Maven, include the required deps for the persistence APIs and it will find the compile time deps in your maven cache.
Also you might want to check out Jar Explorer which lets you search for classes etc inside JARs, folders of JARs etc. Its pretty convenient for finding these things.

what is error cannot find WebServlet class?

I am using 12c web server. I make a .java file and compile it using jdk6_29 which is present in 12c. In java file I use annotation #WebServlet but when i compile it, it give errors class WebServlet not find...please tell me what is problem.

java.lang.NoClassDefFoundError from websphere

I have a problem that I can't figure out.
Context :
was 7.0.0.19 version (with no preCompileJsp)
Caused by: java.lang.NoClassDefFoundError: org/apache/jsp/_xxx (wrong name: com/ibm/_jsp/_xxx) at java.lang.ClassLoader.defineClassImpl(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:275) at java.lang.ClassLoader.defineClass(ClassLoader.java:212) at com.ibm.ws.jsp.webcontainerext.JSPExtensionClassLoader.defClass(JSPExtensionClassLoader.java:181) at com.ibm.ws.jsp.webcontainerext.JSPExtensionClassLoader._loadClass(JSPExtensionClassLoader.java:133)
It's the only JSP that give problem, and only on a specific environment (no problem on the others environments with the same configuration) the xxx.class is well present in my profile/tmp directory with others jsp in the same directory (that all give no problem) and the filesystem is not full.
Tests
I did a copy of xxx.jsp to xxxNew.jsp in the same directory
I can access the xxxNew.jsp without any problem (so there is no coding problem)
So I did a mv from xxx.jsp to xxx1.jsp and had no problem to access the jsp new named
I deleted the xxx.class in the tmp directory
I did the mv back to the first name (xxx.jsp) and still get the error with a newly xxx.class in the tmp directory.
Is there a class cache anywhere in websphere that could explain this ? (no cachespec.xml for dynacache found in the war module).
Why Websphere try to find a class from the org.apache.jsp package and not from com.ibm._jsp ? (how the AS choose the mapping from the URL to the classes ?)
Thxs !
Make sure you are not including in your webapp classpath any JSP engine or other implementation of standard JSP libraries that might be incompatible with WebSphere's runtime. Also, once you delete all potentially incompatible jars, try deleting the generated classes from JSP compilation (which are under {WAS_HOME}/AppServer/profiles/{YOUR_PROFILE}/temp), so recompilation would be triggered and discard any stale .class generated with a previous classpath state.
It would be helpful if you posted the list of JARs in your app's classpath.
Try changing the web application class loading policy on the WAS console: PARENT_FIRST / PARENT_LAST.
this bug is due to websphere incorrect log : the original exception is not displayed.
You should check for instance if there is no missing jsp tag libraries in your page.
See https://www-01.ibm.com/support/docview.wss?uid=swg1PI09596
Regards.

XPath class resolution in JBoss5

I'm having a hard time figuring out where the problem is coming from, so I'm posting this in the hopes that others might have found something similar to this elsewhere and are kind enough to share their insight.
I'm using a JBoss 5.0.1.GA application server running on top of a Sun Java 1.6.0-13 JDK. For the WAR file in the generated Web Service, I use a Axis2 1.4 WS engine whose JAR files are inserted by Eclipse Galileo into the project's WEB-INF/lib directory when creating the Webservice from the given "worker" class in the Dynamic Web Project. The relevant code snippet follows:
String sUrl = "http://example.com/datafile.xml";
String sPath = "/some/xpath/string";
InputStream input = new URL(sUrl).openStream();
InputSource source = new InputSource(input);
DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
docFact.setNamespaceAware(false);
DocumentBuilder parser = docFact.newDocumentBuilder();
Document doc = parser.parse(source);
XPath xpath = XPathFactory.newInstance().newXPath();
// error occurs here:
String result = (String) xpath.evaluate(path,doc,XPathConstants.STRING);
input.close();
This is the error I'm getting from the JBoss log:
java.lang.LinkageError: loader constraint violation: when resolving field "STRING" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the referring class, javax/xml/xpath/XPathConstants, and the class loader (instance of <bootloader>) for the field's resolved type, javax/xml/namespace/QName, have different Class objects for that type
I could use the XPath.evaluate(String,Document) — however there are occasions where I need to get (for example) a XPathConstants.NODESET instead, so it's a no-go. I have also tried to fumble a little by littering some jboss-web.xml files here and there in the WAR file, but with no effect.
What I'm trying to understand is:
Where could the error be coming from? The JBoss class loader? Some weird interaction between JBoss and the Sun JDK? Some weirdness introduced by Eclipse when creating the Web Service? Maybe some confusion introduced by the Axis2 libraries deployed within the WAR?
I've found instances of compiled class files in what looks like a triple-whammie:
Sun JDK (file rt.jar);
JBoss libraries ($JBOSS_HOME/lib/endorsed/stax-api.jar); and
Axis2-deployed libraries ($JBOSS_HOME/server/deploy/MyProject.ear/MyProject.war/WEB-INF/lib/axis2-saaj-api-1.4.jar and woden-impl-dom-1.0M8.jar).
How exactly am I supposed to configure JBoss to tell it which classes it's OK to load from "other" libraries from? Specifically, the jaxax.xml.namespace.QName is is causing the grief.
Thank you in advance.
JBoss will throw a LinkageError when the application's classpath contains classes which JBoss considers "protected", i.e. it does not permit the application to contain its own copies of certain key APIs.
In this case, it looks like your appcontains its own copies of the javax.xml.xpath API, and possibly some others as well, as you mentioned.
You need to remove anything from your EAR/WAR's lib directories that clashes with JBoss's own libraries (e.g. axis2-saaj-api-1.4.jar).
It seems that the problem was solved by removing the javax.xml.namespace.* package and respective classes from the deployed Axis2 JAR files. Namely, using Axis2 1.4.1 (instead of 1.4), I repackaged these JAR files:
axis2-saaj-api-1.4.1.jar, by removing javax.xml.namespace
woden-impl-dom-1.0M8.jar, by removing javax
Also, Eclipse is extremely picky at the project configuration. So far, I've found that the Project Facet for the Dynamic Web Project has to be created with a Dynamic Web Module of version 2.4 (and not 2.5 as it suggests by default), but with a Java version 6 (same as the branch of the used JDK). I don't know why this happens, I suppose the Dynamic Web Module version 2.4 tying up by default with Java 1.4 in Eclipse is where all the confusion comes from. Some googling led me to believe that package javax.xml didn't become incorporated into the JDK until Java 5 or Java 6 -- hence the possible mixup! However, I'm not knowledgeable enough to investigate if the problem comes from how Eclipse packages the archive files for deployment so this is just a suspicion I have so far.

Categories