Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Helper method to retrieve a EJB service instance. The name to be passed to the method is
 * normally 'ServiceXY.SERVICE_NAME'./*from   w  ww  . j  ava 2 s. co m*/
 * 
 * @param serviceName The name of the service, e.g.
 *        "ejb.de.mpg.mpdl.inge.xmltransforming.XmlTransforming"
 * 
 * @return instance of the EJB service
 * 
 * @throws NamingException Thrown if the service is not found.
 */
protected static Object getService(String serviceName) throws NamingException {
    InitialContext context = new InitialContext();
    Object serviceInstance = context.lookup(serviceName);
    assertNotNull(serviceInstance);
    return serviceInstance;
}

From source file:org.jboss.spring.support.SpringInjectionSupport.java

/**
 * @param jndiName      the JNDI location of the Spring context relative to
 *                      'java:' on JBoss AS5 and JBoss AS6 and 'java:jboss' on JBoss AS7
 * @param expectedClass the expected type of the retrieved object
 * @return//  ww  w .ja va  2  s .  co  m
 */
private <T> T lookup(String jndiName, Class<T> expectedClass) {
    Object instance;
    try {
        InitialContext initialContext = new InitialContext();
        instance = initialContext.lookup(jndiName);
        if (!(expectedClass.isAssignableFrom(instance.getClass()))) {
            throw new IllegalArgumentException("Cannot retrieve an " + expectedClass.getName() + " from "
                    + jndiName + " - a " + instance.getClass().getName() + " found instead");
        }
    } catch (NamingException e) {
        throw new IllegalStateException(e);
    }
    return expectedClass.cast(instance);
}

From source file:com.sun.socialsite.business.DatabaseProvider.java

/**
 * Reads configuraiton, loads driver or locates data-source and attempts
 * to get test connecton so that we can fail early.
 *///from   w  w  w  .  j a v a 2 s.  c  o  m
public DatabaseProvider() throws StartupException {

    String connectionTypeString = Config.getProperty("database.configurationType");
    if ("jdbc".equals(connectionTypeString)) {
        type = ConfigurationType.JDBC_PROPERTIES;
    }
    jndiName = Config.getProperty("database.jndi.name");
    jdbcDriverClass = Config.getProperty("database.jdbc.driverClass");
    jdbcConnectionURL = Config.getProperty("database.jdbc.connectionURL");
    jdbcUsername = Config.getProperty("database.jdbc.username");
    jdbcPassword = Config.getProperty("database.jdbc.password");

    successMessage("SUCCESS: Got parameters. Using configuration type " + type);

    // If we're doing JDBC then attempt to load JDBC driver class
    if (getType() == ConfigurationType.JDBC_PROPERTIES) {
        successMessage("-- Using JDBC driver class: " + jdbcDriverClass);
        successMessage("-- Using JDBC connection URL: " + jdbcConnectionURL);
        successMessage("-- Using JDBC username: " + jdbcUsername);
        successMessage("-- Using JDBC password: [hidden]");
        try {
            Class.forName(getJdbcDriverClass());
        } catch (ClassNotFoundException ex) {
            String errorMsg = "ERROR: cannot load JDBC driver class [" + getJdbcDriverClass() + "]. "
                    + "Likely problem: JDBC driver jar missing from server classpath.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: loaded JDBC driver class [" + getJdbcDriverClass() + "]");

        if (getJdbcUsername() != null || getJdbcPassword() != null) {
            props = new Properties();
            if (getJdbcUsername() != null)
                props.put("user", getJdbcUsername());
            if (getJdbcPassword() != null)
                props.put("password", getJdbcPassword());
        }

        // Else attempt to locate JNDI datasource
    } else {
        String name = "java:comp/env/" + getJndiName();
        successMessage("-- Using JNDI datasource name: " + name);
        try {
            InitialContext ic = new InitialContext();
            dataSource = (DataSource) ic.lookup(name);
        } catch (NamingException ex) {
            String errorMsg = "ERROR: cannot locate JNDI DataSource [" + name + "]. "
                    + "Likely problem: no DataSource or datasource is misconfigured.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: located JNDI DataSource [" + name + "]");
    }

    // So far so good. Now, can we get a connection?
    try {
        Connection testcon = getConnection();
        testcon.close();
    } catch (Throwable t) {
        String errorMsg = "ERROR: unable to obtain database connection. "
                + "Likely problem: bad connection parameters or database unavailable.";
        errorMessage(errorMsg);
        throw new StartupException(errorMsg, t, startupLog);
    }
}

From source file:org.apache.roller.planet.business.DatabaseProvider.java

/**
 * Reads configuraiton, loads driver or locates data-source and attempts
 * to get test connecton so that we can fail early.
 *//*from  www . j  a v a2  s  .  c  o m*/
public DatabaseProvider() throws StartupException {

    String connectionTypeString = PlanetConfig.getProperty("database.configurationType");
    if ("jdbc".equals(connectionTypeString)) {
        type = ConfigurationType.JDBC_PROPERTIES;
    }
    jndiName = PlanetConfig.getProperty("database.jndi.name");
    jdbcDriverClass = PlanetConfig.getProperty("database.jdbc.driverClass");
    jdbcConnectionURL = PlanetConfig.getProperty("database.jdbc.connectionURL");
    jdbcUsername = PlanetConfig.getProperty("database.jdbc.username");
    jdbcPassword = PlanetConfig.getProperty("database.jdbc.password");

    successMessage("SUCCESS: Got parameters. Using configuration type " + type);

    // If we're doing JDBC then attempt to load JDBC driver class
    if (getType() == ConfigurationType.JDBC_PROPERTIES) {
        successMessage("-- Using JDBC driver class: " + jdbcDriverClass);
        successMessage("-- Using JDBC connection URL: " + jdbcConnectionURL);
        successMessage("-- Using JDBC username: " + jdbcUsername);
        successMessage("-- Using JDBC password: [hidden]");
        try {
            Class.forName(getJdbcDriverClass());
        } catch (ClassNotFoundException ex) {
            String errorMsg = "ERROR: cannot load JDBC driver class [" + getJdbcDriverClass() + "]. "
                    + "Likely problem: JDBC driver jar missing from server classpath.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: loaded JDBC driver class [" + getJdbcDriverClass() + "]");

        if (getJdbcUsername() != null || getJdbcPassword() != null) {
            props = new Properties();
            if (getJdbcUsername() != null)
                props.put("user", getJdbcUsername());
            if (getJdbcPassword() != null)
                props.put("password", getJdbcPassword());
        }

        // Else attempt to locate JNDI datasource
    } else {
        String name = "java:comp/env/" + getJndiName();
        successMessage("-- Using JNDI datasource name: " + name);
        try {
            InitialContext ic = new InitialContext();
            dataSource = (DataSource) ic.lookup(name);
        } catch (NamingException ex) {
            String errorMsg = "ERROR: cannot locate JNDI DataSource [" + name + "]. "
                    + "Likely problem: no DataSource or datasource is misconfigured.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: located JNDI DataSource [" + name + "]");
    }

    // So far so good. Now, can we get a connection?
    try {
        Connection testcon = getConnection();
        testcon.close();
    } catch (Throwable t) {
        String errorMsg = "ERROR: unable to obtain database connection. "
                + "Likely problem: bad connection parameters or database unavailable.";
        errorMessage(errorMsg);
        throw new StartupException(errorMsg, t, startupLog);
    }
}

From source file:org.apache.roller.weblogger.business.DatabaseProvider.java

/**
 * Reads configuraiton, loads driver or locates data-source and attempts
 * to get test connecton so that we can fail early.
 *///  ww  w. j av  a  2 s  .c o m
public DatabaseProvider() throws StartupException {

    String connectionTypeString = WebloggerConfig.getProperty("database.configurationType");
    if ("jdbc".equals(connectionTypeString)) {
        type = ConfigurationType.JDBC_PROPERTIES;
    }
    jndiName = WebloggerConfig.getProperty("database.jndi.name");
    jdbcDriverClass = WebloggerConfig.getProperty("database.jdbc.driverClass");
    jdbcConnectionURL = WebloggerConfig.getProperty("database.jdbc.connectionURL");
    jdbcUsername = WebloggerConfig.getProperty("database.jdbc.username");
    jdbcPassword = WebloggerConfig.getProperty("database.jdbc.password");

    successMessage("SUCCESS: Got parameters. Using configuration type " + type);

    // If we're doing JDBC then attempt to load JDBC driver class
    if (getType() == ConfigurationType.JDBC_PROPERTIES) {
        successMessage("-- Using JDBC driver class: " + jdbcDriverClass);
        successMessage("-- Using JDBC connection URL: " + jdbcConnectionURL);
        successMessage("-- Using JDBC username: " + jdbcUsername);
        successMessage("-- Using JDBC password: [hidden]");
        try {
            Class.forName(getJdbcDriverClass());
        } catch (ClassNotFoundException ex) {
            String errorMsg = "ERROR: cannot load JDBC driver class [" + getJdbcDriverClass() + "]. "
                    + "Likely problem: JDBC driver jar missing from server classpath.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: loaded JDBC driver class [" + getJdbcDriverClass() + "]");

        if (getJdbcUsername() != null || getJdbcPassword() != null) {
            props = new Properties();
            if (getJdbcUsername() != null)
                props.put("user", getJdbcUsername());
            if (getJdbcPassword() != null)
                props.put("password", getJdbcPassword());
        }

        // Else attempt to locate JNDI datasource
    } else {
        String name = (getJndiName().indexOf(":") == -1 ? "java:comp/env/" + getJndiName() : getJndiName());
        successMessage("-- Using JNDI datasource name: " + name);
        try {
            InitialContext ic = new InitialContext();
            dataSource = (DataSource) ic.lookup(name);
        } catch (NamingException ex) {
            String errorMsg = "ERROR: cannot locate JNDI DataSource [" + name + "]. "
                    + "Likely problem: no DataSource or datasource is misconfigured.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: located JNDI DataSource [" + name + "]");
    }

    // So far so good. Now, can we get a connection?
    try {
        Connection testcon = getConnection();
        testcon.close();
    } catch (Throwable t) {
        String errorMsg = "ERROR: unable to obtain database connection. "
                + "Likely problem: bad connection parameters or database unavailable.";
        errorMessage(errorMsg);
        throw new StartupException(errorMsg, t, startupLog);
    }
}

From source file:com.ocpsoft.pretty.faces.el.resolver.CDIBeanNameResolver.java

/**
 * Tries to get the BeanManager from JNDI
 * //from   w w w  .  ja va 2  s  .  c  o  m
 * @param jndiName
 *           The JNDI name used for lookup
 * @return BeanManager instance or <code>null</code>
 */
private Object getBeanManagerFromJNDI(String jndiName) {

    try {
        // perform lookup
        InitialContext initialContext = new InitialContext();
        Object obj = initialContext.lookup(jndiName);

        if (log.isTraceEnabled()) {
            log.trace("Found BeanManager in: " + jndiName);
        }

        return obj;

    } catch (NamingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to get BeanManager from '" + jndiName + "': " + e.getMessage());
        }
    }

    return null;
}

From source file:org.overlord.sramp.governance.services.NotificationResource.java

/**
 * Constructor.//from  w w  w . j  a  v a  2s  . c om
 * @throws NamingException
 */
public NotificationResource() {
    InitialContext context;
    try {
        String jndiEmailRef = governance.getJNDIEmailName();
        context = new InitialContext();
        mailSession = (Session) context.lookup(jndiEmailRef);
        if (mailSession == null) {
            logger.error(Messages.i18n.format("NotificationResource.JndiLookupFailed", jndiEmailRef)); //$NON-NLS-1$
        }
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:org.wso2.carbon.custom.connector.EJBFactory.java

public Object getEJBObject(MessageContext ctx, String jndiName) {
    EJB2Init ejb2Init = new EJB2Init();
    InitialContext context;
    Object obj = null;/*from   w  ww . jav  a2  s . c o  m*/
    try {
        context = ejb2Init.getInitialContext();
        obj = context.lookup(getParameter(ctx, jndiName).toString());
    } catch (NoClassDefFoundError e) {
        handleException("Failed lookup because of ", ctx);
    } catch (NamingException e) {
        handleException("Failed lookup because of ", e, ctx);
    }
    EJBHome beanHome = (EJBHome) javax.rmi.PortableRemoteObject.narrow(obj, EJBHome.class);
    Method m = null;
    try {
        m = beanHome.getClass().getDeclaredMethod(EJBConstance.CREATE);
    } catch (NoSuchMethodException e) {
        handleException("There is no create method ", ctx);
    }
    Object ejbObj = null;
    try {
        if (m != null) {
            ejbObj = m.invoke(beanHome);
        } else {
            handleException("ejb home is missing", ctx);
        }
    } catch (IllegalAccessException e) {
        handleException("", e, ctx);
    } catch (InvocationTargetException e) {
        handleException("", e, ctx);
    }
    return ejbObj;
}

From source file:org.nimbustools.messaging.gt4_0.common.NimbusMasterContext.java

/**
 * @return TimerManager, never null//w w  w .j  av  a2s . co  m
 * @throws Exception could not locate
 */
public TimerManager discoverTimerManager() throws Exception {

    InitialContext ctx = null;
    try {
        ctx = new InitialContext();

        final TimerManager timerManager = (TimerManager) ctx.lookup(Constants.DEFAULT_TIMER);

        if (timerManager == null) {
            // should be NameNotFoundException if missing
            throw new Exception("null from JNDI for TimerManager (?)");
        }

        return timerManager;
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

public Session getSession() {
    if (session == null) {
        synchronized (this) {
            if (session == null) {
                if (sessionName != null) {
                    try {
                        InitialContext ic = new InitialContext();
                        session = (Session) ic.lookup(sessionName);
                    } catch (NamingException e) {
                        log.warn("Failed to lookup mail session using JNDI name " + sessionName
                                + ". Falling back on local configuration.");
                        session = Session.getInstance(config, auth);
                    }//  w w  w.  j a v  a2  s  .  c  o m
                } else {
                    session = Session.getInstance(config, auth);
                }
            }
        }
    }
    return session;
}