Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

In this page you can find the example usage for javax.naming Context lookup.

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Initialize datasources./*from  w  ww . j av a  2 s.c o m*/
 *
 * @throws SQLException
 *             the SQL exception
 *             the db util exception
 */
public static void initializeDatasources() throws SQLException, DBUtilException {
    if (Datasource != null) {
        return;
    }

    try {
        log.info("Before DB Initialize");
        Context ctx = new InitialContext();
        DEP_DATA_SOURCE = (DataSourceNames.WSO2TELCO_DEP_DB.jndiName());
        Datasource = (DataSource) ctx.lookup(DEP_DATA_SOURCE);

    } catch (NamingException e) {
        handleException("Error while looking up the data source: " + DEP_DATA_SOURCE, e);
    }
}

From source file:OCCIConnectionServlet.java

public static ConnectionPoolDataSource getConnectionPoolDataSource(String baseName) {
    Context context = null;
    ConnectionPoolDataSource cpds = null;
    try {//from  w ww  . j  av  a  2 s  . co m
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "file:/JNDI/JDBC");
        context = new InitialContext(properties);
        cpds = (ConnectionPoolDataSource) context.lookup(baseName);
    } catch (NamingException e) {
        System.err.println(e.getMessage() + " creating JNDI context for " + baseName);
    }
    return cpds;
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*from  w  ww  . j a  v a2  s  .c  o m*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:org.apache.synapse.commons.transaction.TranscationManger.java

public static void lookUp(Context txContext) throws Exception {
    long key = Thread.currentThread().getId();
    Map<Long, TransactionManager> txMgrMap = txManagers.get();
    if (txMgrMap.containsKey(key)) {

    } else {//from  ww w  .j a v  a  2s  . c  o m
        TransactionManager transactionManager = (TransactionManager) txContext
                .lookup(TRANSCATION_MANGER_LOOKUP_STR);
        txMgrMap.put(key, transactionManager);
        if (log.isDebugEnabled()) {
            StringBuilder logMsg = new StringBuilder();
            logMsg.append(" Transaction Mgr Hashcode : " + transactionManager.hashCode()).append("\n")
                    .append(" Transaction Mgr  : " + transactionManager);
            log.debug(logMsg.toString());

        }

    }

}

From source file:com.wso2telco.gsma.authenticators.dao.impl.AttributeConfigDaoImpl.java

private static void initializeConnectDatasource() throws NamingException {
    if (mConnectDatasource != null) {
        return;//from w w w. j  a va 2s .c  o  m
    }

    String dataSourceName = null;
    try {
        Context ctx = new InitialContext();
        ConfigurationService configurationService = new ConfigurationServiceImpl();
        dataSourceName = configurationService.getDataHolder().getMobileConnectConfig().getDataSourceName();
        mConnectDatasource = (DataSource) ctx.lookup(dataSourceName);
    } catch (NamingException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml:" + e);
    }
}

From source file:com.silverpeas.jcrutil.BetterRepositoryFactoryBean.java

protected static void prepareContext(InitialContext ic, String jndiName) throws NamingException {
    Context currentContext = ic;
    StringTokenizer tokenizer = new StringTokenizer(jndiName, "/", false);
    while (tokenizer.hasMoreTokens()) {
        String name = tokenizer.nextToken();
        if (tokenizer.hasMoreTokens()) {
            try {
                currentContext = (Context) currentContext.lookup(name);
            } catch (javax.naming.NameNotFoundException nnfex) {
                currentContext = currentContext.createSubcontext(name);
            }/*  w  ww.j  a  va2s. co m*/
        }
    }
}

From source file:Util.java

/**
 * Create a link//from  w  ww  . j a  v  a  2 s  . com
 * 
 * @param ctx
 *          the context
 * @param fromName
 *          the from name
 * @param toName
 *          the to name
 * @throws NamingException
 *           for any error
 */
public static void createLinkRef(Context ctx, String fromName, String toName) throws NamingException {
    LinkRef link = new LinkRef(toName);
    Context fromCtx = ctx;
    Name name = ctx.getNameParser("").parse(fromName);
    String atom = name.get(name.size() - 1);
    for (int n = 0; n < name.size() - 1; n++) {
        String comp = name.get(n);
        try {
            fromCtx = (Context) fromCtx.lookup(comp);
        } catch (NameNotFoundException e) {
            fromCtx = fromCtx.createSubcontext(comp);
        }
    }

    System.out.println("atom: " + atom);
    System.out.println("link: " + link);

    fromCtx.rebind(atom, link);

    System.out.println("Bound link " + fromName + " to " + toName);
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName)
        throws HibernateException {
    //ClassLoader cl1;

    if (sessionFactory == null) {

        if (jndiName == null || jndiName.trim().length() == 0)
            jndiName = CommonConstant.DEFAULT_JNDI_URL;
        Context initCtx = null;
        try {//  www.  j  a v  a  2s  .  c  o  m
            initCtx = new InitialContext();
            sessionFactory = (SessionFactory) initCtx.lookup(jndiName);
            return;
        } catch (Exception e) {
            logger.log(Level.INFO, "Unable to get JNDI data source connection", e);
        } finally {
            if (initCtx != null)
                try {
                    initCtx.close();
                } catch (NamingException e) {
                    //ignore
                }
        }

        Thread thread = Thread.currentThread();
        try {
            //Class.forName("org.hibernate.Configuration");
            //Configuration ffff = new Configuration();
            //Class.forName("org.apache.commons.logging.LogFactory");

            oldloader = thread.getContextClassLoader();
            //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration");
            //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory");
            //refreshURLs();
            //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader());
            ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader);
            //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]));

            thread.setContextClassLoader(testLoader);
            //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration");
            //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader);
            //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader);
            //Configuration cfg=null;
            //cfg = new Configuration();
            //Object oo = cls.newInstance();
            //Configuration cfg = (Configuration)oo;
            Configuration cfg = new Configuration();
            buildConfig(hibfile, mapdir, cfg);

            Class<? extends Driver> driverClass = testLoader
                    .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class);
            Driver driver = driverClass.newInstance();
            WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class"));

            boolean foundDriver = false;
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while (drivers.hasMoreElements()) {
                Driver nextDriver = (Driver) drivers.nextElement();
                if (nextDriver.getClass() == wd.getClass()) {
                    if (nextDriver.toString().equals(wd.toString())) {
                        foundDriver = true;
                        break;
                    }
                }
            }
            if (!foundDriver) {

                DriverManager.registerDriver(wd);
            }

            sessionFactory = cfg.buildSessionFactory();
            //configuration = cfg;
            HibernateMapDirectory = mapdir;
            HibernateConfigFile = hibfile;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e);
        } finally {
            thread.setContextClassLoader(oldloader);
        }
    }
}

From source file:com.cws.esolutions.security.utils.DAOInitializer.java

/**
 * @param properties - The <code>AuthRepo</code> object containing connection information
 * @param isContainer - A <code>boolean</code> flag indicating if this is in a container
 * @param bean - The {@link com.cws.esolutions.security.SecurityServiceBean} <code>SecurityServiceBean</code> that holds the connection
 * @throws SecurityServiceException {@link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs opening the connection
 */// w w  w. j a  v  a  2  s. c o m
public synchronized static void configureAndCreateAuthConnection(final InputStream properties,
        final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException {
    String methodName = DAOInitializer.CNAME
            + "#configureAndCreateAuthConnection(final String properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("InputStream: {}", properties);
        DEBUGGER.debug("isContainer: {}", isContainer);
        DEBUGGER.debug("SecurityServiceBean: {}", bean);
    }

    try {
        Properties connProps = new Properties();
        connProps.load(properties);

        if (DEBUG) {
            DEBUGGER.debug("Properties: {}", connProps);
        }

        AuthRepositoryType repoType = AuthRepositoryType
                .valueOf(connProps.getProperty(DAOInitializer.REPO_TYPE));
        RepositoryConnectionType connType = RepositoryConnectionType
                .valueOf(connProps.getProperty(DAOInitializer.CONN_TYPE));

        if (DEBUG) {
            DEBUGGER.debug("AuthRepositoryType: {}", repoType);
            DEBUGGER.debug("RepositoryConnectionType: {}", connType);
        }

        switch (repoType) {
        case LDAP:
            SSLUtil sslUtil = null;
            LDAPConnection ldapConn = null;
            LDAPConnectionPool connPool = null;
            LDAPConnectionOptions connOpts = new LDAPConnectionOptions();

            connOpts.setAutoReconnect(true);
            connOpts.setAbandonOnTimeout(true);
            connOpts.setBindWithDNRequiresPassword(true);
            connOpts.setConnectTimeoutMillis(
                    Integer.parseInt(connProps.getProperty(DAOInitializer.CONN_TIMEOUT)));
            connOpts.setResponseTimeoutMillis(
                    Integer.parseInt(connProps.getProperty(DAOInitializer.READ_TIMEOUT)));

            if (DEBUG) {
                DEBUGGER.debug("LDAPConnectionOptions: {}", connOpts);
            }

            switch (connType) {
            case CONNECTION_TYPE_INSECURE:
                ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));

                break;
            case CONNECTION_TYPE_SSL:
                sslUtil = new SSLUtil(new TrustStoreTrustManager(
                        connProps.getProperty(DAOInitializer.TRUST_FILE),
                        PasswordUtils
                                .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                        connProps.getProperty(DAOInitializer.TRUST_SALT),
                                        secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                        secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                        secConfig.getEncryptionInstance(), systemConfig.getEncoding())
                                .toCharArray(),
                        connProps.getProperty(DAOInitializer.TRUST_TYPE), true));

                if (DEBUG) {
                    DEBUGGER.debug("SSLUtil: {}", sslUtil);
                }

                SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory();

                if (DEBUG) {
                    DEBUGGER.debug("SSLSocketFactory: {}", sslSocketFactory);
                }

                ldapConn = new LDAPConnection(sslSocketFactory, connOpts,
                        connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));

                break;
            case CONNECTION_TYPE_TLS:
                ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                sslUtil = new SSLUtil(new TrustStoreTrustManager(
                        connProps.getProperty(DAOInitializer.TRUST_FILE),
                        PasswordUtils
                                .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                        connProps.getProperty(DAOInitializer.TRUST_SALT),
                                        secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                        secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                        secConfig.getEncryptionInstance(), systemConfig.getEncoding())
                                .toCharArray(),
                        connProps.getProperty(DAOInitializer.TRUST_TYPE), true));

                if (DEBUG) {
                    DEBUGGER.debug("SSLUtil: {}", sslUtil);
                }

                SSLContext sslContext = sslUtil.createSSLContext();

                if (DEBUG) {
                    DEBUGGER.debug("SSLContext: {}", sslContext);
                }

                StartTLSExtendedRequest startTLS = new StartTLSExtendedRequest(sslContext);

                if (DEBUG) {
                    DEBUGGER.debug("StartTLSExtendedRequest: {}", startTLS);
                }

                ExtendedResult extendedResult = ldapConn.processExtendedOperation(startTLS);

                if (DEBUG) {
                    DEBUGGER.debug("ExtendedResult: {}", extendedResult);
                }

                BindRequest bindRequest = new SimpleBindRequest(
                        connProps.getProperty(DAOInitializer.REPOSITORY_USER),
                        PasswordUtils.decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                connProps.getProperty(DAOInitializer.TRUST_SALT),
                                secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                secConfig.getEncryptionInstance(), systemConfig.getEncoding()));

                if (DEBUG) {
                    DEBUGGER.debug("BindRequest: {}", bindRequest);
                }

                BindResult bindResult = ldapConn.bind(bindRequest);

                if (DEBUG) {
                    DEBUGGER.debug("BindResult: {}", bindResult);
                }

                StartTLSPostConnectProcessor tlsProcessor = new StartTLSPostConnectProcessor(sslContext);

                if (DEBUG) {
                    DEBUGGER.debug("StartTLSPostConnectProcessor: {}", tlsProcessor);
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)), tlsProcessor);

                break;
            }

            if (DEBUG) {
                DEBUGGER.debug("LDAPConnectionPool: {}", connPool);
            }

            if ((connPool == null) || (connPool.isClosed())) {
                throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
            }

            bean.setAuthDataSource(connPool);
            break;
        case SQL:
            // the isContainer only matters here
            if (isContainer) {
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(DAOInitializer.DS_CONTEXT);

                bean.setAuthDataSource(envContext.lookup(DAOInitializer.REPOSITORY_HOST));
            } else {
                BasicDataSource dataSource = new BasicDataSource();
                dataSource.setInitialSize(
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)));
                dataSource
                        .setMaxActive(Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));
                dataSource.setDriverClassName(connProps.getProperty(DAOInitializer.CONN_DRIVER));
                dataSource.setUrl(connProps.getProperty(DAOInitializer.REPOSITORY_HOST));
                dataSource.setUsername(connProps.getProperty(DAOInitializer.REPOSITORY_USER));
                dataSource.setPassword(PasswordUtils.decryptText(
                        connProps.getProperty(DAOInitializer.REPOSITORY_PASS),
                        connProps.getProperty(DAOInitializer.REPOSITORY_SALT), secConfig.getSecretAlgorithm(),
                        secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                        secConfig.getEncryptionInstance(), systemConfig.getEncoding()));

                bean.setAuthDataSource(dataSource);
            }

            break;
        case NONE:
            return;
        default:
            throw new SecurityServiceException("Unhandled ResourceType");
        }
    } catch (LDAPException lx) {
        throw new SecurityServiceException(lx.getMessage(), lx);
    } catch (GeneralSecurityException gsx) {
        throw new SecurityServiceException(gsx.getMessage(), gsx);
    } catch (NamingException nx) {
        throw new SecurityServiceException(nx.getMessage(), nx);
    } catch (FileNotFoundException fnfx) {
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new SecurityServiceException(iox.getMessage(), iox);
    }
}

From source file:com.clican.pluto.common.util.JndiUtils.java

/**
 * Look up the object with the specified JNDI name in the JNDI server.
 * /*from w w  w.  j  a v  a2 s .  c o  m*/
 * @param jndiName
 *            the JNDI name specified
 * @return the object bound with the name specified, null if this method
 *         fails
 */
public static Object lookupObject(String jndiName) {
    Context ctx = null;
    try {
        Hashtable<String, String> ht = new Hashtable<String, String>();
        // If a special JNDI initial context factory was specified in the
        // constructor, then use it.
        if (jndiInitialContextFactory != null) {
            ht.put(Context.INITIAL_CONTEXT_FACTORY, jndiInitialContextFactory);
        }
        ctx = new InitialContext(ht);
        Object obj = null;
        try {
            obj = ctx.lookup(jndiName);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info(
                        "Lookup for an object from Non-Serializable JNDI (relookup from Serializable JNDI) using the JNDI name ["
                                + jndiName + "] : ");
            }
            obj = NonSerializableFactory.lookup(jndiName);
        }

        if (log.isDebugEnabled()) {
            log.debug("JNDI lookup with path [" + jndiName + "] returned object [" + obj + "].");
        }
        return obj;
    } catch (NamingException ex) {
        log.debug("Failed to lookup for an object using the JNDI name [" + jndiName + "] : " + ex);
        return null;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                log.error("Close context error:", ne);
            }
        }
    }
}