I am learning about EJB and I would like to get the following code working but so far no success.
Here's my EJB project code:
#Stateless
public class CalcBean implements ICalcRemote {
private static final long serialVersionUID = 5571798968598315142L;
#Override
public int add(int a, int b) {
return a + b;
}
}
package com.ejb.test.pckg;
import javax.ejb.Remote;
#Remote
public interface ICalcRemote extends ICalculator {
}
package com.ejb.test.pckg;
import java.io.Serializable;
public interface ICalculator extends Serializable {
public int add(int a, int b);
}
I run glassfish-4.1.1 in Eclipse Neon.
When I deploy the EJB project, I can see the following in the log:
2017-02-24T21:18:09.036-0400|Info: Portable JNDI names for EJB CalcBean: [java:global/EJBDemo/CalcBean, java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote]
2017-02-24T21:18:09.036-0400|Info: Glassfish-specific (Non-portable) JNDI names for EJB CalcBean: [com.ejb.test.pckg.ICalcRemote#com.ejb.test.pckg.ICalcRemote, com.ejb.test.pckg.ICalcRemote]
This is my client code:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.ejb.test.pckg.ICalcRemote;
public class Main {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
//
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
Context ctx = new InitialContext();
ICalcRemote calc = (ICalcRemote) ctx.lookup("java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote");
System.out.println(calc.add(5, 7));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Java-doc)
*
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
}
But I am having no luck. Any suggestions how to get this working?
Thank you!
EDIT:
This is my main (client) which includes info from the EJBDemo deployment log:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.ejb.test.pckg.ICalcRemote;
public class Main {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
//
// props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
// props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
/*
* THIS IS from Glassfish log of EJBDemo deployment
*
* 2017-02-25T20:41:47.100-0400|Info: Portable JNDI names for EJB CalcBean: [java:global/EJBDemo/CalcBean,
* java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote] 2017-02-25T20:41:47.100-0400|Info: Glassfish-specific (Non-portable) JNDI names for EJB CalcBean:
* [com.ejb.test.pckg.ICalcRemote#com.ejb.test.pckg.ICalcRemote, com.ejb.test.pckg.ICalcRemote]
*
*
*/
Context ctx = new InitialContext();
ICalcRemote calc = (ICalcRemote) ctx.lookup("java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote");
System.out.println(calc.add(5, 7));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Java-doc)
*
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
}
I finally got things working! Since it's been quite a process despite reading many posts related to this issue. Here are the details of my configuration. Hopefully, this will be useful to somebody.
OS: win 10
IDE: Eclipse Neon
App server: Glassfish 4.1.1
JDK: 1.8.0_111
I need to mention this article which eventually led me to the answer:
http://mavicode.com/2014/08/a-standalone-client-for-ejbs-running-on-glassfish-4/
So, thanks and kudos.
First, create the EJB Demo project:
package com.ejb.test.pckg;
import java.io.Serializable;
public interface ICalculator extends Serializable {
public int add(int a, int b);
}
package com.ejb.test.pckg;
import javax.ejb.Remote;
#Remote
public interface ICalcRemote extends ICalculator {
}
package com.ejb.test.pckg;
import javax.ejb.Stateless;
// #Stateless(mappedName = "chester")
#Stateless
public class CalcBean implements ICalcRemote {
private static final long serialVersionUID = 5571798968598315142L;
#Override
public int add(int a, int b) {
return a + b;
}
}
Deploy it on the server (run as > run on the server) > check the log to see the JDNI info. It should look like something like this:
2017-02-25T20:41:47.100-0400|Info: Portable JNDI names for EJB
CalcBean: [java:global/EJBDemo/CalcBean,
java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote]
2017-02-25T20:41:47.100-0400|Info: Glassfish-specific (Non-portable)
JNDI names for EJB CalcBean:
[com.ejb.test.pckg.ICalcRemote#com.ejb.test.pckg.ICalcRemote,
com.ejb.test.pckg.ICalcRemote]
After that, create Application Client Project. Main.java will be created automatically. This is my main:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.ejb.test.pckg.ICalcRemote;
public class Main {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
Context ctx = new InitialContext();
ICalcRemote calc = (ICalcRemote) ctx.lookup("java:global/EJBDemo/CalcBean!com.ejb.test.pckg.ICalcRemote");
System.out.println(calc.add(5, 43));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Java-doc)
*
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
}
At this point, my project looks like this:
And here comes the key part. Add a new external library from the Glassfish lib directory. !!! IMPORTANT: Don't just copy and paste to the path! The .jar apparently uses/references other classes in other GF jars. So just add it to the build path as an external jar instead of copy/paste.
You should be set now. Run the Main as a Java application.
This is what I get.
Related
I try to run a websocket server in a Java project that was running on Tomcat6. I have set up a Tomcat 7 server where the project now is running on.
First I tried to run the socket example of Tomcat7. This run perfectly. I copied this class to my old project. When I run the old project again all the functionalities are working like before but only the websocket server doe not work.
This is the ChatAnnotation class that I have copied from the examples from Tomcat to my old project.
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
#ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
private static Logger logger = Logger.getLogger(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections = new CopyOnWriteArraySet<ChatAnnotation>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
logger.info("ws instance");
}
#OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "has disconnected.");
broadcast(message);
}
#OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s", nickname, message.toString());
broadcast(filteredMessage);
}
#OnError
public void onError(Throwable t) throws Throwable {
logger.error("Chat Error: " + t.toString(), t);
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
logger.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s", client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
I have noting added in my web.xml. In my old project are also tcpsockets used can this be the problem?
Can anyone help me with this problem?
EDIT
Class added:
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
import org.apache.log4j.Logger;
public class ExamplesConfig implements ServerApplicationConfig {
private static Logger log = Logger.getLogger(ChatAnnotation.class);
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();
log.info("getEndpointConfigs");
return result;
}
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
log.info("getAnnotatedEndpointClasses");
return scanned;
}
}
Java websocket server use return value of ServerApplicationConfig interface to deploy programmatic endpoints and for annotated endpoints.
For Tomcat example, if you change the package name of ChatAnnotation. You have to modify websocket.ExamplesConfig too.
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
// Deploy all WebSocket endpoints defined by annotations in the examples
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<>();
for (Class<?> clazz : scanned) {
String name = clazz.getPackage().getName();
boolean ok = name.startsWith("websocket.");
if (ok) {
results.add(clazz);
}
}
return scanned;
}
The getAnnotatedEndpointClasses(scanned) only return classes which package name start with websocket. Unmatched classes will not deployed even they have #ServerEndpoint declarations.
I need to be able to call a save() method from this simple swing java app to my web app that is published on the server with the beans I use to save a new Entity type class Persona, that has name, address, email.
Im using wildfly 8.x for my server and have my web app published like this:
23:51:10,641 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-3) JNDI bindings for session bean named ContactoDAO in deployment unit deployment "proyectobase.war" are as follows:
java:global/proyectobase/ContactoDAO!edu.ups.appdis.proyectobase.negocio.ContactoDAO
java:app/proyectobase/ContactoDAO!edu.ups.appdis.proyectobase.negocio.ContactoDAO
java:module/ContactoDAO!edu.ups.appdis.proyectobase.negocio.ContactoDAO
java:global/proyectobase/ContactoDAO
java:app/proyectobase/ContactoDAO
java:module/ContactoDAO
This is my ContactoDAO Bean:
package edu.ups.appdis.proyectobase.negocio;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import edu.ups.appdis.proyectobase.modelo.Persona;
#Stateless
// #Remote(Serializable.class)
#Remote
public class ContactoDAO implements Serializable {
// #Inject
// private Logger log;
/**
*
*/
#Inject
private EntityManager em;
public void save(Persona persona) {
// if (em.find(Persona.class, persona.getCodiog()) == null) {
insertar(persona);
// } else {
//
// update(persona);
// }
}
public void test() {
System.out.println("si funciona ");
}
public void insertar(Persona persona) {
em.persist(persona);
}
public void update(Persona persona) {
em.merge(persona);
}
public void remove(int codigo) {
Persona persona = em.find(Persona.class, codigo);
em.remove(persona);
}
public Persona read(int codigo) {
System.out.println("insertado objeto persona");
return em.find(Persona.class, codigo);
}
public List<Persona> getContactos() {
String sql = "SELECT p FROM Persona p";
Query query = em.createQuery(sql, Persona.class);
List<Persona> personas = query.getResultList();
return personas;
}
}
On my simple client swing app I have it set up like this:
package cliente.gui;
import java.awt.EventQueue;
............
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.security.Security;
import java.util.Hashtable;
import edu.ups.appdis.proyectobase.modelo.Persona;
import edu.ups.appdis.proyectobase.negocio.*;
public class guiPersona {
// #EJB(lookup = "java:global/proyectobase/ContactoDAO!edu.ups.appdis.proyectobase.negocio.ContactoDAO")
#EJB(lookup = "java:global/proyectobase/ContactoDAO")
ContactoDAO contactoDAO;
private JFrame frame;
private JTextField textNombre;
private JTextField textDireccion;
private JTextField textEmail;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
guiPersona window = new guiPersona();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* #throws NamingException
*/
public guiPersona() {
initialize();
}
...........
JButton btnGuardar = new JButton("Guardar");
btnGuardar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contactoDAO.test();
if (textDireccion.getText() != "" && textEmail.getText() != "" && textNombre.getText() != "") {
Persona p = new Persona();
p.setNombre(textNombre.getText());
p.setDireccion(textDireccion.getText());
p.setEmail(textEmail.getText());
contactoDAO.save(p);
textNombre.setText("");
textDireccion.setText("");
textEmail.setText("");
}
}
});
You can see in the code above I use this to call my bean in the other proyect:
#EJB(lookup = "java:global/proyectobase/ContactoDAO")
ContactoDAO contactoDAO;
And on my button to save the new entry I use this:
if (textDireccion.getText() != "" && textEmail.getText() != "" && textNombre.getText() != "") {
Persona p = new Persona();
p.setNombre(textNombre.getText());
p.setDireccion(textDireccion.getText());
p.setEmail(textEmail.getText());
contactoDAO.save(p);
textNombre.setText("");
textDireccion.setText("");
textEmail.setText("");
}
}
});
I also tried using this:
#EJB(lookup="java:global/proyectobase/ContactoDAO!edu.ups.appdis.proyectobase.negocio.ContactoDAO")
ContactoDAO contactoDAO;
I keep getting a null pointer exception on my ContactoDAO but is it maybe because the lookup is not finding anything or Im not using it right, I dont really know. My question is what would be another way of calling my save method from my bean in another simple swing project, or maybe Im missing something else whenever I use the #EJB?
EDIT:
This is my beans.xml in case you were wondering.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
</beans>
From the log it seems that your ContactDAO and all its dependencies are correct getting initialized on the server. On the standalone swing client possibly you are missing jboss-ejb-client.properties in your META-INF folder or you can also explicitly set the initial context properties and do the JNDI lookup manually.
SE POST
Also you should make sure to include the jboss-client.jar file in the classpath of swing client project.
Wildfly Developer Guide
If you get a Authentication failed exception then you need to add username/password properties to the InitialContext and run the add-user.sh script on the server
Add User
This issue is very common. I have read some articles but can't find the problem. I want to create a simple HelloWorld program in EJB 3.0, eclipse luna, jboss 7.1.1 Final.
Here is my bean:
package com.tcs.HelloWorldPack;
import javax.ejb.Stateless;
/**
* Session Bean implementation class HelloWorld
*/
#Stateless(mappedName="HelloWorldBean")
public class HelloWorld implements HelloWorldRemote {
/**
* Default constructor.
*/
public HelloWorld() {
// TODO Auto-generated constructor stub
}
#Override
public void displayMsg() {
// TODO Auto-generated method stub
System.out.println("Hello World!!");
}
}
Here is my remote interface:
package com.tcs.HelloWorldPack;
import javax.ejb.Local;
//import javax.ejb.Remote;
import javax.ejb.Remote;
#Remote
public interface HelloWorldRemote {
void displayMsg();
}
Here is my client which is running in the same machine:
package com.tcs.HelloWorldClient;
import java.util.Hashtable;
import java.util.Properties;
import com.tcs.HelloWorldPack.*;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloWorldClient {
public static void main(String[] args) throws NamingException {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProperties.put(javax.naming.Context.SECURITY_PRINCIPAL, "myUser");
jndiProperties.put(javax.naming.Context.SECURITY_CREDENTIALS, "myPass");
// jndiProperties.put(javax.naming.Context.PROVIDER_URL, "jnp://localhost:1099");
// jndiProperties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put("jboss.naming.client.ejb.context", true);
final Context context = new InitialContext(jndiProperties);
final String appName= "HeloWorldEJBEAR";
final String moduleName= "";
final String distinctName ="";
final String beanName = "HeloWorld";
final String viewClassName = "com.tcs.HelloWorldPack.HelloWorldRemote";
HelloWorldRemote hello = (HelloWorldRemote) context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
hello.displayMsg();
}
}
This is my jboss-ejb-client.properties file:
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=myUser
remote.connection.default.password=myPass
I have put the properties file in the classpath also.But this is happening when I am trying to run it:
Exception in thread "main" java.lang.IllegalStateException: No EJB receiver available for handling [appName:HeloWorldEJBEAR,modulename:,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#413ded77
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
at com.sun.proxy.$Proxy0.displayMsg(Unknown Source)
at com.tcs.HelloWorldClient.HelloWorldClient.main(HelloWorldClient.java:71)
Jan 08, 2015 3:34:44 PM org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleEnd
INFO: Channel Channel ID de8d2aa6 (outbound) of Remoting connection 44477156 to localhost/127.0.0.1:4447 can no longer process messages
I have also uploaded my directory structure. I am new to the EJB concept. Please help me to find where is the problem. Thanks in advance.
Your module name is an empty String, but the module name can't be an empty string in the JNDI name.
Look here
you have to set the name of your ejb module .jar, without the .jar suffix.
final String moduleName = "HeloWorldEJB";
Then it should work.
As you are out to do a simple example lets keeep it simple [KISS],Most of your code is correct the catch is the client, I have simplified the client code, added my comments in client hope its self explanatory.And.... Added on EJB #javax.ejb.Stateless(name = "HelloWorldEJB") //This is portable No Vendor locked in. Alternative is mappedName [removed from your code #Stateless(mappedName="HelloWorldBean") p]which i believe is more weblogic and glassfish centric.
Ensure you have client.jar in your class path. this is the only jar you will have to add aftr you have created the EJB project in intelija or eclipse or any other ide.
I have deployed the EJB's in glassfish container once ear deployed successfully, run the client.
Apart from the below code you wont need any other configurations. This code is portable and should work on most containers however Surprises is fun do run as is and let me know .....
Once the below works for you you can add other jndi properties as per your project requirement and move on.....
==============================
The Remote
package com.au.ejbs;
import javax.ejb.Remote;
#Remote
public interface HelloWorldI {
String displayMessage(String message);
}
=================================
2. The Impl
package com.au.ejbs;
import javax.ejb.Remote;
#javax.ejb.Stateless(name = "HelloWorldEJB")
public class HelloWorld implements HelloWorldI {
#Override
public String displayMessage(String message) {
// TODO Auto-generated method stub
return "Returning from Remote" + message;
}
}
======================================
3. The client
package com.au.clients;
import com.au.ejbs.HelloWorldI;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloWorldT {
public static void main(String[] args) throws NamingException {
Context context = new InitialContext();
HelloWorldI helloWorldI = (HelloWorldI)context.lookup("java:global/ejb3_2_ear_exploded/ejb/HelloWorldEJB");
//portable syntax java:global/[ ear name]/[module name normally the jar name in my case ejb.jar within the ear, ejb3_2_ear_exploded]/name in ....javax.ejb.Stateless(name = "HelloWorldEJB")/
System.out.println( "output " + helloWorldI.displayMessage("From Client with luv...."));
}
}
===================
4. output
output Returning from RemoteFrom Client with luv....
iam getting below error when calling the ejb from jsf application
javax.naming.NamingException: ejb ref resolution error for remote business interfaceretail.ejb.service.CustomerSessionBeanRemote [Root exception is java.lang.ClassNotFoundException: retail.ejb.service.CustomerSessionBeanRemote]
here is the code below.
Interface : CustomerSessionBean
package retail.ejb.service;
import retail.model.vo.Customer;
public interface CustomerSessionBean {
public void insterCustomerDetails(Customer customer);
}
package retail.ejb.service;
import javax.ejb.Remote;
import retail.model.vo.Customer;
#Remote
public interface CustomerSessionBeanRemote extends CustomerSessionBean{
void insterCustomerDetails(Customer customer);
}
package retail.ejb.service;
import javax.ejb.Local;
import retail.model.vo.Customer;
#Local
public interface CustomerSessionBeanLocal extends CustomerSessionBean{
void insterCustomerDetails(Customer customer);
}
package retail.ejb.service;
import javax.ejb.Stateless;
import retail.model.vo.Customer;
#Stateless(name="CustomerSessionBeanImpl", mappedName="ejb/CustomerSessionBeanImplJNDI")
public class CustomerSessionBeanImpl implements CustomerSessionBeanRemote,CustomerSessionBeanLocal,CustomerSessionBean{
#Override
public void insterCustomerDetails(Customer customer) {
// TODO Auto-generated method stub
System.out.println("Customer object ::::" + customer);
}
}
package retail.web.mbean;
import java.io.Serializable;
import java.util.Properties;
import javax.faces.bean.ManagedBean;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import retail.ejb.service.CustomerSessionBeanRemote;
import retail.model.vo.Customer;
#ManagedBean
public class CustomerMB implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4402277663508618618L;
private Customer customer = new Customer();
public void CustomerMB(){
System.out.println("customer method +++++++++++++++++++++++"+getCustomer());
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String createCustomer() throws NamingException{
try{
System.out.println("in Create customer method +++++++++++++++++++++++");
Properties p = new Properties();
//properties.put("java.naming.factory.initial","com.sun.jndi.cosnaming.CNCtxFactory");
p.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.impl.SerialInitContextFactory");
p.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
p.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
p.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
p.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); //any configured port different from 3700 - 34513
InitialContext c = new InitialContext(p);
CustomerSessionBeanRemote remote = (CustomerSessionBeanRemote) c.lookup("ejb/CustomerSessionBeanImplJNDI");
remote.insterCustomerDetails(getCustomer());
}catch(Exception e){
e.printStackTrace();
}
//System.exit(1);
return "viewCustomerDetails";
}
}
Caused by: javax.naming.NamingException: ejb ref resolution error for remote business interfaceretail.ejb.service.CustomerSessionBeanRemote [Root exception is java.lang.ClassNotFoundException: retail.ejb.service.CustomerSessionBeanRemote]
at com.sun.ejb.EJBUtils.lookupRemote30BusinessObject(EJBUtils.java:433)
at com.sun.ejb.containers.RemoteBusinessObjectFactory.getObjectInstance(RemoteBusinessObjectFactory.java:75)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
at com.sun.enterprise.naming.impl.SerialContext.getObjectInstance(SerialContext.java:556)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:514)
... 43 more
Caused by: java.lang.ClassNotFoundException: retail.ejb.service.CustomerSessionBeanRemote
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at com.sun.ejb.EJBUtils.getBusinessIntfClassLoader(EJBUtils.java:687)
at com.sun.ejb.EJBUtils.loadGeneratedRemoteBusinessClasses(EJBUtils.java:462)
at com.sun.ejb.EJBUtils.lookupRemote30BusinessObject(EJBUtils.java:413)
... 47 more
Please suggest anyone
A possible reason may be
EJB 3.0 specification warns Applications that use mappedNames may not be portable
Is this working without mappedNames or by looking up full qualified bean name?
You can see the portable name of a bean in Glassfish log, use that name instead.
Now I am learner to log4j , please guide me how to create and the run simple example step by step.
From Log4J Java - A simple Log4J example
package com.devdaily.log4jdemo;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
/**
* A simple Java Log4j example class.
* #author alvin alexander, devdaily.com
*/
public class Log4JExample
{
// our log4j category reference
static final Category log = Category.getInstance(Log4JDemo.class);
static final String LOG_PROPERTIES_FILE = "lib/Log4J.properties";
public static void main(String[] args)
{
// call our constructor
new Log4JExample();
// Log4J is now loaded; try it
log.info("leaving the main method of Log4JDemo");
}
public Log4JExample()
{
initializeLogger();
log.info( "Log4JExample - leaving the constructor ..." );
}
private void initializeLogger()
{
Properties logProperties = new Properties();
try
{
// load our log4j properties / configuration file
logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
PropertyConfigurator.configure(logProperties);
log.info("Logging initialized.");
}
catch(IOException e)
{
throw new RuntimeException("Unable to load logging property " +
LOG_PROPERTIES_FILE);
}
}
}
Log4J Manual...
Basics and Intermediate Example for log4j
http://aayushtuladhar.wordpress.com/2012/12/01/testtt/
Best Doc for log4j
http://logging.apache.org/log4j/1.2/manual.html