I've been trying for some time to learn Java EE but I could never run an EJB example. Oracle's guide uses netbeans but I must learn how to do it in Eclipse. Neither did books did any help or youtube videos.
I can run servlets, jsp, jsf without problems but I always had problems with EJBs. What am I missing?
The problem is configuration within Eclipse I think.
My Project Structure in Eclipse is the following:
The code of HelloWorld.java file:
package helloworld.ejb;
import javax.ejb.Remote;
#Remote
public interface HelloWorld {
public String outputHelloWorld();
}
Code of the HelloWorldBean.java file
package helloworld.ejb;
import javax.ejb.Stateless;
#Stateless
public class HelloWorldBean implements HelloWorld {
public String outputHelloWorld() {
return "Hello World!";
}
}
Code of the HelloWorldClient.java
package helloworldprojectclient;
import javax.ejb.EJB;
import helloworld.ejb.HelloWorld;
public class HelloWorldClient {
#EJB
private static HelloWorld helloWorld;
public static void main (String[] args) {
System.out.println(helloWorld.outputHelloWorld());
}
}
I am using Glassfish 4.0 as a server. The HelloWorldProject is an "EJB Project" while "helloworldprojectclient" is a regular Java Project and i've added javaee.jar (from the glassfish directory) to the buildpath.
When I try to run the HelloWorldClient.java I get the following exception:
Exception in thread "main" java.lang.NullPointerException
at helloworldprojectclient.HelloWorldClient.main(HelloWorldClient.java:10)
which is the following line: System.out.println(helloWorld.outputHelloWorld());
What is the problem? I mention i'm a total beginner at EJBs. Thank you!
Just in case you are still intrested in this:
The first version doesn´t work because you are trying to inject an ejb reference in a class that is not managed by a Container. When you execute the main method, the #EJB annotation is ignored, thus 'HelloWorld' class member is never initialized.
In order to execute this code without modification, you need execute the class in a Application Client Container that will inject the ejb reference.
Your second version runs because instead of to delegate to Container, you are getting the ejb reference through the JNDI service. This is the suggested way when Container injection is no available.
I've managed to make it work. I don't know if this is the correct way but in the "helloworldprojectclient" if you set the buildpath's Project tab and add HelloWorldProject then on the Libraries tab add appserv-rt.jar and javaee.jar (both from glassfish lib folder)
then the client should look like this:
package helloworldprojectclient;
import javax.naming.InitialContext;
import helloworld.ejb.HelloWorld;
public class HelloWorldClient {
public static void main(String[] args) {
try {
InitialContext ic = new InitialContext();
HelloWorld thing = (HelloWorld) ic.lookup("helloworld.ejb.HelloWorld");
System.out.println("It seems it runs: " + thing.outputHelloWorld());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
i want to know that if "MethodOrderer" class is available in JUnit5 Library FOR ECLIPSE or not, because i am unable to find it.
If not, how can i shift jupiter.api_5.3.1 to jupiter.api_5.4.2 in eclipse JUnit5 library?
Will be thankful to see your reply.
I downloaded JUnit5 jar file from "https://search.maven.org/artifact/name.remal.tools.test/junit5/1.26.97/jar" and this jar does have "MethodOrderer" class but when i add this to project dependency and run the testclass, eclipse shows up this error "No tests found with test runner 'JUnit5'."
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
#TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class JunitCalculatorV4 {
#BeforeAll
static void setUpBeforeClass() throws Exception {
System.out.println("Before All");
}
#AfterAll
static void tearDownAfterClass() throws Exception {
System.out.println("After All");
}
#Test
#Order(1)
void addTest() {
System.out.println("Add test");
}
#Test
#Order(2)
void divideTest() {
System.out.println("Divide Test");
}
}
Actually this annotation #TestMethodOrder(MethodOrderer.OrderAnnotation.class) is from jupiter.api_5.4.2 which i added as an external jar, and that might be causing conflict with the existing JUnit5 library.
My problem would be solved if the JUnit5 library is updated as a whole, or atleast the jarfile inside the library is updated.
Project > Properties: Java Build Path, tab Libraries:
You are using Eclipse 2018-12 (4.10) with JUnit 5.3.1 instead of Eclipse 2019-03 (4.11) with JUnit 5.4.0 (the screenshot shows JAR file names containing _5.3.1.v20181005- instead of _5.4.0.v20190212-).
Please upgrade.
I have created a very basic Java Web Application with Netbeans 8.2
Here is the steps i have done:
"File" > "New Project" : "Java Web" > "Web Application"
I have created a Java Class by right clicking on project name. Then New > Java Classe
Here what i have put in this java class:
package pkg1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
public class TestService
{
#Path("/test")
#GET
#Produces("text/plain")
public String methode_test()
{
return "Hello test";
}
}
I have no compilation problem.
GlassFish is launched, but i got a 404 error if i try to go to /test url...
Any idea ?
Thanks
I made a couple of small changes to get your code working using NetBeans 8.2, JDK 8 and Glassfish 4.1.1 on Windows 10:
Add a #Path annotation on the class as well as methode_test().
Add a second class to pkg1 named ApplicationConfig which extends javax.ws.rs.core.Application as shown below.
This is the revised TestService class:
package pkg1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/demo")
public class TestService
{
#Path("/test")
#GET
#Produces("text/plain")
public String methode_test()
{
return "Hello test";
}
}
This is the additional class you need to add:
package pkg1;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("sample")
public class ApplicationConfig extends Application {
}
My project was named DemoService, and therefore had a context root of DemoService, but in your case the URL to use would probably be: http://localhost:8080/TestService/sample/demo/test
Notes:
See this answer to the SO question What is that Application class lifecycle of a rest service? for more details on why you need to create a class which extends that Application class.
For convenience you can set the default path to be used in the browser when testing your project:
Open the Properties window of your project from the Projects panel.
Select Run and set the values of Context Path and Relative URL as appropriate:
NetBeans 8.2 provides a basic "Hello World" REST application that you can create in just a few seconds using the Project Wizard: File > New Project... > Samples > Web Services > REST: Hello World.
I am using Eclipse with the Google App Engine plugin. I'm trying to run a simple program with added joda time. It seems like the error relates to the build path and I followed the instructions in:
https://stackoverflow.com/a/12105417/3255963
but I am still getting the error below. What do I need to do to next?
package test;
import java.io.IOException;
import javax.servlet.http.*;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
#SuppressWarnings("serial")
public class testServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DateTime newYears = new DateTime (2014, 1, 1, 0, 0);
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
Error:
java.lang.NoClassDefFoundError: org/joda/time/DateTime
I see the joda-time-2.3.jar in the project explorer and the build path.
I also tried selecting it under order and export.
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
Please ck whether u have the req. jars under \WebContent\WEB-INF\lib in the project explorar as well as on the project build path.
I am trying to learn OSGI. (Mainly, the dynamic loading and unloading of bundles).
Following Neil Bartlett's tutorial for How To Embed OSGi, I added The Equinox OSGi framework implementation to the class path and started the game.
Here's the code:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
public class BundleManager {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FrameworkFactory frameworkFactory = ServiceLoader.load(
FrameworkFactory.class).iterator().next();
Map<String, String> config = new HashMap<String, String>();
//TODO: add some config properties
Framework framework = frameworkFactory.newFramework(config);
framework.start();
BundleContext context = framework.getBundleContext();
List<Bundle> installedBundles = new LinkedList<Bundle>();
installedBundles.add(context.installBundle(
"file:C:/Users/student/Documents/eclipse/myPlugins/HellowService.jar"));
for (Bundle bundle : installedBundles) {
if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null)
bundle.start();
}
System.out.println("done!!");
}
}
Yes, it works. No errors at all. However, the bundle that I installed which is a jar file in the path:C:/Users/student/Documents/eclipse/myPlugins/HellowService.jar contains a "HelloWorld" in its start method. I don't see that "HelloWold" in my eclipse console. Why I don't see that message although the bundle was started? I appreciate any simple help.
Note: HellowService.jar is a plugin project that i created earlier, implemented BundleActivator in one of its classes to add "HelloWorld" message in the start method, and finally exported it as a jar file to the directory C:/Users/student/Documents/eclipse/myPlugins/
Edit: Here's my Activator class in the bundle I am installing and starting:
package com.javaworld.sample.service.impl;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import com.javaworld.sample.service.HelloService;
public class HelloServiceActivator implements BundleActivator {
ServiceRegistration helloServiceRegistration;
public void start(BundleContext context) throws Exception {
HelloServiceFactory helloServiceFactory = new HelloServiceFactory();
helloServiceRegistration =context.registerService(HelloService.class.getName(), helloServiceFactory, null);
System.out.println("Hello World!");
}
public void stop(BundleContext context) throws Exception {
helloServiceRegistration.unregister();
}
}
And here's the MANIFEST.MF file of the bundle:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: HelloService
Bundle-SymbolicName: com.javaworld.sample.HelloService
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.javaworld.sample.service.impl.HelloServiceActivator
Bundle-Vendor: JAVAWORLD
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Import-Package: org.osgi.framework;version="1.3.0"
Export-Package: com.javaworld.sample.service
The way i export the bundle is by Right Click on the bundle project->Export->Runnable Jar File->then I select the Launch Configuration to be BundleManager (Which is the class installing the bundle).
I still do not see "Hello World!" message when I start the bundle from my application.
Your launcher does not wait for the OSGi Framework to stop. I would expect this program to start everything but then immediately shut down, because we reach the end of the main method. Refer back to my tutorial where I show how to use the Framework.waitForStop method.
Having said that, I would expect the output from your HelloWorld bundle to actually appear before the shutdown. So it seems likely there is an error in that bundle also. Perhaps you haven't declared the activator? I can only guess, because you haven't given any details.
It turned out that I was exporting the bundle incorrectly. That's because I tried to do it by myself. Here's how the bundle should be exported as a jar file:
Open the plugin export wizard File > Export... > Plug-in Development >
Deployable plug-ins and fragments .
Then select the bundle you want to export and the destination directory. Done!
You can now use the path of the jar file to install the bundle. In my case, it is:
installedBundles.add(context.installBundle(
"file:C:/Users/student/Documents/eclipse/myPlugins/plugins/com.javaworld.sample.HelloService_1.0.0.201307220322.jar"));
Source: http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.pde.doc.user%2Fguide%2Ftools%2Fexport_wizards%2Fexport_plugins.htm
And for sure thanks to #Neil Bartlett
In Eclipse i have created an EAR Project with EJB Project, EJBClient Project and a WebProject.
I create a EntityBean Person and a SessionBean PersonTask at EJB Project. The Eclipse creates automatic a PersonTaskRemote Interface at EJBClient Project. And a Servlet wird created at the WebProject.
// at EJB Project
#Entity
public class Person {
private int id;
private String name;
...setter and getter
}
//SessionBean
public class PersonTask implements PersonTaskRemote {
Person findPerson(int personId){
do something;
}
And
//In EJBClient Project
//The Interface
#Remote
public interface PersonTaskRemote {
Person findPerson(int personId);
}
By Running, Eclipse get an Error! Because it hat a cycle in the Dependency (Project EJB and Project EJBClient). How can i do?
I had search in google, but in all funded tutorials the Interface in Client hat not the EntityBeans. only something like String sayHello(); functions.
How can i avoid the Problem? Maybe create the local Entities in Client Project for the Interface?
Or get me some tutorials for those cases.
thanks.
Move Person to the EJBClient module. It is clearly part of the client, because it is return value of business method. After that there is no cycle anymore, because EJBClient do not depend about other modules.