call Ejb - Java javax.naming

Java examples for javax.naming:Context

Description

call Ejb

Demo Code


import java.lang.reflect.Method;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;

public class Main{
    static Logger logger = Logger.getLogger(EjbUtils.class);
    public static Object callEjb(String ejbName, String ejbMethod,
            Object[] parameters, Class<?> parametersTypes)
            throws NamingException {

        Method mthdRemote = null;
        Object objRemote = null;/*from   w w w .ja va2  s.c  om*/

        String ejbNameRemote = "";
        String ejbNameLocal = "";
        Context ejbContext = new InitialContext();

        try {
            Object objRef = ejbContext.lookup(ejbName);
            Class<?> clazz = objRef.getClass();
            Method mthd = clazz.getMethod("create");
            objRemote = (Object) mthd.invoke(objRef, ejbName);
            logger.debug("EjbUtils::callEjb::Find EJB 2");
        } catch (Throwable e) {
            logger.warn("EjbUtils:callEjb:: Dont find EJB 2::" + ejbName
                    + ", with Method::" + ejbMethod);
            try {
                ejbNameRemote = ejbName + "/remote";
                objRemote = ejbContext.lookup(ejbNameRemote);
                logger.debug("EjbUtils::callEjb::Find EJB 3 remote");
            } catch (Throwable t) {
                logger.warn("EjbUtils:callEjb:: Dont find EJB 3 remote::"
                        + ejbName + ", with Method::" + ejbMethod);
                try {
                    ejbNameLocal = ejbName + "/local";
                    objRemote = ejbContext.lookup(ejbNameLocal);
                } catch (Throwable w) {
                    logger.warn("EjbUtils:callEjb:: Dont find EJB 3 local::"
                            + ejbName + ", with Method::" + ejbMethod);
                    throw new NamingException("Dont Find EJB 2 or 3::"
                            + ejbName + ", with Method::" + ejbMethod);
                }
            }
        }

        Class<?> clazzRemote = objRemote.getClass();
        try {
            mthdRemote = clazzRemote.getMethod(ejbMethod, parametersTypes);
            return mthdRemote.invoke(objRemote, parameters);
        } catch (Throwable e) {
            logger.error(
                    "UploadFilesUtils::getResultEjb::Error al llamar el ejb remoto::",
                    e);
        } finally {
            ejbContext.close();
        }

        return null;

    }
}

Related Tutorials