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:org.latticesoft.util.resource.DatabaseUtil.java

/**
 * Gets a database connection from JNDI Datasource.
 * @param jndi the name which the datasource is bounded to.
 * @param env the environment for initializing the initial context
 * @return the connection if successful. If not null will be returned. 
 **/// w ww  . jav a2 s .c o m
public static Connection getConnectionFromJNDI(String jndiName, Map env) throws NamingException, SQLException {
    Properties p = null;
    InitialContext ctx = null;
    if (env != null) {
        if (env instanceof Properties) {
            p = (Properties) env;
        } else {
            p = new Properties();
            p.putAll(env);
        }
        ctx = new InitialContext(p);
    } else {
        ctx = new InitialContext();
    }
    Object o = ctx.lookup(jndiName);
    javax.sql.DataSource ds = (javax.sql.DataSource) PortableRemoteObject.narrow(o, DataSource.class);
    Connection conn = ds.getConnection();
    return conn;
}

From source file:ece356.UserDBAO.java

public static Connection getConnection() throws ClassNotFoundException, SQLException, NamingException {
    InitialContext cxt = new InitialContext();
    if (cxt == null) {
        throw new RuntimeException("Unable to create naming context!");
    }//from  w ww .java  2  s  . c om
    Context dbContext = (Context) cxt.lookup("java:comp/env");
    DataSource ds = (DataSource) dbContext.lookup("jdbc/myDatasource");
    if (ds == null) {
        throw new RuntimeException("Data source not found!");
    }
    Connection con = ds.getConnection();

    /*Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, user, pwd);*/
    Statement stmt = null;
    try {
        con.createStatement();
        stmt = con.createStatement();
        stmt.execute("USE ece356db_" + nid);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
    return con;
}

From source file:wqm.web.bean.ConfigBean.java

public ConfigBean() throws NamingException {
    InitialContext ic = new InitialContext();
    config = (WQMConfig) ic.lookup(WQMConfig.class.getCanonicalName());

}

From source file:org.efaps.bpm.BPM.java

/**
 * Initialize BPM./*from  ww  w  .j a va2 s.c  o  m*/
 *
 * @throws EFapsException on error
 */
public static void initialize() throws EFapsException {
    final SystemConfiguration config = EFapsSystemConfiguration.get();
    final boolean active = config != null ? config.getAttributeValueAsBoolean(KernelSettings.ACTIVATE_BPM)
            : false;
    if (active) {

        if (BPM.PMANAGER != null) {
            BPM.PMANAGER.close();
            BPM.PMANAGER = null;
        }
        if (BPM.SMANAGER != null) {
            BPM.SMANAGER.close();
            BPM.SMANAGER = null;
        }

        UserTransaction userTrans = null;
        InitialContext context = null;
        try {
            context = new InitialContext();
            userTrans = TransactionHelper.findUserTransaction();
            Object object = null;
            try {
                object = context.lookup(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME);
            } catch (final NamingException ex) {
                BPM.LOG.info("Checked for JtaTransactionManager");
            }
            if (object == null) {
                context.bind(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, userTrans);
                context.bind(JtaTransactionManager.FALLBACK_TRANSACTION_MANAGER_NAMES[0],
                        TransactionHelper.findTransactionManager());
            }
        } catch (final NamingException ex) {
            BPM.LOG.error("Could not initialise JNDI InitialContext", ex);
        }

        // register our own KnowledgeBuilderFactoryService
        ServiceRegistryImpl.getInstance().addDefault(KnowledgeBuilderFactoryService.class,
                KnowledgeBuilderFactoryServiceImpl.class.getName());

        final RegisterableItemsFactoryImpl itemsFactory = new RegisterableItemsFactoryImpl();
        itemsFactory.addWorkItemHandler("Manual Task", ManualTaskItemHandler.class);
        itemsFactory.addProcessListener(WorkingMemoryLogListener.class);

        final Map<String, String> properties = new HashMap<String, String>();
        properties.put(AvailableSettings.DIALECT, Context.getDbType().getHibernateDialect());
        properties.put(AvailableSettings.SHOW_SQL, String.valueOf(BPM.LOG.isDebugEnabled()));
        properties.put(AvailableSettings.FORMAT_SQL, "true");
        properties.put(AvailableSettings.RELEASE_CONNECTIONS, "after_transaction");
        properties.put(AvailableSettings.CONNECTION_PROVIDER, ConnectionProvider.class.getName());
        properties.put(org.hibernate.jpa.AvailableSettings.NAMING_STRATEGY, NamingStrategy.class.getName());

        final EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa",
                properties);

        final RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.getDefault()
                .classLoader(EFapsClassLoader.getInstance()).userGroupCallback(new UserGroupCallbackImpl())
                .entityManagerFactory(emf).registerableItemsFactory(itemsFactory).persistence(true)
                .addEnvironmentEntry("TRANSACTION_LOCK_ENABLED", "false");

        BPM.add2EnvironmentBuilder(builder);

        final RuntimeEnvironment environment = builder.get();
        final ManagerFactoryImpl factory = new ManagerFactoryImpl();

        BPM.PMANAGER = factory.newPerProcessInstanceRuntimeManager(environment);
        BPM.SMANAGER = factory.newSingletonRuntimeManager(environment);
    }
}

From source file:org.akhikhl.examples.gretty.hellogretty.MainConfig.java

@Bean
public DataSource dataSource() {
    /* final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
    dsLookup.setResourceRef(true);//from ww  w  .  j  a  va 2s .co m
    return dsLookup.getDataSource("jdbc/devcore"); */

    DataSource dataSource = null;
    try {
        InitialContext init = new InitialContext();
        Context env = (Context) init.lookup("java:comp/env");
        dataSource = (DataSource) env.lookup("jdbc/devcore");
        Connection con = dataSource.getConnection();
    } catch (Exception e) {
        logger.error("Exception in dataSource", e);
        throw new RuntimeException(e);
    }
    return dataSource;
}

From source file:com.sf.ddao.conn.JNDIDataSourceHandler.java

public void init(AnnotatedElement element, Annotation annotation) {
    JNDIDao daoAnnotation = (JNDIDao) annotation;
    String dsName = daoAnnotation.value();
    try {//  ww  w  .ja  v  a2  s. c  o  m
        InitialContext ic = new InitialContext(new Hashtable());
        dataSource = (DataSource) ic.lookup(DS_CTX_PREFIX + dsName);
    } catch (Exception e) {
        throw new InitializerException("Failed to find DataSource " + dsName, e);
    }
}

From source file:dk.itst.oiosaml.sp.service.session.jdbc.JndiFactory.java

public SessionHandler getHandler() {
    try {//w w  w.  j  a  va  2  s. c  o m
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup(name);

        return new JdbcSessionHandler(ds);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.t2tierp.controller.T2TiSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    try {//from   ww w  . j av a 2 s.c  om
        InitialContext initialContext = new InitialContext();
        dao = (UsuarioDAO) initialContext.lookup("java:comp/ejb/usuarioDAO");
        Usuario usuario = dao.getUsuario(authentication.getName());
        request.getSession().setAttribute("usuarioT2TiERP", usuario);
    } catch (Exception e) {
        //e.printStackTrace();
    }
    super.onAuthenticationSuccess(request, response, authentication);
}

From source file:com.manydesigns.portofino.model.database.JndiConnectionProvider.java

public DataSource getDataSource() throws Exception {
    InitialContext ic = new InitialContext();
    return (DataSource) ic.lookup(jndiResource);
}

From source file:br.com.icone.martan.security.AppUserDetailsService.java

public AppUserDetailsService() {
    try {/*from   w ww. j ava  2 s  . co  m*/
        InitialContext ctx = new InitialContext();
        repositorio = (UserEJBRemote) ctx.lookup("br.com.icone.martan.modelo.repositorio.UserEJBRemote");
    } catch (NamingException ex) {
        Logger.getLogger(UserEJBRemote.class.getName()).log(Level.SEVERE, null, ex);
    }

}