Javax.naming.NameNotFoundException: when trying to look up the jndi name in JavaEE and Wildfly - wildfly

I am doing some unit testing using javaee and wildly so I am in the client project trying to lookup the jndi name remotely in order to test a service located of course in the ejb, all is fine and the handshake is done correctly but while testing I am getting an exeception which is:
test.ServiceLocatorException: javax.naming.NameNotFoundException:
/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
Here is a snippet showing the appname, modulename and this is how I am trying to lookup the jndi:
java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
java:app/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
java:module/ClientSessionBean!utilities.CllientSessionBeanRemote
java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanLoacal
java:app/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanLoacal
java:module/ClientSessionBean!utilities.CllientSessionBeanLoacal
Client Code:
public class JunitTester {
public static final String jndi = "java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote" ;
private static CllientSessionBeanRemote getProxy() {
return (CllientSessionBeanRemote) ServiceLocator.getInstance().getProxy(jndi);
}
#org.junit.Test
public void Test() throws NamingException {
System.out.println(JunitTester.getProxy().Verify_No_Existence("Multiskan"));}
Any advice could help, thanks.

with your client code I was able to run on glassfish successfully....
Below is the code having said that
if you can test again please give me the exact exception.
Ensure Client.jar is in your classpath in my case its gf-client.jar
server up and running and you than connect the client
Junit
package com.au.clients;
import com.au.ejbs.GreetingI;
import javax.naming.NamingException;
public class JunitTester {
public static final String jndi = "java:global/ejb3_2_ear_exploded/ejb/Greeting";
private static GreetingI getProxy() throws NamingException {
return (GreetingI) ServiceLocator.getInstance().getProxy(jndi);
}
#org.junit.Test
public void Test() throws NamingException {
System.out.println(getProxy().Verify_No_Existence("Multiskan"));
}
}
Service locator
import com.au.ejbs.GreetingI;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
public static ServiceLocator getInstance() {
ServiceLocator serviceLocator = null;
if(serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public static GreetingI getProxy(String jndi) throws NamingException {
InitialContext context =new InitialContext();
GreetingI greeting = context.doLookup(jndi);
return greeting;
}
}
output
true
Process finished with exit code 0

Related

Integration Tests for RESTEasy Endpoint

I want to perform integration tests on my REST endpoint but am running into issues.
Below is my endpoint. NOTE: I cannot change this part of the code.
#Path("/people")
public class PersonResource {
private final PersonService personService;
#Inject
public PersonResource(final PersonService personService) {
this.personService = personService;
}
#GET
#Produces("application/json")
public List<Person> getPersonList() {
return personService.getPersonList();
}
}
From what I've been able to find online, I have the following basic structure for my test.
public class PersonResourceTest {
private Dispatcher dispatcher;
private POJOResourceFactory factory;
#Before
public void setup() {
dispatcher = MockDispatcherFactory.createDispatcher();
factory = new POJOResourceFactory(PersonResource.class);
dispatcher.getRegistry().addResourceFactory(factory);
}
#Test
public void testEndpoint() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("people");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
System.out.print("\n\n\n\n\n" + response.getStatus() + "\n\n\n\n\n");
System.out.print("\n\n\n\n\n" + response.getContentAsString() + "\n\n\n\n\n");
}
}
However, this results in the following error on the last line of the setup method.
java.lang.RuntimeException: RESTEASY003190: Could not find constructor for class: my.path.PersonResource
I explored the Registry API and thought maybe I should have been using addSingletonResource instead, so I changed the last line of setup to dispatcher.getRegistry().addSingletonResource(personResource); and added the following.
#Inject
private PersonResource personResource;
But that results in a NullPointerException on the last line of setup.
The sparse documentation on the mocking isn't very helpful. Can anyone point out where I'm going wrong? Thanks.
You need to do two things
Add a no arguments constructor to your source class:
public PersonResource() {
this(null)
}
In the test class, initialize the PersonResource class with an instance of PersonService class:
dispatcher.getRegistry().addSingletonResource(new PersonResource(new PersonService()));
If needed, the PersonService class can be mocked:
private Dispatcher dispatcher;
#Mock
private PersonService service;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
dispatcher = MockDispatcherFactory.createDispatcher();
PersonResource resource= new PersonResource(service);
ispatcher.getRegistry().addSingletonResource(resource);
}
Hope it helps!

EJB not initializing in Wildfly 9.0.0 using #EJB

I'm trying to migrate from EJB2.x to EJB3.x and i'm using Wildfly 9.0.0.
The old EJB2.x is working in JBoss 4.2.2 and this is how it looks like:
public interface WUFFacadeRemote extends EJBObject {
public ClientData getItems(ClientData data);
public ClientData save(ClientData data);
}
public interface WUFFacadeHome extends EJBHome {
public WUFFacadeRemote create();
}
public class WUFFacade {
public ClientData getItems(ClientData data) {
//code here
}
public ClientData save(ClientData data) {
//code here
}
}
public class WUFAction extends HttpServlet implements IAction {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
...
Object objRef = ic.lookup("java:comp/env/wUF");
com.wuf.WUFFacadeHome home = (com.wuf.WUFFacadeHome) PortableRemoteObject.narrow(objRef, com.wuf.WUFFacadeHome.class);
engine = home.create();
//engine gets the reference, and I can use it normally.
...
}
}
I also have the ejb-jar.xml and it's working. Now, the solution I was thinking to EJB3.x and Wildfly 9.0.0 is as below:
#WebServlet(urlPatterns = "windows/wUF.do", loadOnStartup = 1)
public class WUFAction extends HttpServlet implements IAction {
#EJB
private WUFFacadeRemote engine;
public void doPost(HttpServletRequest request, HttpServletResponse response) {
//Here I should be able to use my engine.
//Wildfly starts and I call the page, engine is not null at this moment,
//but after I call the page again, it becomes null and remains null.
}
}
#Stateless
#Remote(WUFFacadeRemote.class)
public class WUFFacade extends RootFacade implements WUFFacadeRemote, Serializable {
public WUFFacade() { }
#EJB
FUFHome home;
public ClientData getItems(ClientData data) {
//code here
}
public ClientData save(ClientData data) {
//code here
}
private Col load(ClientData data,InitialContext ic) {
//here i'm calling home.
// but home is always null. It was supposed to have the #EJB reference initialized.
//But instead I get a null pointer...
home.findByFilter(loader);
}
}
#Remote(FUFHome.class)
public interface FUFHome {
FUF create(FUFValue fUFValue);
FUF findByPrimaryKey(FUFPK pk);
Collection findByFilter(FacadeLoader loader);
}
public interface WUFFacadeRemote{
public ClientData getItems(ClientData data);
public ClientData save(ClientData data);
}
I don't have ejb-jar.xml anymore, the deploy is sucessfully done and Wildfly starts with no errors. Then the first time I call the page in question, it seems that #EJB is working (Debug is "Proxy for remote EJB StatelessEJBLocator for "bus-facade/WUFFacade", view is interface com.wuf.WUFFacadeRemote, affinity is None"), the value is not null, but for all subsequent calls, my variable is null and I got a NullPointerException.
I really don't know what i'm doing wrong (maybe i'm completely lost), but to me, #EJB should be working correctly like that. What am I missing? Thanks.
As i'm using EJB3.x i'm just using annotations now, (this seems to be ok).
JNDIs:
JNDI bindings for session bean named FUF in deployment
java:global/fumo/bus-entities-fumo/FUF!apyon.components.fumo.fuf.FUF
java:app/bus-entities-fumo/FUF!apyon.components.fumo.fuf.FUF
java:module/FUF!apyon.components.fumo.fuf.FUF
java:global/fumo/bus-entities-fumo/FUF
java:app/bus-entities-fumo/FUF
java:module/FUF
JNDI bindings for session bean named WUFFacade
java:global/fumo/bus-facade-fumo/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:app/bus-facade-fumo/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:module/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:jboss/exported/fumo/bus-facade-fumo/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:global/fumo/bus-facade-fumo/WUFFacade
java:app/bus-facade-fumo/WUFFacade
java:module/WUFFacade
I think I found a possible solution to the problem. I'll still try to find another one, but this is good so far.
After changing to a .war and keeping my other projects in .ears it's working. Maybe the problem was because I have a RootController servlet im my main.ear, which is the starting point of the aplication. The context starts there and then it redirects to fumo.ear (now fumo.war).
For some reason, I always was getting a null in my EJB after entering a page. It was always hapening when I first entered a JSP and tried to call the page again. My solution to this is:
#WebServlet(urlPatterns = "windows/wUF.do", loadOnStartup = 1)
public class WUFAction extends HttpServlet {
private WUFFacadeRemote engine;
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
doPost(req, resp);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
if(engine == null) {
InitialContext ic;
try {
ic = new InitialContext();
engine = (WUFFacadeRemote) ic.lookup("java:global/fumo/WUFFacade!fumo.wuf.WUFFacadeRemote");
} catch (NamingException e) {
e.printStackTrace();
}
}
//here I always have the context now.
}
}
And as a .war my structure now looks like this:
So other annotations like #Inject and #EJB are now working. Always when i'm being redirect from a JSP calling a Servlet or some action, I first check if the context is not null, otherwise I lookup it. My #Stateless are working and the #PersistenceContext and #Remote are working too.
#Stateless
public class WUFFacade implements WUFFacadeRemote {
#Inject
private FUFRules rules;
#EJB
private FUFHome home;
private Col load(ClientData data, InitialContext ic) throws InterfaceException {
try {
// home here is nor null anymore.
Collection res = (Collection) home.findByFilter(loader);
...
} catch (InterfaceException e) {
e.printStackTrace();
}
...
return data;
}
}
So I'd like to thank everyone who helped in the thread. It was a good way to understand and see the problem or to find a workaround. As I said, I'll still try the .ear in the future, but as a simplified packaging it definitely works.

Spring Boot Rest : Error 404 not found when posting JSON via Postman

I am trying to invoke a POST service via Postman. My application is running on embedded tomcat server. However when I try to invoke the service, the error I get is "No mapping found for HTTP request with URI [/findrouting] in DispatcherServlet with name 'dispatcherServlet'"
It is not even recognizing http:localhost:8080/
RoutingRequest and RoutingResponse are the POJOs with getters and setters.
Am I missing something here. I did check lots of examples but didn't find any solution to my problem.
Please see my code below :
package com.ab.hello.ambassador.server;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(AmbassadorApplication.class, args);
System.out.println("List of Beans instantiated");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
package com.ab.hello.ambassador.server.controller;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.dp.connect.ambassador.server.RoutingRequest;
import com.dp.connect.ambassador.server.RoutingResponse;
#RestController
public class ApplicationController {
#RequestMapping("/")
public String index() {
return "Spring Boot POC Welcomes You!";
}
#RequestMapping(method = POST, value = "/findrouting", consumes = { APPLICATION_JSON_VALUE }, produces = {
APPLICATION_JSON_VALUE })
public RoutingResponse findRoute(#RequestBody RoutingRequest request) throws Exception {
// some business logic that would return response; as of now I have set it to null
RoutingResponse response = null;
return response;
}
}
Thanks for your time. After struggling for quite a long time. I figured out this piece of code. Added annotation #EnableWebMvc. This solved my problem.
#SpringBootApplication
#EnableWebMvc
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Try to define the path in your controller:
#RestController
#RequestMapping("/")
public class ApplicationController {
#RequestMapping
public String index() {
return "Spring Boot POC Welcomes You!";
}
#RequestMapping(method = POST, value = "/findrouting", consumes = { APPLICATION_JSON_VALUE }, produces = {
APPLICATION_JSON_VALUE })
public RoutingResponse findRoute(#RequestBody RoutingRequest request) throws Exception {
// some business logic that would return response; as of now I have set it to null
RoutingResponse response = null;
return response;
}
}
Change the below line
ApplicationContext ctx = SpringApplication.run(AmbassadorApplication.class, args);
with
ApplicationContext ctx = SpringApplication.run(Application.class, args);
according to spring docs , seems need to Override a config method:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}

Eclipse: EJB and ManagedBean(for JSF)

I'm trying to create some Java EE application. The base is EJB as a controller. Next I want to present the data with JSF+ManagedBeans. The problem is there is
javax.servlet.ServletException: standards/SampleController
java.lang.NoClassDefFoundError: standards/SampleController
The Code looks like this:
Managed bean(Dynamic Web Project):WebView project: StdSampleController.java:
import javax.ejb.EJB;
import standards.SampleController;
public class StdSampleController {
#EJB private SampleController c;
public String value;
public StdSampleController() {
c = new SampleController();
value = c.getValue();
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
EJB(EJB Project): WebController project: standards.SampleController.java:
package standards;
import javax.ejb.Stateless;
/**
* Session Bean implementation class SampleController
*/
#Stateless
public class SampleController implements SampleControllerRemote {
private String value;
public SampleController() {
value = "EJB:SampleController bean";
}
public String getValue(){
return value;
}
}
All this code is put together in an Enterprise Application Project.
I use GlassFish version 3 and Eclipse 3.5.2.
Adding to the answer of unbeli, please remove the following from your code:
public StdSampleController() {
c = new SampleController();
value = c.getValue();
}
This is wrong. In the situation you're depicting, c will be injected by the container with a reference to your EJB. Do not instantiate the EJB yourself via the new() operator.
You call your EJB using the (remote) interface, not it's implementation.
Therefore, instead of
#EJB private SampleController c;
you need
#EJB private SampleControllerRemote c;
and adjust imports accordingly.

Starting Selenium with custom Firefox profile from Eclipse

I'm running Selenium tests from within Eclipse, but I can't load a custom Firefox profile.
Most sources suggest I need to launch the Selenium Server like this:
java -jar selenium-server.jar -firefoxProfileTemplate </path/to/template/>
But when launching my test from within Eclipse it doesn't use that - the tests will run if the Selenium Server isn't running.
This thread suggests that I can set the profile in the DefaultSelenium constructor:
Selenium RC - disabling browser cookie
But the code generated for me by Selenium IDE (Firefox plugin) doesn't use that constructor:
package com.example.tests;
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;
public class Example extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://www.example.com/", "*firefox");
}
public void testExample() throws Exception {
selenium.open("/");
selenium.click("//body");
}
}
Where should I set the DefaultSelenium configuration options? Or is there some other method I can use to load my custom Firefox template?
Thanks!
Stu
I made a SeleniumTestCase that starts/stops the server before/after each test class and starts/stops the Selenium instance before/after each test:
public class SeleniumTestCase {
protected static Selenium selenium;
protected static AppNavUtils appNavUtils;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
SeleniumServerControl.getInstance().startSeleniumServer();
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
SeleniumServerControl.getInstance().stopSeleniumServer();
}
#Before
public void setUp() throws Exception {
// Replace "*chrome" with "*firefox" for Selenium > 1.0
selenium = new DefaultSelenium("localhost", 5444, "*chrome", "http://localhost:8080/");
selenium.start();
appNavUtils = new AppNavUtils(selenium);
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
The SeleniumServerControl starts and stops the server:
public class SeleniumServerControl {
private static final SeleniumServerControl instance = new SeleniumServerControl();
public static SeleniumServerControl getInstance()
{
return instance;
}
private SeleniumServer server = null;
protected SeleniumServerControl(){}
public void startSeleniumServer() {
if (server == null) {
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setPort(5444);
//rcc.setFirefoxProfileTemplate(newFirefoxProfileTemplate)
server = new SeleniumServer(rcc);
}
server.start();
}
public void stopSeleniumServer()
{
if (server != null) {
server.stop();
server = null;
}
}
}
the version of code you have above assumes that you are running your tests against localhost on port 4444 thats why it is has 2 parameters in the setup.
To set up eclipse to run it you will need to update the run configuration. That is under
Run > Run Configurations
Have a look for the item that has selenium in it and add the config above so that when it runs it will pick it up and run.
I personally just fire up the server when I start working by running a batch file and kill it at the end of the day.