Java Code Examples for javax.naming.Context#bind()

The following examples show how to use javax.naming.Context#bind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JndiRegistry.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 2
Source File: JNDIUtil.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
   }
}
 
Example 3
Source File: DataSourceCipheredExampleTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: UtilitiesForTest.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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);
}
 
Example 5
Source File: BaseAdmUmTest.java    From development with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: TransactionManagerImpl.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Start
 * @exception Throwable Thrown if an error occurs
 */
public void start() throws Throwable
{
   Context context = new InitialContext();

   context.bind(JNDI_NAME, this);

   context.close();
}
 
Example 7
Source File: JNDIRegistration.java    From juddi with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 8
Source File: MysqlUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 9
Source File: ContextImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
      }
    }
  }
}
 
Example 10
Source File: Util.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 11
Source File: JNDIIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
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"));
        }
    }
 
Example 12
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 13
Source File: Util.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 14
Source File: UserTransactionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Start
 * @exception Throwable Thrown if an error occurs
 */
public void start() throws Throwable
{
   Context context = new InitialContext();

   context.bind(JNDI_NAME, this);

   context.close();
}
 
Example 15
Source File: MoviesTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 16
Source File: TransactionSynchronizationRegistryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Start
 * @exception Throwable Thrown if an error occurs
 */
public void start() throws Throwable
{
   Context context = new InitialContext();

   context.bind(JNDI_NAME, this);

   context.close();
}
 
Example 17
Source File: DefaultInitialContextTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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"));
}
 
Example 18
Source File: JMSAppenderTest.java    From servicemix with Apache License 2.0 4 votes vote down vote up
@Override
protected Context createJndiContext() throws Exception {
    Context context = super.createJndiContext();
    context.bind("amq", ActiveMQComponent.activeMQComponent(broker.getVmConnectorURI().toString() + "?create=false"));
    return context;
}
 
Example 19
Source File: TikaIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
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;
  }
 
Example 20
Source File: JavaLookupTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
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);


    }