Java 类javax.naming.InitialContext 实例源码

项目:BibliotecaPS    文件:DataSourceTest.java   
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
项目:tomcat7    文件:TestNamingContext.java   
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj = ctx.lookup("java:comp/env/bug50351");
        TesterObject to = (TesterObject) obj;
        out.print(to.getFoo());
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
项目:nifi-jms-jndi    文件:JNDIConnectionFactoryProvider.java   
/**
 * Creates an instance of the {@link ConnectionFactory} from the provided 'CONNECTION_FACTORY_IMPL'.
 */
private void createConnectionFactoryInstance(ConfigurationContext context) {
    String connectionFactoryImplName = getContextValue(context, CONNECTION_FACTORY_IMPL);
    Properties env = new Properties();

    try {
        env.put(InitialContext.INITIAL_CONTEXT_FACTORY, connectionFactoryImplName);
        env.put(InitialContext.PROVIDER_URL, getContextValue(context, BROKER_URI));

        InitialContext initialContext = new InitialContext(env);
        this.connectionFactory = (ConnectionFactory) initialContext.lookup(context.getProperty(JNDI_CF_LOOKUP).evaluateAttributeExpressions().getValue());
        if (logger.isDebugEnabled())
            logger.debug("Connection factory is created");
    } catch (Exception e) {
        throw new IllegalStateException("Failed to load and/or instantiate class 'com.solacesystems.jndi.SolJNDIInitialContextFactory'", e);
    }
}
项目:oscm    文件:HibernateEventListener.java   
private void handleIndexing(Object entity,
        ModificationType modType) {
    if (entity instanceof DomainObject<?>) {
        if (hibernateIndexer == null) {
            try {
                Properties p = new Properties();
                p.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.apache.openejb.client.LocalInitialContextFactory");
                Context context = new InitialContext(p);
                hibernateIndexer = (HibernateIndexer) context
                        .lookup(HibernateIndexer.class.getName());
            } catch (NamingException e) {
                throw new SaaSSystemException("Service lookup failed!", e);
            }
        }
        hibernateIndexer.handleIndexing((DomainObject<?>) entity, modType);
    }
}
项目:lemon    文件:SMTPAppenderBase.java   
private Session lookupSessionInJNDI() {
    addInfo("Looking up javax.mail.Session at JNDI location ["
            + jndiLocation + "]");

    try {
        Context initialContext = new InitialContext();
        Object obj = initialContext.lookup(jndiLocation);

        return (Session) obj;
    } catch (Exception e) {
        addError("Failed to obtain javax.mail.Session from JNDI location ["
                + jndiLocation + "]");

        return null;
    }
}
项目:cloud-ariba-partner-flow-extension-ext    文件:EcmServiceProvider.java   
private static EcmService initEcmService() {
    LOGGER.debug(DEBUG_INITIALIZING_ECM_SERVICE);

    EcmService ecmService;
    try {
        InitialContext initialContext = new InitialContext();
        ecmService = (EcmService) initialContext.lookup(ECM_SERVICE_NAME);
    } catch (NamingException e) {
        String errorMessage = MessageFormat.format(ERROR_LOOKING_UP_THE_ECM_SERVICE_FAILED, ECM_SERVICE_NAME);
        LOGGER.error(errorMessage, e);
        throw new RuntimeException(errorMessage, e);
    }

    LOGGER.debug(DEBUG_ECM_SERVICE_INITIALIZED);
    return ecmService;
}
项目:dbg-amqp-dispatch-workshop    文件:DateRequest.java   
public DateRequest() throws NamingException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss Z");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");

    try {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        properties.setProperty("connectionfactory.connection", String.format(
                "amqp://%s:%d?amqp.idleTimeout=30000",
                "localhost",
                5672));
        properties.setProperty("queue.time", "/time");
        properties.setProperty("queue.date", "/date");
        properties.setProperty("queue.response", UUID.randomUUID().toString());
        this.context = new InitialContext(properties);
    } catch (NamingException ex) {
        LOGGER.error("Unable to proceed with broadcast receiver", ex);
        throw ex;
    }
}
项目:dbg-amqp-dispatch-workshop    文件:TimeRequest.java   
public TimeRequest() throws NamingException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss Z");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");

    try {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        properties.setProperty("connectionfactory.connection", String.format(
                "amqp://%s:%d?amqp.idleTimeout=30000",
                "localhost",
                5672));
        properties.setProperty("queue.time", "/time");
        properties.setProperty("queue.date", "/date");
        properties.setProperty("queue.response", UUID.randomUUID().toString());
        this.context = new InitialContext(properties);
    } catch (NamingException ex) {
        LOGGER.error("Unable to proceed with broadcast receiver", ex);
        throw ex;
    }
}
项目:dbg-amqp-dispatch-workshop    文件:Service.java   
public Service() throws NamingException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss Z");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");

    try {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        properties.setProperty("connectionfactory.connection", String.format(
                "amqp://%s:%d?amqp.idleTimeout=30000&jms.forceAsyncSend=true",
                "localhost",
                5672));
        properties.setProperty("queue.time", "/time");
        properties.setProperty("queue.date", "/date");
        this.context = new InitialContext(properties);
    } catch (NamingException ex) {
        LOGGER.error("Unable to proceed with broadcast receiver", ex);
        throw ex;
    }
}
项目:flume-release-1.7.0    文件:TestJMSSource.java   
@SuppressWarnings("unchecked")
@Test
public void testStartConsumerCreateThrowsException() throws Exception {
  when(consumerFactory.create(any(InitialContext.class), any(ConnectionFactory.class),
                              anyString(), any(JMSDestinationType.class),
                              any(JMSDestinationLocator.class), anyString(), anyInt(), anyLong(),
                              any(JMSMessageConverter.class), any(Optional.class),
                              any(Optional.class))).thenThrow(new RuntimeException());
  source.configure(context);
  source.start();
  try {
    source.process();
    Assert.fail();
  } catch (FlumeException expected) {

  }
}
项目:jboss-eap7.1-playground    文件:MultipleServerWildFlyConfigURIClient.java   
public static void main(String[] args) throws NamingException {
    checkArgs(args);

    // Set I_C_F with properties and use wildfly-config.xml to set the server URI and credentials
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
    InitialContext ic = new InitialContext(p);

    Simple proxy = (Simple) ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());
    log.fine("Proxy is : " + proxy);

    HashSet<String> serverList = new HashSet<>();

    for (int i = 0; i < 20; i++) {
        serverList.add(proxy.getJBossServerName());
    }

    if(serverList.size() > 1) {
        log.info("Server should be part of a cluster or multiple URL's as the invocation was executed on the following servers : " + serverList);
    }else if(serverList.size() == 1) {
        log.warning("Server is not part of a cluster with multiple nodes, or did not have multiple PROVIDER URL's, as the invocation was executed on a single server : " + new ArrayList<String>(serverList).get(0));
    }else{
        throw new RuntimeException("Unexpected result, no server list!");
    }
}
项目:cli-java    文件:AocConnectionManager.java   
/**
 * Creates an object using qpid/amq initial context factory.
 *
 * @param className can be any of the qpid/amq supported JNDI properties:
 *                  connectionFactory, queue, topic, destination.
 * @param address   of the connection or node to create.
 */
protected Object createJMSProviderObject(String className, String address) {
    /* Name of the object is the same as class of the object */
    String name = className;
    properties.setProperty(className + "." + name, address);

    Object jmsProviderObject = null;
    try {
        Context context = new InitialContext(properties);
        jmsProviderObject = context.lookup(name);
        context.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return jmsProviderObject;
}
项目:jboss-eap7.1-playground    文件:DelegateBean.java   
@RolesAllowed({"Application"})
@Override
public void checkApplicationUser4DedicatedConnection(String localUserName, String remoteUserName) throws NamingException {
    Principal caller = context.getCallerPrincipal();

    if(!localUserName.equals(caller.getName())) {
        log.severe("Given user name '" + localUserName + "' not equal to real use name '" + caller.getName() + "'");
    }else{
        log.info("Expected user '" + localUserName + "'. Try to invoke remote SimpleBean with user '" + remoteUserName + "'");
        Properties p = new Properties();
        p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
        p.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");

        p.put(Context.SECURITY_PRINCIPAL, remoteUserName);
        p.put(Context.SECURITY_CREDENTIALS, remoteUserName);

        InitialContext ic = new InitialContext(p);
        Simple localProxy = (Simple)ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());
        if (!localProxy.checkApplicationUser(remoteUserName)) {
            log.severe("Remote bean was not invoked with the correct user!");
            throw new RuntimeException("Remote bean was not invoked with the correct user!");
        }

    }
    return;
}
项目:oscm    文件:APPTemplateServiceFactory.java   
public static APPTemplateService getInstance() {
    try {
        Properties p = new Properties();
        p.setProperty (Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

        InitialContext context = new InitialContext(p);
        Object lookup = context.lookup(JNDI_NAME);
        if (!APPTemplateService.class.isAssignableFrom(lookup.getClass())) {
            throw new IllegalStateException(
                "Failed to look up APPlatformService. The returned service is not implementing correct interface");
        }
        return (APPTemplateService) lookup;
    } catch (NamingException e) {
        logger.error("Service lookup failed: " + JNDI_NAME);
        throw new IllegalStateException(
            "No valid platform service available", e);
    }
}
项目:tomcat7    文件:TestTomcat.java   
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException {

    String name = null;

    try {
        javax.naming.Context initCtx = new InitialContext();
        javax.naming.Context envCtx =
                (javax.naming.Context) initCtx.lookup("java:comp/env");
        name = (String) envCtx.lookup(JNDI_ENV_NAME);
    } catch (NamingException e) {
        throw new IOException(e);
    }

    res.getWriter().write("Hello, " + name);
}
项目:tomcat7    文件:TestNamingContext.java   
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj1 = ctx.lookup("java:comp/env/list/foo");
        Object obj2 = ctx.lookup("java:comp/env/list/foo");
        if (obj1 == obj2) {
            out.print("EQUAL");
        } else {
            out.print("NOTEQUAL");
        }
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
项目:jboss-eap7.1-playground    文件:DelegateClient.java   
public static void main(String[] args) throws NamingException {
    checkArgs(args);

    Properties p = new Properties();

    p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
    p.put(Context.PROVIDER_URL, "http-remoting://localhost:9080");

    p.put(Context.SECURITY_PRINCIPAL, "delegateUser");
    p.put(Context.SECURITY_CREDENTIALS, "delegateUser");
    InitialContext ic = new InitialContext(p);

    Delegate proxy = (Delegate) ic.lookup("ejb:EAP71-PLAYGROUND-MainServer-icApp/ejb/DelegateBean!" + Delegate.class.getName());
    proxy.checkApplicationUser4DedicatedConnection("delegateUser", "delegateUserR");

    ic.close();
}
项目:the-vigilantes    文件:DataSourceTest.java   
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
项目:keycloak-health-checks    文件:DatabaseHealthIndicator.java   
@Override
public HealthStatus check() {

  try {
    InitialContext ic = new InitialContext();
    DataSource dataSource = (DataSource) ic.lookup(jndiName);

    try (Connection connection = dataSource.getConnection()) {

      try (Statement statement = connection.createStatement()) {
        if (statement.execute(healthQuery)) {
          return reportUp();
        }
      }
    }
  } catch (Exception ex) {
    return reportDown().withAttribute("message", ex.getMessage());
  }

  return reportDown();
}
项目:asura    文件:JNDIConnectionProvider.java   
private void init() {

        if (!isAlwaysLookup()) {
            Context ctx = null;
            try {
                ctx = (props != null) ? new InitialContext(props) : new InitialContext(); 

                datasource = (DataSource) ctx.lookup(url);
            } catch (Exception e) {
                getLog().error(
                        "Error looking up datasource: " + e.getMessage(), e);
            } finally {
                if (ctx != null) {
                    try { ctx.close(); } catch(Exception ignore) {}
                }
            }
        }
    }
项目:lams    文件:JNDIConnectionProvider.java   
private void init() {

        if (!isAlwaysLookup()) {
            Context ctx = null;
            try {
                ctx = (props != null) ? new InitialContext(props) : new InitialContext(); 

                datasource = (DataSource) ctx.lookup(url);
            } catch (Exception e) {
                getLog().error(
                        "Error looking up datasource: " + e.getMessage(), e);
            } finally {
                if (ctx != null) {
                    try { ctx.close(); } catch(Exception ignore) {}
                }
            }
        }
    }
项目:lucene-demo    文件:JdbcUtil.java   
/**
 * 获取连接,使用数据库连接池
 * @param jndi 配置在tomcat的context.xml里面的东西
 * @return 创建的连接对象
 */
public Connection getConnection(String jndi)
{
    try
    {
        log.debug("开始尝试连接数据库!");
        Context context=new InitialContext();
        DataSource dataSource=(DataSource)context.lookup("java:comp/env/"+jndi);
        con=dataSource.getConnection();
        log.debug("连接成功!");
    }
    catch (Exception e)
    {
        log.error("连接数据库失败!", e);
    }
    return con;
}
项目:oscm    文件:APPlatformServiceFactory.java   
/**
 * Retrieves an <code>APPlatformService</code> instance.
 * 
 * @return the service instance
 */
public static APPlatformService getInstance() {
    try {

        Properties p = new Properties();
        p.setProperty (Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

        InitialContext context = new InitialContext(p);
        Object lookup = context.lookup(JNDI_NAME);
        if (!APPlatformService.class.isAssignableFrom(lookup.getClass())) {
            throw new IllegalStateException(
                    "Failed to look up APPlatformService. The returned service is not implementing correct interface");
        }
        return (APPlatformService) lookup;
    } catch (NamingException e) {
        logger.error("Service lookup failed: " + JNDI_NAME);
        throw new IllegalStateException(
                "No valid platform service available", e);
    }
}
项目:lams    文件:OpenEjbFactory.java   
/**
 * Crete a new EJB instance using OpenEJB.
 * 
 * @param obj The reference object describing the DataSource
 */
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
                                Hashtable environment)
    throws Exception {

    Object beanObj = null;

    if (obj instanceof EjbRef) {

        Reference ref = (Reference) obj;

        String factory = DEFAULT_OPENEJB_FACTORY;
        RefAddr factoryRefAddr = ref.get("openejb.factory");
        if (factoryRefAddr != null) {
            // Retrieving the OpenEJB factory
            factory = factoryRefAddr.getContent().toString();
        }

        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);

        RefAddr linkRefAddr = ref.get("openejb.link");
        if (linkRefAddr != null) {
            String ejbLink = linkRefAddr.getContent().toString();
            beanObj = (new InitialContext(env)).lookup(ejbLink);
        }

    }

    return beanObj;

}
项目:nifi-jms-jndi    文件:CommonTest.java   
static ConnectionFactory buildJmsJndiConnectionFactory() throws Exception {
    Properties env =new Properties();
    env.setProperty(Context.PROVIDER_URL, "vm://localhost?broker.persistent=false");
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.activemq.jndi.ActiveMQInitialContextFactory");

    InitialContext initialContext = new InitialContext(env);
    // Lookup ConnectionFactory.
    ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");  
    return connectionFactory;

}
项目:EJB-CON-DTO    文件:Utilidades.java   
public static Object getEJBRemote(String nameEJB, String iface) throws Exception {

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        props.put(Context.PROVIDER_URL, "http://localhost:7001");
        try {
            Context ctx = new InitialContext(props);
            String lookup = nameEJB + "#" + iface;
            System.out.println("Lookup: " + lookup);
            return ctx.lookup(lookup);
        } catch (Exception ex) {
            throw new Exception("No se encontro el EJB: '"+nameEJB+"'.");
        }

}
项目:rapidminer    文件:DatabaseHandler.java   
public static DatabaseHandler getConnectedDatabaseHandler(Operator operator) throws OperatorException, SQLException {
    Process process = operator.getProcess();
    switch(operator.getParameterAsInt("define_connection")) {
        case 0:
            String repositoryName = null;
            if(process != null) {
                RepositoryLocation entry = process.getRepositoryLocation();
                if(entry != null) {
                    repositoryName = entry.getRepositoryName();
                }
            }

            ConnectionEntry entry1 = DatabaseConnectionService.getConnectionEntry(operator.getParameterAsString("connection"), repositoryName, process != null?process.getRepositoryAccessor():null);
            if(entry1 == null) {
                throw new UserError(operator, 318, new Object[]{operator.getParameterAsString("connection")});
            }

            return getConnectedDatabaseHandler(entry1);
        case 1:
        default:
            return getConnectedDatabaseHandler(operator.getParameterAsString("database_url"), operator.getParameterAsString("username"), operator.getParameterAsString("password"));
        case 2:
            String jndiName = operator.getParameterAsString("jndi_name");

            try {
                InitialContext e = new InitialContext();
                DataSource source = (DataSource)e.lookup(jndiName);
                return getHandler(source.getConnection());
            } catch (NamingException var7) {
                throw new OperatorException("Failed to lookup \'" + jndiName + "\': " + var7, var7);
            }
    }
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:BeanCallingOtherBeans.java   
public Ejb21StateLocal getEjb21StateLocal() {
    try {
        InitialContext jndiContext = new InitialContext();
        Ejb21StateLocalHome sessionHome = (Ejb21StateLocalHome) jndiContext.lookup("java:comp/env/injected2");
        return sessionHome.create();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:RemotingNamingTestCase.java   
private void createInitialContext() throws NamingException {
    Properties prop = new Properties();

    prop.put(INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
    prop.put(PROVIDER_URL, "http-remoting://127.0.0.1:8080");
    prop.put(SECURITY_PRINCIPAL, "admin");
    prop.put(SECURITY_CREDENTIALS, "secret123!");
    prop.put("jboss.naming.client.ejb.context", true);

    context = new InitialContext(prop);
}
项目:openjdk-jdk10    文件:RMIConnectorServer.java   
/**
 * Bind a stub to a registry.
 * @param jndiUrl URL of the stub in the registry, extracted
 *        from the <code>JMXServiceURL</code>.
 * @param attributes A Hashtable containing environment parameters,
 *        built from the Map specified at this object creation.
 * @param rmiServer The object to bind in the registry
 * @param rebind true if the object must be rebound.
 **/
void bind(String jndiUrl, Hashtable<?, ?> attributes,
          RMIServer rmiServer, boolean rebind)
    throws NamingException, MalformedURLException {
    // if jndiURL is not null, we nust bind the stub to a
    // directory.
    InitialContext ctx =
        new InitialContext(attributes);

    if (rebind)
        ctx.rebind(jndiUrl, rmiServer);
    else
        ctx.bind(jndiUrl, rmiServer);
    ctx.close();
}
项目:ralasafe    文件:DataSourceProviderJndiImpl.java   
public void setup( Properties prop ) {
    this.prop=prop;
    String jndiName=prop.getProperty( "jndiName" );
    try {
        InitialContext ctx=new InitialContext();
        dataSource=(javax.sql.DataSource) ctx.lookup( jndiName );
    } catch( NamingException e ) {
        e.printStackTrace();
        throw new RuntimeException( e );
    }
}
项目:drinkwater-java    文件:JndiSqlDataStoreTest.java   
@Test
public void shouldApplyMigrations() throws Exception {

    //bind the datasources
    DataSource migrationdataSource = pg.getPostgresDatabase();
    DataSource userdataSource = pg.getPostgresDatabase();

    //bind to context
    Context ctx = new InitialContext();
    ctx.bind("java:test/datasources/migrationDS", migrationdataSource);
    ctx.bind("java:test/datasources/testDS", userdataSource);

    try (DrinkWaterApplication app = DrinkWaterApplication.create("jndi-datastore-test",
            options().use(JndiDataStoreConfiguration.class).autoStart())) {

        JndiSqlDataStore store = app.getStore("test");
        store.executeNoQuery("INSERT INTO contact(id, first_name, last_name) VALUES (2 , 'Jean-Marc', 'Canon');");

        try (Connection c = store.getConnection()) {
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("SELECT * from contact");
            assertTrue(rs.next());
            assertEquals(2, rs.getInt(1));
            assertFalse(rs.next());
        }
    }
}
项目:flume-release-1.7.0    文件:JMSMessageConsumerFactory.java   
JMSMessageConsumer create(InitialContext initialContext, ConnectionFactory connectionFactory,
    String destinationName, JMSDestinationType destinationType,
    JMSDestinationLocator destinationLocator, String messageSelector, int batchSize,
    long pollTimeout, JMSMessageConverter messageConverter,
    Optional<String> userName, Optional<String> password) {
  return new JMSMessageConsumer(initialContext, connectionFactory, destinationName,
      destinationLocator, destinationType, messageSelector, batchSize, pollTimeout,
      messageConverter, userName, password);
}
项目:lams    文件:JNDIConnectionProvider.java   
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;

        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props): new InitialContext(); 

            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }

        if (ds == null) {
            throw new SQLException( "There is no object at the JNDI URL '" + url + "'");
        }

        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) { 
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException(
                "Could not retrieve datasource via JNDI url '" + url + "' "
                        + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try { ctx.close(); } catch(Exception ignore) {}
        }
    }
}
项目:drinkwater-java    文件:MockInitialContextFactoryTest.java   
@Test
public void shouldThrowExceptionbecauseNotBound()  {

    assertThatThrownBy(() -> {
        Context ctx = new InitialContext();
        Object result = ctx.lookup("hello");
    }).isInstanceOf(NamingException.class).hasMessageContaining("hello");

}
项目:lams    文件:JndiServiceImpl.java   
private void cleanUp(InitialContext initialContext) {
    try {
        initialContext.close();
    }
    catch ( NamingException e ) {
        LOG.unableToCloseInitialContext(e.toString());
    }
}
项目:lams    文件:WorkManagerThreadExecutor.java   
public void initialize() {
    try {
        this.workManager = (WorkManager) new InitialContext().lookup(workManagerName);
    } catch (NamingException e) {
        throw new IllegalStateException("Could not locate WorkManager: " + e.getMessage(), e);
    }
}