javax.naming.Context#bind ( )源码实例Demo

下面列出了javax.naming.Context#bind ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Knowage-Server   文件: UtilitiesForTest.java
/**
 * <pre>
 *  <Environment name="service_url" type="java.lang.String" value="http://localhost:8080/knowage"/>
 *     <Environment name="host_url" type="java.lang.String" value="http://localhost:8080"/>
 *     <Environment name="sso_class" type="java.lang.String" value="it.eng.spagobi.services.common.FakeSsoService"/>
 * </pre>
 *
 * @throws Exception
 */
public static void setUpTestJNDI() throws Exception {

	// Create initial context
	System.setProperty(Context.INITIAL_CONTEXT_FACTORY, MockFactory.class.getName());

	Context ic = new MockContext();
	MockFactory.context = ic;
	ic.bind("java:/comp/env/service_url", "http://localhost:8080/knowage");
	ic.bind("java:/comp/env/host_url", "http://localhost:8080");
	ic.bind("java:/comp/env/sso_class", "it.eng.spagobi.services.common.FakeSsoService");

	ic.bind("java://comp/env/service_url", "http://localhost:8080/knowage");
	ic.bind("java://comp/env/host_url", "http://localhost:8080");
	ic.bind("java://comp/env/sso_class", "it.eng.spagobi.services.common.FakeSsoService");
	ic.bind("java:/comp/env/jdbc/hdfs_url", "hdfs://192.168.56.1:8020");

	SimpleConfigurationRetriever configuration = new SimpleConfigurationRetriever();
	configuration.setProperty("SPAGOBI.ORGANIZATIONAL-UNIT.hdfsResource", "java:/comp/env/jdbc/hdfs_url");
	configuration.setProperty("SPAGOBI_SSO.INTEGRATION_CLASS_JNDI", "java:/comp/env/sso_class");
	SingletonConfig.getInstance().setConfigurationRetriever(configuration);
}
 
源代码2 项目: tomee   文件: DataSourceCipheredExampleTest.java
@Test
public void accessDatasourceWithMyImplementation() throws Exception {
    // define the datasource
    Properties properties = new Properties();
    properties.setProperty("ProtectedDatasource", "new://Resource?type=DataSource");
    properties.setProperty("ProtectedDatasource.JdbcDriver", "org.hsqldb.jdbcDriver");
    properties.setProperty("ProtectedDatasource.JdbcUrl", "jdbc:hsqldb:mem:protected");
    properties.setProperty("ProtectedDatasource.UserName", USER);
    properties.setProperty("ProtectedDatasource.Password", "3MdniFr3v3NLLuoY");
    properties.setProperty("ProtectedDatasource.PasswordCipher", "reverse");
    properties.setProperty("ProtectedDatasource.JtaManaged", "true");

    // start the context and makes junit test injections
    EJBContainer container = EJBContainer.createEJBContainer(properties);
    Context context = container.getContext();
    context.bind("inject", this);

    // test the datasource
    assertNotNull(dataSource);
    assertNotNull(dataSource.getConnection());

    // closing the context
    container.close();
}
 
源代码3 项目: activemq-artemis   文件: JNDIUtil.java
/**
 * Context.rebind() requires that all intermediate contexts and the target context (that named by
 * all but terminal atomic component of the name) must already exist, otherwise
 * NameNotFoundException is thrown. This method behaves similar to Context.rebind(), but creates
 * intermediate contexts, if necessary.
 */
public static void rebind(final Context c, final String jndiName, final Object o) throws NamingException {
   Context context = c;
   String name = jndiName;

   int idx = jndiName.lastIndexOf('/');
   if (idx != -1) {
      context = JNDIUtil.createContext(c, jndiName.substring(0, idx));
      name = jndiName.substring(idx + 1);
   }
   boolean failed = false;
   try {
      context.rebind(name, o);
   } catch (Exception ignored) {
      failed = true;
   }
   if (failed) {
      context.bind(name, o);
   }
}
 
源代码4 项目: XPagesExtensionLibrary   文件: JndiRegistry.java
public static synchronized void registerConnections(IJdbcResourceFactoryProvider provider) throws ResourceFactoriesException {
    // Look at the local providers
    String[] names = provider.getConnectionNames();
    if(names!=null) {
        for(int j=0; j<names.length; j++) {
            String name = names[j];
            Integer n = connections.get(name);
            if(n==null) {
                n = 1;
                //Register the dataSourceName in JNDI
                try {
                    Context ctx = new InitialContext();
                    String jndiName = JndiRegistry.getJNDIBindName(name);
                    ctx.bind( jndiName, new JndiDataSourceProxy(name) );
                } catch(NamingException ex) {
                    throw new ResourceFactoriesException(ex,StringUtil.format("Error while binding JNDI name {0}",name)); // $NLX-JndiRegistry.Errorwhilebinding0name1-1$ $NON-NLS-2$
                }
            } else {
                n = n+1;
            }
            connections.put(name,n);
        }
    }
}
 
源代码5 项目: ironjacamar   文件: Util.java
/**
 * Bind val to name in ctx, and make sure that all intermediate contexts exist
 * @param ctx the parent JNDI Context under which value will be bound
 * @param name the name relative to ctx where value will be bound
 * @param value the value to bind.
 * @throws NamingException for any error
 */
private static void bind(Context ctx, Name name, Object value) throws NamingException
{
   int size = name.size();
   String atom = name.get(size - 1);
   Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1));
   parentCtx.bind(atom, value);
}
 
源代码6 项目: piranha   文件: DefaultInitialContextTest.java
/**
 * Test listBindings method.
 *
 * @throws Exception when an error occurs.
 */
@Test
public void testListBindings6() throws Exception {
    DefaultInitialContext context = new DefaultInitialContext();
    Context subContext = context.createSubcontext("context1");
    subContext.bind("context2", "value");
    assertThrows(NamingException.class, () -> context.listBindings("context1/context2"));
}
 
/**
 * Start
 * @exception Throwable Thrown if an error occurs
 */
public void start() throws Throwable
{
   Context context = new InitialContext();

   context.bind(JNDI_NAME, this);

   context.close();
}
 
源代码8 项目: tomee   文件: MoviesTest.java
@Test
public void test() throws Exception {
    final Properties p = new Properties();
    p.put("movieDatabase", "new://Resource?type=DataSource");
    p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver");
    p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb");

    final EJBContainer container = EJBContainer.createEJBContainer(p);
    final Context context = container.getContext();
    context.bind("inject", this);

    assertTrue(((ReloadableEntityManagerFactory) emf).getManagedClasses().contains(Movie.class.getName()));

    container.close();
}
 
源代码9 项目: lams   文件: UserTransactionImpl.java
/**
 * Start
 * @exception Throwable Thrown if an error occurs
 */
public void start() throws Throwable
{
   Context context = new InitialContext();

   context.bind(JNDI_NAME, this);

   context.close();
}
 
源代码10 项目: lams   文件: Util.java
/**
 * Bind val to name in ctx, and make sure that all intermediate contexts exist
 * @param ctx the parent JNDI Context under which value will be bound
 * @param name the name relative to ctx where value will be bound
 * @param value the value to bind.
 * @throws NamingException for any error
 */
private static void bind(Context ctx, Name name, Object value) throws NamingException
{
   int size = name.size();
   String atom = name.get(size - 1);
   Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1));
   parentCtx.bind(atom, value);
}
 
源代码11 项目: tomee   文件: TomcatWebAppBuilder.java
/**
 * Binds given object into given component context.
 *
 * @param comp  context
 * @param name  name of the binding
 * @param value binded object
 */
private void safeBind(final Context comp, final String name, final Object value) {
    try {
        comp.lookup(name);
        LOGGER.debug(name + " already bound, ignoring");
    } catch (final Exception e) {
        try {
            comp.bind(name, value);
        } catch (final NamingException ne) {
            LOGGER.error("Error in safeBind method", e);
        }
    }
}
 
源代码12 项目: wildfly-camel   文件: JNDIIntegrationTest.java
private void assertBeanBinding(WildFlyCamelContext camelctx) throws NamingException, Exception {

        InitialContext inicxt = new InitialContext();
        String bindingName = CamelConstants.CAMEL_CONTEXT_BINDING_NAME + "/" + camelctx.getName();

        Context jndictx = camelctx.getNamingContext();
        jndictx.bind("helloBean", new HelloBean());
        try {
            camelctx.addRoutes(new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    from("direct:start").bean("helloBean");
                }
            });

            camelctx.start();
            try {

                // Assert that the context is bound into JNDI after start
                CamelContext lookup = (CamelContext) inicxt.lookup(bindingName);
                Assert.assertSame(camelctx, lookup);

                ProducerTemplate producer = camelctx.createProducerTemplate();
                String result = producer.requestBody("direct:start", "Kermit", String.class);
                Assert.assertEquals("Hello Kermit", result);
            } finally {
                camelctx.close();
            }

            // Assert that the context is unbound from JNDI after stop
            Assert.assertTrue("Expected " + bindingName + " to be unbound", awaitUnbinding(inicxt, bindingName));
        } finally {
            jndictx.unbind("helloBean");
            Assert.assertTrue("Expected java:/helloBean to be unbound", awaitUnbinding(jndictx, "helloBean"));
        }
    }
 
源代码13 项目: development   文件: BaseAdmUmTest.java
protected static FifoJMSQueue createIndexerQueue() throws NamingException,
        JMSException {
    enableJndiMock();
    Context jndiContext = new InitialContext();
    // static queue required since hibernate listener caches queue object
    FifoJMSQueue indexerQueue = new FifoJMSQueue();
    jndiContext.bind("jms/bss/indexerQueueFactory",
            initMockFactory(indexerQueue));
    jndiContext.bind("jms/bss/indexerQueue", indexerQueue);
    return indexerQueue;
}
 
源代码14 项目: gemfirexd-oss   文件: ContextImpl.java
/**
 * Rebinds object obj to name name . If there is existing binding it will be
 * overwritten.
 * 
 * @param name name of the object to rebind.
 * @param obj object to add. Can be null.
 * @throws NoPermissionException if this context has been destroyed
 * @throws InvalidNameException if name is empty or is CompositeName that
 *           spans more than one naming system
 * @throws NotContextException if name has more than one atomic name and
 *           intermediate context is not found
 * @throws NamingException if any other naming error occurs
 *  
 */
public void rebind(Name name, Object obj) throws NamingException {
  checkIsDestroyed();
  Name parsedName = getParsedName(name);
  if (parsedName.size() == 0 || parsedName.get(0).length() == 0) { throw new InvalidNameException(LocalizedStrings.ContextImpl_NAME_CAN_NOT_BE_EMPTY.toLocalizedString()); }
  String nameToBind = parsedName.get(0);
  if (parsedName.size() == 1) {
    ctxMaps.put(nameToBind, obj);
  }
  else {
    Object boundObject = ctxMaps.get(nameToBind);
    if (boundObject instanceof Context) {
      /*
       * Let the subcontext bind the object.
       */
      ((Context) boundObject).bind(parsedName.getSuffix(1), obj);
    }
    else {
      if (boundObject == null) {
        // Create new subcontext and let it do the binding
        Context sub = createSubcontext(nameToBind);
        sub.bind(parsedName.getSuffix(1), obj);
      }
      else {
        throw new NotContextException(LocalizedStrings.ContextImpl_EXPECTED_CONTEXT_BUT_FOUND_0.toLocalizedString(boundObject));
      }
    }
  }
}
 
源代码15 项目: gameserver   文件: MysqlUtil.java
/**
 * Initialize the connection pool.
 */
public static final void init(String database, String username, String password, 
		String server, int maxConn, int minConn, String jndi) {
	String dbUrl = StringUtil.concat("jdbc:mysql://", server, ":3306/", database, 
			"?connectTimeout=", 10000, "&useUnicode=true&characterEncoding=utf8");
	
	logger.info("Try to connect to Mysql with url: {}", dbUrl);
	
  // create a new configuration object
 	BoneCPConfig config = new BoneCPConfig();
  // set the JDBC url
 	config.setJdbcUrl(dbUrl);
 	config.setPartitionCount(2);
 	config.setMaxConnectionsPerPartition(maxConn);
 	config.setMinConnectionsPerPartition(minConn);
 	config.setUsername(username);
 	config.setPassword(password);
	
  // setup the connection pool
	try {
		BoneCPDataSource dataSource = new BoneCPDataSource(config);
		Context jndiContext = GameContext.getInstance().getJndiContext();
		jndiContext.bind(jndi, dataSource);
		dataSourceMap.put(jndi, dataSource);
		dataSourceReadyMap.put(jndi, Boolean.TRUE);
	} catch (Exception e) {
		logger.warn("The connection to Mysql database is unavailable. Exception:{}", e.getMessage());
		dataSourceReadyMap.put(jndi, Boolean.FALSE);
	}
}
 
源代码16 项目: juddi   文件: JNDIRegistration.java
/**
 * Registers the Publish and Inquiry Services to JNDI and instantiates a
 * instance of each so we can remotely attach to it later.
 */
public void register(int port) {
	try {
		Context juddiContext = context.createSubcontext(JUDDI);
		
		securityService = new UDDISecurityService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + UDDI_SECURITY_SERVICE + ", " + securityService.getClass());
		juddiContext.bind(UDDI_SECURITY_SERVICE, securityService);
		
		publicationService = new UDDIPublicationService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + UDDI_PUBLICATION_SERVICE + ", " + publicationService.getClass());
		juddiContext.bind(UDDI_PUBLICATION_SERVICE, publicationService);
		
		inquiryService = new UDDIInquiryService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + UDDI_INQUIRY_SERVICE + ", " + inquiryService.getClass());
		juddiContext.bind(UDDI_INQUIRY_SERVICE, inquiryService);
		
		subscriptionService = new UDDISubscriptionService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + UDDI_SUBSCRIPTION_SERVICE + ", " + subscriptionService.getClass());
		juddiContext.bind(UDDI_SUBSCRIPTION_SERVICE, subscriptionService);
		
		subscriptionListenerService = new UDDISubscriptionListenerService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + UDDI_SUBSCRIPTION_LISTENER_SERVICE + ", " + subscriptionListenerService.getClass());
		juddiContext.bind(UDDI_SUBSCRIPTION_LISTENER_SERVICE, subscriptionListenerService);
		
		custodyTransferService = new UDDICustodyTransferService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + UDDI_CUSTODY_TRANSFER_SERVICE + ", " + custodyTransferService.getClass());
		juddiContext.bind(UDDI_CUSTODY_TRANSFER_SERVICE, custodyTransferService);
		
		publisherService = new JUDDIApiService(port);
		if (log.isDebugEnabled()) log.debug("Setting " + JUDDI_PUBLISHER_SERVICE + ", " + publisherService.getClass());
		juddiContext.bind(JUDDI_PUBLISHER_SERVICE, publisherService);
		
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
}
 
源代码17 项目: ironjacamar   文件: TransactionManagerImpl.java
/**
 * Start
 * @exception Throwable Thrown if an error occurs
 */
public void start() throws Throwable
{
   Context context = new InitialContext();

   context.bind(JNDI_NAME, this);

   context.close();
}
 
源代码18 项目: tomee   文件: JavaLookupTest.java
public void testLinking() throws Exception {

        final Assembler assembler = new Assembler();
        final ConfigurationFactory config = new ConfigurationFactory();

        assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
        assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));

        final InitialContext context = new InitialContext();

        final Context javaContext = (Context) context.lookup("java:");

        javaContext.bind("java:TransactionManager", new JndiUrlReference("java:comp/TransactionManager"));
        javaContext.bind("java:TransactionManagerLink", new LinkRef("java:comp/TransactionManager"));

        assertTrue(context.lookup("java:TransactionManager") instanceof TransactionManager);
        assertTrue(context.lookup("java:TransactionManagerLink") instanceof TransactionManager);

        new InitialContext().bind("java:foo", new LinkRef("java:comp/TransactionManager"));

        assertTrue(context.lookup("java:foo") instanceof TransactionManager);


    }
 
源代码19 项目: servicemix   文件: JMSAppenderTest.java
@Override
protected Context createJndiContext() throws Exception {
    Context context = super.createJndiContext();
    context.bind("amq", ActiveMQComponent.activeMQComponent(broker.getVmConnectorURI().toString() + "?create=false"));
    return context;
}
 
源代码20 项目: wildfly-camel   文件: TikaIntegrationTest.java
private static BeanRepository createRegistryWithEmptyConfig() throws Exception {
  	Context jndiContext = createJndiContext();
  	jndiContext.bind("testConfig", new TikaConfig(new File("src/test/resources/tika/tika-empty.xml")));
JndiBeanRepository repository = new JndiBeanRepository(jndiContext);
      return repository;
  }