I'm trying to mock an HTTPServletRequest data on my development GAE server. I'm running Eclipse Plugin 1.3.7
I've tried to do this:
package com.FOO.madservice.servlet.mock;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.mockito.Mockito.*;
#SuppressWarnings("serial")
public class BAR2ServletMock extends HttpServlet {
...
protected HttpServletRequest requestFilter(HttpServletRequest req) {
HttpServletRequest servletRequest = spy(req);
doReturn("gzip, deflate").when(servletRequest).getHeader("header-name-goes-here");
doReturn("174.30.216.4").when(servletRequest).getRemoteAddr();
return servletRequest;
}
...
}
Running the following gives exception:
java.lang.NoClassDefFoundError: sun.reflect.ReflectionFactory is a restricted class. Please see the Google App Engine developer's guide for more details.
Any ideas on how to disable class while list checking on GAE development server or perhaps using a different mocking library that works with GAE?
Thanks,
Maxim.
I doubt that you'll be able to get around this on the GAE.
The GAE is compliant with the Java Servlet Standard, so you could probably test out your program by installed a standard Java Servlet Container such as Tomcat.
Also, doesn't object mocking require reflection, by definition of "mocking"? The GAE whitelist is absolutely enforced, and you will not be able to get around it. To deploy on the app engine, there is no way to use the full reflection API (some classes are supported, however).
Related
Stack
Java
Jakarta EE 10
JBoss/Widlfly 27
Kubernetes K8S
JAX-RS (RestEasy)
I want to initialize some caches on startup of my app. During that time i want my readiness probe to respond not ready.
With the management inteface turned on, this works BUT not with my classes, instead the standard one responds.
Wildfly runs in standalone mode.
What i try to accomplish is to run my OWN code for readiness/live BUT that these endpoints are available during startup. I created my own outside of microprofile.healt but they are not available during startup.
Does anybody have some ideas?
Below is my code
import jakarta.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Liveness;
import org.eclipse.microprofile.health.Readiness;
/**
* Created by Gerry Askefalk on: 2023-01-13
*/
#ApplicationScoped
#Liveness
#Readiness
public class Mycheck implements HealthCheck {
#Override
public HealthCheckResponse call() {
return HealthCheckResponse.named("mycheck").up().build();
}
}
Ok
the solution (and my bad) was to not add microprofile extensions to WF.
When i did, it works!
This article explained it to me.
microprofile on wf
Although I have used EJB earlier, I want to re-assure myself that I understand how it really works.
So, I created a Simple Session Bean EJB (3.1), and packaged it as .ear (which has client jar as well). The below is the snippet:
Session Bean Implementation:
package com.example;
import javax.ejb.Stateless;
#Stateless
public class FirstSessionEJB implements FirstSessionEJBRemote {
public FirstSessionEJB() {
}
#Override
public String print() {
return "Hello";
}
}
Remote interface:
package com.example;
import javax.ejb.Remote;
#Remote
public interface FirstSessionEJBRemote {
public String print();
}
I deployed this EJB as .ear and it was successfully deployed in Wildfly 10.x.
Now, I want to access this using a standalone Java client, running in a separate JVM.
Here is the client code (It might not be completed as I am not clear on how to invoke mainly due to JNDI).
package com.example.main;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.example.FirstSessionEJBRemote;
public class Main {
public static void main(String[] args) throws NamingException {
String GLOBAL_JNDI_NAME="java:global/FirstEJBProjEAR/FirstEJBProj/FirstSessionEJB!com.example.FirstSessionEJBRemote";
Hashtable<String,String> jndiProperties = new Hashtable<>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
InitialContext ic = new InitialContext(jndiProperties);
FirstSessionEJBRemote ejbRemote = null;
ejbRemote = (FirstSessionEJBRemote)ic.lookup(GLOBAL_JNDI_NAME);
ejbRemote.print();
}
}
I referred to this link on how to do the JNDI lookup (and what all parameters to use in, however it is not working.)
In the link it is mentioned that it has Wildfly specific jar which works without JNDI lookup.
Can anyone help me understand:
1) What all properties I need to set up for JNDI look up?
2) Is there any specific jar that needs to be present in client side application?
I don't want to use any specific Wildfly jar, that is, I want to go with traditional JNDI lookup, so can anyone please guide me on this?
It is very frustrating to struggle just to write a simple "Hello world" kind of EJB. I referred to some books are well, but all what they have provided is just the "lookup" code without actually telling what all properties needs to be included for JNDI and any jar to be included.
As the article you link to states albeit a bit hidden in that mountain of text, you do need the jboss-client.jar that you will find in the Wildfly server installation (bin/client/jboss-client.jar); it needs to be on the client's runtime classpath. It contains to begin with that org.jboss.ejb.client.naming package referenced in your code.
The jar contains the extra bit of magic for a client to be able to setup and maintain EJB remote invocations with the Wildfly server, just using JNDI isn't going to cut it. And there is no one jar to rule them all, each container (Wildfly, Glassfish, Weblogic, etc.) has its own implementation for a client library.
Do note that invoking EJBs from a client application is very old school (read: you don't want to do that). A more realistic and modern day view of EJB technology is to use it within an enterprise container itself, such as from a web application / war - say as part of a RESTful service. You likely don't even need the extra layer of the EAR file then, you can just package everything neatly into the one war application.
And in that scenario if you do have a client application, that client can talk to the RESTful service - a much simpler and cross-server, cross-platform communications interface.
I have a working web-application that I built, successfully deployed to Heroku, and is functioning well. However, I'm trying to tune the server/servlet config, and that's when I realized that I don't know what my application is actually doing.
For glassfish, this is the config that's needed.
However, for Jetty, this is the config that's needed.
I realized I have no idea which of the above my application is actually using, so I started digging in my code and found the following:
The main method being called by Heroku is instantiating the following Jetty server/webappcontext.
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
However, the jetty config seems to rely on a number of files (such as etc/jetty.xml, webapps folder or war files) which my project does not have at all.
In addition, my web.xml file defines the following servlet:
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
The fact that my application is defining a Jetty server but Glassfish servlet concerned me quite a bit. In an effort to standardize everything around Jetty, I tried adding the jetty servlet to my pom.xml dependencies and changed the above to:
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
However, this change caused my application to break. It still compiles successfully and all my jerset-test based integration tests still succeed locally. But when I actually run the server, none of the routes work.
Some questions:
Is it a ill-advised to use a Jetty server along with a Glassfish servlet (container)?
If yes, what servlet (container?) should I replace Glassfish with, and what do I need to do to get the new Jetty servlet working?
If no, what config should I be using for my current setup? Should I be implementing the Glassfish config or the Jersey config?
I've spent many hours trying to read through various documentations, tutorials and stack-overflow threads, but they all either assume prior knowledge about servlets, JavaEE and related topics (none of which I'm familiar with), or they are oriented towards building brand new hello-world apps from scratch (as opposed to porting an existing working app over, which is what I'm trying to do). Any explanations you could give, without assuming prior knowledge, relevant to the context described above, would be much appreciated.
Edit: I think I'm starting to understand now that a Servlet is the code that generates the response for a request, and the ServletContainer is what provides the infrastructure for the Servlet. I've never had to deal with Servlets directly in building my web-app. Here's an example of what a route looks like in my app:
#Path(Ping.REST_PREFIX)
public class Ping {
static final String REST_PREFIX = "/ping";
#GET
public static Response get(#DefaultValue("getPing") #QueryParam("param") String param) {
return Response.ok().entity(param).build();
}
#Path("/pong")
#GET
public static Response getPong(#DefaultValue("getPong") #QueryParam("param") String param) {
return Response.ok().entity(param).build();
}
}
How can I port code like the above into a Jetty ServletContainer, without rewriting vast sections of my application?
You are not using a "Glassfish Servlet Container", you are using a "Jersey Servlet Container".
Jersey is the project you are using.
Glassfish was the umbrella organization (sometimes called "a forge") that helps manage/maintain the Jersey project (along with dozens of other projects).
Difference com.sun.jersey and org.glassfish.jersey
The Jersey project can now be found at the java.net organization.
https://jersey.java.net/
How to use OWASP ESAPI in J2SE? When I import the jar to my project. and use the method
ESAPI.encoder().encodeForURL(string url)
,it throws an Exception Caused by:
java.lang.ClassNotFoundException: javax.servlet.http.HttpServletResponse
But my program don't need Servlet. So as the title, how to use ESAPI in J2SE? Is it possible?
The ESAPI locator class has dependencies on the JavaEE HttpServletResponse and HttpServletRequest classes so you can't use it the way that you did. However, you could use:
import org.owasp.esapi.reference.DefaultEncoder;
...
DefaultEncoder.getInstance().encodeForURL(url_string);
and get the same effect. It's ugly, yes, but should work as long as you don't use anything else that requires any JavaEE classes.
I have been looking for a few days at tutorials on this subject but either they aren't exactly what i'm looking for or I cant get them to work. I cant imagine that more people aren't confused on the subject so I will ask here.
What I would like to create is a REST service in Eclipse that I can run on my web server and "connect to" using ajax from a separate dynamic web project. All i'm looking for here at the moment is a simple hello world example of a service returning ajax working alongside a separate web project that consumes the JSON it returns.
Im hoping to get a usable user guide (or at least links to one) that will help me out and future people looking for this same thing.
I have gotten as far as this simple class (i have included Jersey Jars but I dont understand what to do from here):
public class UserRestService {
private static final Logger log = Logger.getLogger(UserRestService.class.getName());
private CreateUserService createUser;
#POST
#Path("/CreateUser/{name}/{age}")
#Consumes("text/html")
public User createUser(#PathParam("name") String name, #PathParam("age") Integer age) {
return createUser.createUser(name, age);
}
}
How do i get this class to be an accessible api service on my tomcat server? How do I setup another web project to consume it (I understand how to make an ajax call this is more a question of how do i setup the projects)? Where do servlets come in ?
Rather than copying jars, it would be better to use maven or gradle for package management. A simple pom.xml (maven) with the dependencies can help you abstract determining the compile and runtime dependencies.
Okay so the Java standard is jaxrs (https://jax-rs-spec.java.net/). You can use Jersey which is the rest implementation of jaxrs (https://jersey.java.net/).
A sample of implementing a service using eclipse, jersey and tomcat can be found here: http://www.vogella.com/articles/REST/article.html
If you are feeling like an adventure you can look at vertx.io (http://vertx.io) and my beta release of jaxrs 2.0 framework for vertx called 'vest' (https://github.com/kevinbayes/vest)
Addition:
Jersey provides examples on github of how to implement services at https://github.com/jersey/jersey/tree/master/examples