Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available - ejb

I created an EJB project and another project to test the first.
This screenshot gives an overview about my two projects.
The class main on the test project is:
public class TestEjb
{
public static void main(String[] args)
{
GestionEmployeeRemote gestion = null;
try {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
Object o = context.lookup("ejb:/FirstEJBProject/GestionEmployee!services.GestionEmployeeRemote");
gestion = (GestionEmployeeRemote) o;
} catch (NamingException e) {
e.printStackTrace();
}
createEmployee(gestion);
}
public static void createEmployee(GestionEmployeeRemote gestion)
{
Employee employee = new Employee("Foulen", "Ben Foulen", new Date(), "Directeur");
gestion.createEmployee(employee);
}
The file jndi.properties is:
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.provider.url=remote://localhost:4447
jboss.naming.client.ejb.context=true
jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
The class GestionEmployee.java is:
package services;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import persistance.Employee;
/**
* Session Bean implementation class GestionEmployee
*/
#Stateless
public class GestionEmployee implements GestionEmployeeRemote, GestionEmployeeLocal {
#PersistenceContext
EntityManager em;
public GestionEmployee() {
// TODO Auto-generated constructor stub
}
#Override
public void createEmployee(Employee employee) {
em.persist(employee);
}
#Override
public void updateEmployee(Employee employee) {
em.merge(employee);
}
#Override
public void deleteEmployee(Employee employee) {
em.remove(employee);
}
#Override
public Employee getEmployeeById(int idEmployee) {
Employee elmployee = em.find(Employee.class, idEmployee);
return null;
}
#Override
public List<Employee> getAllEmployee() {
Query query = em.createQuery("select e from Employee e");
return query.getResultList();
}
}
The class GestionEmployeeRemote.java is:
package services;
import java.util.List;
import javax.ejb.Remote;
import persistance.Employee;
#Remote
public interface GestionEmployeeRemote
{
public void createEmployee (Employee employee);
public void updateEmployee (Employee employee);
public void deleteEmployee (Employee employee);
public Employee getEmployeeById (int idEmployee);
public List<Employee> getAllEmployee();
}
After running the class main, I got this error:
Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:, moduleName:FirstEJBProject, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#a47962
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:749)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy0.createEmployee(Unknown Source)
at test.TestEjb.createEmployee(TestEjb.java:37)
at test.TestEjb.main(TestEjb.java:31)
I'm looking for finding a solution for this issue, any help is appreciated.Thanks a lot.

Related

Update label from nested function called from Task API in JavaFX

I am performing some background task using this class
class Download extends Task{
protected Object call() throws Exception {
try {
updateMessage("Establishing Connection");
DownloadHelper downloadHelper = new DownloadHelper();
downloadHelper.performTask();
return null;
} catch (IOException | ParseException ex) {
logger.error(ExceptionUtils.getStackTrace(ex));
throw ex;
}
}
}
This Task in turn calls DownloadHelper to perform some task.
class DownloadHelper{
public DownloadHelper(){
}
public void performTask(){
----
----
}
}
Is there a way to update the status message of the Task API (updateMessage()) from the DownloadHelper class.?
The expedient approach is to pass a reference to the Download task as a parameter to the DownloadHelper constructor. To minimize coupling, you can instead pass a reference to your implementation of updateMessage() as a parameter of type Consumer, "an operation that accepts a single input argument and returns no result."
DownloadHelper helper = new DownloadHelper(this::updateMessage);
Your helper's implementation of performTask() can then ask the updater to accept() messages as needed.
Consumer<String> updater;
public DownloadHelper(Consumer<String> updater) {
this.updater = updater;
}
public void performTask() {
updater.accept("Helper message");
}
A related example is seen here.
import java.util.function.Consumer;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* #see https://stackoverflow.com/q/45708923/230513
*/
public class MessageTest extends Application {
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("MessageTest");
StackPane root = new StackPane();
Label label = new Label();
root.getChildren().add(label);
Scene scene = new Scene(root, 320, 120);
primaryStage.setScene(scene);
primaryStage.show();
Download task = new Download();
task.messageProperty().addListener((Observable o) -> {
label.setText(task.getMessage());
});
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
private static class Download extends Task<String> {
#Override
protected String call() throws Exception {
updateMessage("Establishing connection");
DownloadHelper helper = new DownloadHelper(this::updateMessage);
helper.performTask();
return "MessageTest";
}
#Override
protected void updateMessage(String message) {
super.updateMessage(message);
}
}
private static class DownloadHelper {
Consumer<String> updater;
public DownloadHelper(Consumer<String> updater) {
this.updater = updater;
}
public void performTask() {
updater.accept("Helper message");
}
}
public static void main(String[] args) {
launch(args);
}
}

Simple example for 'ScheduledService' in Javafx

I am a student and learning JavaFX since a month.
I am developing a application where I want a service to repeatedly start again after its execution of the task. For this I have come to know that 'ScheduledService' is used.
So can anybody please explain the use of scheduledservice with simple example and also how it differs from the 'Service' in JavaFX. Thanks ;)
EDIT : How can I define that this ScheduledService named DataThread should be restarted every 5 seconds ?
public class DataThread extends ScheduledService<Void>
{
#Override
public Task<Void> createTask() {
return new Task<Void>() {
#Override
public Void call() throws Exception {
for(i=0;i<10;i++)
{
System.out.println(""+i);
}
return null;
}
};
}
}
Considering you have a sound knowledge of Service class. ScheduledService is just a Service with a Scheduling functionality.
From the docs
The ScheduledService is a Service which will automatically restart itself after a successful execution, and under some conditions will restart even in case of failure
So we can say it as,
Service -> Execute One Task
ScheduledService -> Execute Same Task at regular intervals
A very simple example of Scheduled Service is the TimerService, which counts the number of times the Service Task has been called. It is scheduled to call it every 1 second
import java.util.concurrent.atomic.AtomicInteger;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TimerServiceApp extends Application {
#Override
public void start(Stage stage) throws Exception {
TimerService service = new TimerService();
AtomicInteger count = new AtomicInteger(0);
service.setCount(count.get());
service.setPeriod(Duration.seconds(1));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
System.out.println("Called : " + t.getSource().getValue()
+ " time(s)");
count.set((int) t.getSource().getValue());
}
});
service.start();
}
public static void main(String[] args) {
launch();
}
private static class TimerService extends ScheduledService<Integer> {
private IntegerProperty count = new SimpleIntegerProperty();
public final void setCount(Integer value) {
count.set(value);
}
public final Integer getCount() {
return count.get();
}
public final IntegerProperty countProperty() {
return count;
}
protected Task<Integer> createTask() {
return new Task<Integer>() {
protected Integer call() {
//Adds 1 to the count
count.set(getCount() + 1);
return getCount();
}
};
}
}
}

Cast String in JavaFX ComboBox

I'm trying to use this to select a value from a Custom Combo Box:
import java.util.List;
import javafx.application.Application;
import static javafx.application.Application.launch;
import static javafx.application.Application.launch;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class MainApp extends Application
{
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage)
{
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.setButtonCell(new GroupListCell());
listGroups.setCellFactory(new Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>()
{
#Override
public ListCell<ListGroupsObj> call(ListView<ListGroupsObj> p)
{
return new GroupListCell();
}
});
listGroups.setEditable(true);
listGroups.setConverter..............
// Insert Some data
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");
listGroups.getItems().addAll(ob);
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Test2");
listGroups.getItems().addAll(osb);
listGroups.setValue(ob);
// Display the selected Group
listGroups.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ListGroupsObj>()
{
#Override
public void changed(ObservableValue<? extends ListGroupsObj> arg0, ListGroupsObj arg1, ListGroupsObj arg2)
{
if (arg2 != null)
{
System.out.println("Selected Group: " + arg1.getGroupId() + " - " + arg2.getGroupName());
}
}
});
final StackPane layout = new StackPane();
layout.getChildren().add(listGroups);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
class GroupListCell extends ListCell<ListGroupsObj>
{
#Override
protected void updateItem(ListGroupsObj item, boolean empty)
{
super.updateItem(item, empty);
if (item != null)
{
setText(item.getGroupId() + " - " + item.getGroupName());
}
}
}
private List<ListGroupsObj> listGroups;
public static class ListGroupsObj
{
private int groupId;
private String groupName;
public static ListGroupsObj newInstance()
{
return new ListGroupsObj();
}
public ListGroupsObj()
{
}
public ListGroupsObj groupId(int groupId)
{
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName)
{
this.groupName = groupName;
return this;
}
public int getGroupId()
{
return groupId;
}
public String getGroupName()
{
return groupName;
}
#Override
public String toString()
{
return groupId + " - " + groupName;
}
}
public class GroupConverter extends StringConverter<ListGroupsObj>
{
#Override
public String toString(ListGroupsObj obj)
{
return obj.getGroupId() + " - " + obj.getGroupName();
}
#Override
public ListGroupsObj fromString(String obj)
{
//TODO when you type for example "45 - NextGroup" you want to take only tyhe number"
return ListGroupsObj.newInstance().groupName(obj);
}
}
}
I get this error when I click outside of the comboBox:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.String cannot be cast to com.selectmenuexample.MainApp$ListGroupsObj
I found that this can be done using convertor but I'm now aware how to use it. Can you help with this implementation?
Here is what is wrong:
You called your ComboBox listGroups and your List of Items listGroups. So in your start code, you were hiding that variable. So I removed that useless variable since you can manipulate Items directly in the ComboBox.
You had basically three methods/variable doing the exact same things. Converting your Object into a String with a "-" between them. So I removed the GroupConverter and the custom cellFactory. You don't need them because you already have your "toString()" method in your ListGroupsObj which is doing the job.
Then you misunderstood how the ComboBox is working. If it's editable, the ComboBox will allow something to be typed inside the TextField. That's where the StringConverter comes. It will allow you to make the conversion between a String and your ListGroupsObj and the way around.
In order to go from a ListGroupsObj to a String, simply call the "toString()" method on your object.
But in the way around, you should either create a new ListGroupsObj, or verify that what's inside the ComboBox is not already one item of yours. For example, if you select an Item in the comboBox, the fromString() will be called. But you don't want to create a new ListGroupsObj, you just want to isolate the ListGroupsObj inside your items List and returns it.
Now, you have the guaranty that a call to getValue() on your ComboBox will always return an ListGroupsObj object since you have provided a custom and valid StringConverter.
Here is a simplified and working version of your code :
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class MainApp extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
final ComboBox<ListGroupsObj> comboBox = new ComboBox();
comboBox.setEditable(true);
comboBox.setConverter(new StringConverter<ListGroupsObj>() {
#Override
public String toString(ListGroupsObj obj) {
return obj.toString();
}
#Override
public ListGroupsObj fromString(String obj) {
//Here we try to identify if the given String actually represents one item of our list
for(ListGroupsObj tempObj:comboBox.getItems()){
if(tempObj.toString().equals(obj)){
return tempObj;
}
}
//If not we just create a new one
return ListGroupsObj.newInstance().groupName(obj);
}
});
// Insert Some data
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");
comboBox.getItems().addAll(ob);
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Test2");
comboBox.getItems().addAll(osb);
comboBox.setValue(ob);
final StackPane layout = new StackPane();
layout.getChildren().add(comboBox);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
public static class ListGroupsObj {
private int groupId;
private String groupName;
public static ListGroupsObj newInstance() {
return new ListGroupsObj();
}
public ListGroupsObj() {
}
public ListGroupsObj groupId(int groupId) {
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName) {
this.groupName = groupName;
return this;
}
public int getGroupId() {
return groupId;
}
public String getGroupName() {
return groupName;
}
#Override
public String toString() {
return groupId + " - " + groupName;
}
}
}
PS: The issue was already raised in the official JavaFX issue Tracker, I'll leave the link here since there is another example in the ticket (login required) : https://javafx-jira.kenai.com/browse/RT-29118

Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Fault occurred while processing

I &m trying to expose my data base using a web service , i am using a postgresql data base , ejb 3.1 and , CXF as webservice framework.
This is the entity
package persistance.model;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: ENVOI
*
*/
#Entity
#Table(name = "Envoi")
#NamedQueries({#NamedQuery(name="Envoi.getAll", query="Select e from Envoi e")})
public class Envoi implements Serializable {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column
private int Numet;
#Column
private int Numseq;
#Column
private int Valadler;
#Column
private String Typemess;
#Column
#Temporal(TemporalType.DATE)
private Date Horodatage;
#Column
private String Appli;
#Column
private String Versproto;
#Column
private String Data;
#Column
private String ACK;
private static final long serialVersionUID = 1L;
public Envoi() {
super();
}
public int getNumet() {
return this.Numet;
}
public void setNumet(int Numet) {
this.Numet = Numet;
}
public int getNumseq() {
return this.Numseq;
}
public void setNumseq(int Numseq) {
this.Numseq = Numseq;
}
public int getValadler() {
return this.Valadler;
}
public void setValadler(int Valadler) {
this.Valadler = Valadler;
}
public String getTypemess() {
return this.Typemess;
}
public void setTypemess(String Typemess) {
this.Typemess = Typemess;
}
public Date getHorodatage() {
return this.Horodatage;
}
public void setHorodatage(Date Horodatage) {
this.Horodatage = Horodatage;
}
public String getAppli() {
return this.Appli;
}
public void setAppli(String Appli) {
this.Appli = Appli;
}
public String getVersproto() {
return this.Versproto;
}
public void setVersproto(String Versproto) {
this.Versproto = Versproto;
}
public int getId() {
return this.Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getData() {
return this.Data;
}
public void setData(String Data) {
this.Data = Data;
}
public String getACK() {
return this.ACK;
}
public void setACK(String ACK) {
this.ACK = ACK;
}
}
Now here the DAO
this one is generic
package persistance.dao;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//import javax.persistence.criteria.CriteriaQuery;
public abstract class GenericDAO<T> {
private final static String UNIT_NAME = "MestaPU";
#PersistenceContext(unitName = UNIT_NAME)
private EntityManager em;
private Class<T> entityClass;
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void save(T entity) {
em.persist(entity);
}
protected void delete(Object id, Class<T> classe) {
T entityToBeRemoved = em.getReference(classe, id);
em.remove(entityToBeRemoved);
}
public T update(T entity) {
return em.merge(entity);
}
public T find(int entityID) {
return em.find(entityClass, entityID);
}
// Using the unchecked because JPA does not have a
// em.getCriteriaBuilder().createQuery()<T> method
/* #SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}*/
// Using the unchecked because JPA does not have a
// ery.getSingleResult()<T> method
/* #SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = em.createNamedQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}*/
/* private void populateQueryParameters(Query query, Map<String, Object> parameters) {
for (Entry<String, Object> entry : parameters.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}*/
}
this one is spécifique to Envoi entity
package persistance.dao;
import javax.ejb.Stateless;
import persistance.model.*;
#Stateless
public class EnvoiDAO extends GenericDAO<Envoi> {
public EnvoiDAO() {
super(Envoi.class);
}
public void delete(Envoi envoi) {
super.delete(envoi.getId(), Envoi.class);
}
}
This is the Facade to expose the ejb
package persistance.facade;
import java.util.List;
import javax.ejb.Local;
import javax.jws.WebService;
import persistance.model.Envoi;
#WebService
#Local
public interface EnvoiFacade {
public abstract void save(Envoi envoi);
public abstract Envoi update(Envoi envoi);
public abstract void delete(Envoi envoi);
public abstract Envoi find(int entityID);
public abstract List<Envoi> findAll();
}
package persistance.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import persistance.dao.EnvoiDAO;
import persistance.model.Envoi;
#WebService
#Stateless
public class EnvoiFacadeImp implements EnvoiFacade {
#EJB
private EnvoiDAO envoiDAO;
public void save(Envoi envoi) {
envoiDAO.save(envoi);
}
public Envoi update(Envoi envoi) {
return envoiDAO.update(envoi);
}
public void delete(Envoi envoi) {
envoiDAO.delete(envoi);
}
public Envoi find(int entityID) {
// TODO Auto-generated method stub
return null;
}
public List<Envoi> findAll() {
// TODO Auto-generated method stub
return null;
}
/*public Envoi find(int entityID) {
return envoiDAO.find(entityID);
}*/
/*public List<Envoi> findAll() {
return envoiDAO.findAll();
}*/
}
Now you will find the spring bean that publishes the service
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint
id="orderProcess"
implementor="demo.order.OrderProcessImpl"
address="/OrderProcess" />
<jaxws:endpoint
id="EnvoiFacade"
implementor="persistance.facade.EnvoiFacadeImp"
address="/EnvoiFacade" />
</beans>
Now you'll find the client and the bean associated to it
package demo.ejb.client;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import persistance.facade.EnvoiFacade;
import persistance.model.Envoi;
public final class Client {
public Client() {
}
public static void main(String args[]) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "demo/ejb/client/client-beans.xml" });
EnvoiFacade client = (EnvoiFacade) context.getBean("envoiClient");
Envoi p1 = new Envoi();
p1.setNumet(3690);
p1.setNumseq(9990);
client.save(p1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:client id="envoiClient" serviceClass="persistance.facade.EnvoiFacade" address="http://localhost:8080/orderapp/EnvoiFacade" >
</jaxws:client>
</beans>
Now my webservice deploy just fin in JBOSS 7.1.0 AS , i created the datasources and included the driver for postgres my sql , the problem is when a run the client i get this error
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Fault occurred while processing.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:143)
at $Proxy57.save(Unknown Source)
at demo.ejb.client.Client.main(Client.java:23)
Caused by: org.apache.cxf.binding.soap.SoapFault: Fault occurred while processing.
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.unmarshalFault(Soap11FaultInInterceptor.java:75)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:46)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:35)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:96)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:69)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:34)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:658)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2139)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2022)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1947)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:632)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:472)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:302)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:254)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:123)
... 2 more
I had a similar stack trace recently and I found out I was missing a classic setter on one of my fields.

Null Pointer exception in ejb 2.0 while referring a local beans home interface

I am just trying out examples of entity beans. I am using JBOSS 4.0.0, EJB 2.0, MyEclipse 8.6. Reason for using JBOSS 4.0.0 and EJB 2.0 is just for learning sake. I am reading head first book. In the process help me if I made any mistakes. I wrote a build file using ant to deploy this in deploy directory of JBOSS. Don't know where I went wrong, but struggling with error. I am getting this error:
java.lang.NullPointerException
at org.jboss.ejb.plugins.local.LocalHomeProxy.invoke(LocalHomeProxy.java:118)
at $Proxy0.findByPrimaryKey(Unknown Source)
at AccesesPackage.DirectorMovie.go(DirectorMovie.java:24)
at AccesesPackage.DirectorMovie.main(DirectorMovie.java:13)
Thank you in advance.
My ejb-jar.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<display-name>EJB1</display-name>
<enterprise-beans>
<session>
<display-name>AdviceBean</display-name>
<ejb-name>AdviceBean</ejb-name>
<home>headfirst.AdviceHome</home>
<remote>headfirst.Advice</remote>
<ejb-class>headfirst.AdviceBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
<session>
<display-name>AdviceStatefullBean</display-name>
<ejb-name>AdviceStatefullBean</ejb-name>
<home>headfirstStatefull.AdviceHomeStatefull</home>
<remote>headfirstStatefull.AdviceStatefull</remote>
<ejb-class>headfirstStatefull.AdviceStatefullBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Bean</transaction-type>
</session>
<entity>
<display-name>MovieBean</display-name>
<ejb-name>MovieBean</ejb-name>
<local-home>movie.MovieHome</local-home>
<local>movie.Movie</local>
<ejb-class>movie.MovieBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>moviebean</abstract-schema-name>
<cmp-field><field-name>movieId</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>genre</field-name></cmp-field>
<cmp-field><field-name>directorId</field-name></cmp-field>
<cmp-field><field-name>year</field-name></cmp-field>
<primkey-field>movieId</primkey-field>
<security-identity>
<use-caller-identity></use-caller-identity>
</security-identity>
<query>
<query-method>
<method-name>findByPrimaryKey</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(m) FROM moviebean m WHERE m.movieId = ?1</ejb-ql>
</query>
</entity>
<entity>
<display-name>DirectorBean</display-name>
<ejb-name>DirectorBean</ejb-name>
<local-home>director.DirectorHome</local-home>
<local>director.Director</local>
<ejb-class>director.DirectorBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>directorbean</abstract-schema-name>
<cmp-field><field-name>directorId</field-name></cmp-field>
<cmp-field><field-name>oscarWinner</field-name></cmp-field>
<cmp-field><field-name>degrees</field-name></cmp-field>
<cmp-field><field-name>name</field-name></cmp-field>
<primkey-field>directorId</primkey-field>
<security-identity>
<use-caller-identity></use-caller-identity>
</security-identity>
<query>
<query-method>
<method-name>findByPrimaryKey</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(d) FROM directorbean d WHERE d.directorId = ?1</ejb-ql>
</query>
<query>
<query-method>
<method-name>ejbSelectGetAllMovies</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(m) FROM moviebean m WHERE m.directorId = ?1</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relationship-role>
<ejb-relationship-role-name>Director-directs-many-movies</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>DirectorBean</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>movies</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Movie-has-one-director-only</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<cascade-delete />
<relationship-role-source>
<ejb-name>MovieBean</ejb-name>
</relationship-role-source>
</ejb-relationship-role>
</ejb-relation>
</relationships>
</ejb-jar>
My jboss.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>AdviceBean</ejb-name>
<jndi-name>Advisor</jndi-name>
</session>
<session>
<ejb-name>AdviceStatefullBean</ejb-name>
<jndi-name>AdvisorStatefull</jndi-name>
</session>
<entity>
<ejb-name>MovieBean</ejb-name>
<local-jndi-name>movies</local-jndi-name>
</entity>
<entity>
<ejb-name>DirectorBean</ejb-name>
<local-jndi-name>directors</local-jndi-name>
</entity>
</enterprise-beans>
</jboss>
My Director package:
Director Bean:
package director;
import java.rmi.RemoteException;
import javax.ejb.;
import java.util.;
import movie.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import AccesesPackage.ConnectionPool;
public abstract class DirectorBean implements EntityBean {
private EntityContext context;
public void ejbActivate() throws EJBException{
System.out.println("Inside director ejb activate method");
}
public void ejbLoad() throws EJBException {
System.out.println("Inside director ejb load method");
}
public void ejbPassivate() throws EJBException{
System.out.println("Inside director ejb passivate method");
}
public void ejbRemove() throws RemoveException, EJBException{
System.out.println("Inside director ejb remove method");
}
public void ejbStore() throws EJBException{
System.out.println("Inside director ejb store method");
}
public void setEntityContext(EntityContext arg0) throws EJBException{
this.context = arg0;
System.out.println("Inside director ejb set entity context method");
}
public void unsetEntityContext() throws EJBException{
System.out.println("Inside director ejb unset entity context method");
}
public abstract void setDirectorId(String id);
public abstract String getDirectorId();
public abstract void setOscarWinner(boolean b);
public abstract boolean getOscarWinner();
public abstract void setDegrees(String m);
public abstract String getDegrees();
public abstract void setName(String name);
public abstract String getName();
public abstract Collection getMovies();
public abstract void setMovies(Collection movies);
public abstract Collection ejbSelectGetAllMovies(String directorId) throws FinderException;
public String directorName(){
return this.getName();
}
public java.lang.String ejbCreate(String directorId, boolean isOscar, String degrees, String name) throws CreateException {
this.setDirectorId(directorId);
this.setOscarWinner(isOscar);
this.setDegrees(degrees);
this.setName(name);
return directorId;
}
public void ejbPostCreate(String directorId, boolean isOscar, String degrees, String name) throws CreateException {
}
public Collection getAllMovies() {
Collection coll = null;
try{
coll = this.ejbSelectGetAllMovies(this.getDirectorId());
}catch(Exception ex){
ex.printStackTrace();
}
return coll;
}
public void changeOscarStatus(String b){
Connection con= null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ejbpr","root","chaitanya");
String sql1 = "UPDATE director SET degrees = ? where directorId = ?";
PreparedStatement pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, b);
pstmt.setString(2, this.getDirectorId());
boolean update = pstmt.execute();
conn.close();
System.out.println(update);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Director Home:
package director;
import javax.ejb.;
import java.util.;
public interface DirectorHome extends EJBLocalHome {
public Director create(String directorId, boolean isOscar, String degrees, String name) throws CreateException;
public Director findByPrimaryKey(String directorId) throws FinderException;
}
Director component interface:
package director;
import javax.ejb.;
import java.util.;
public interface Director extends EJBLocalObject {
public void changeOscarStatus(String st);
public String directorName();
public Collection getAllMovies();
}
My Movie package:
Movie Bean:
package movie;
import java.rmi.RemoteException;
import javax.ejb.;
import director.;
import java.util.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
public abstract class MovieBean implements EntityBean {
private EntityContext context = null;
public void ejbActivate() throws EJBException {
System.out.println("Inside movie ejb activate method");
}
public void ejbLoad() throws EJBException {
System.out.println("Inside movie ejb load method");
}
public void ejbPassivate() throws EJBException {
System.out.println("Inside movie ejb passivate method");
}
public void ejbRemove() throws RemoveException, EJBException {
System.out.println("Inside movie ejb remove method");
}
public void ejbStore() throws EJBException, RemoteException {
System.out.println("Inside movie ejb store method");
}
public void setEntityContext(EntityContext arg0) throws EJBException {
this.context = arg0;
System.out.println("Inside movie ejb set entity context method");
}
public void unsetEntityContext() throws EJBException {
System.out.println("Inside movie ejb unset entity context method");
}
public String getMovieTitle(){
return this.getTitle();
}
public String getMovieDirectorId(){
return this.getDirectorId();
}
public String getMovieDirectorName(String directorId){
String name= null;
try{
Properties properties = new Properties();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","localhost:1099");
Context ic = new InitialContext(properties);
Object d = ic.lookup("directors");
DirectorHome dir0 = (DirectorHome)PortableRemoteObject.narrow(d, DirectorHome.class);
Director direct0 = dir0.findByPrimaryKey(directorId);
name= direct0.directorName();
}catch(Exception ex){ex.printStackTrace();}
return name;
}
public abstract String getMovieId();
public abstract void setMovieId(String movieId);
public abstract String getTitle();
public abstract void setTitle(String title);
public abstract String getYear();
public abstract void setYear(String year);
public abstract String getGenre();
public abstract void setGenre(String genre);
public abstract void setDirectorId(String directorId);
public abstract String getDirectorId();
public abstract void setDirector(Director director);
public abstract Director getDirector();
public java.lang.String ejbCreate(String movieId, String title, String year, String genre, String directorId) throws CreateException {
this.setMovieId(movieId);
this.setTitle(title);
this.setYear(year);
this.setGenre(genre);
this.setDirectorId(directorId);
return movieId;
}
public void ejbPostCreate(String movieId, String title, String year, String genre, String directorId) throws CreateException{
}
}
Movie Home:
package movie;
import javax.ejb.;
import java.util.;
public interface MovieHome extends EJBLocalHome {
public Movie create(String movieId, String title, String year, String genre, String directorId) throws CreateException;
public Movie findByPrimaryKey(String Key) throws FinderException;
}
Movie component interface:
package movie;
import javax.ejb.*;
public interface Movie extends EJBLocalObject {
public String getMovieTitle();
public String getMovieDirectorName(String directorId);
public String getMovieDirectorId();
}
Finally my client:
package AccesesPackage;
import javax.naming.*;
import java.rmi.*;
import javax.rmi.*;
import movie.*;
import director.*;
import javax.ejb.*;
import java.util.*;
public class DirectorMovie {
//public static final String localJndiName= "local/"+DirectorBean.class.getSimpleName();
public static void main(String[] args){
new DirectorMovie().go();
}
public void go(){
try{
Properties properties = new Properties();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","localhost:1099");
Context ic = new InitialContext(properties);
DirectorHome dir0 = (DirectorHome)ic.lookup("directors");
dir0.findByPrimaryKey("1");
//DirectorHome dir0 = (DirectorHome)PortableRemoteObject.narrow(d, DirectorHome.class);
// Director direct0 = dir0.create("1", true, "3", "Chaitanya");
//Collection col = direct0.getAllMovies();
//if(col.isEmpty()){
// System.out.println("The returned collection is empty");
//}
//else{
// Iterator ita = col.iterator();
// if (ita.hasNext()){
// Movie movieName = (Movie)ita.next();
// System.out.println(movieName.getMovieTitle());
// }
//}
//System.out.println(direct0.directorName());
//MovieHome mov0 = (MovieHome)ic.lookup("movies");
//MovieHome mov0 = (MovieHome)PortableRemoteObject.narrow(m, MovieHome.class);
//Movie movie0 = mov0.create("M1", "Men In Black", "2001", "Action", "1");
//System.out.println(movie0.getMovieTitle());
//String mdId = movie0.getMovieDirectorId();
//String directorName = movie0.getMovieDirectorName(mdId);
//System.out.println(directorName);
//System.out.println();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
I think that the reason is you aren't supposed to define the findByPrimaryKey in the ejb-jar.xml.
The container will built it automatically using your deployment descriptor, the findByPrimaryKey is defined only the Home interface.

Resources