javax.naming.Context Java Examples

The following examples show how to use javax.naming.Context. 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: JndiTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testLookupFailsWithTypeMismatch() throws Exception {
	Object o = new Object();
	String name = "foo";
	final Context context = mock(Context.class);
	given(context.lookup(name)).willReturn(o);

	JndiTemplate jt = new JndiTemplate() {
		@Override
		protected Context createInitialContext() {
			return context;
		}
	};

	try {
		jt.lookup(name, String.class);
		fail("Should have thrown TypeMismatchNamingException");
	}
	catch (TypeMismatchNamingException ex) {
		// Ok
	}
	verify(context).close();
}
 
Example #2
Source File: DirectoryManager.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
private static Object createObjectFromFactories(Object obj, Name name,
        Context nameCtx, Hashtable<?,?> environment, Attributes attrs)
    throws Exception {

    FactoryEnumeration factories = ResourceManager.getFactories(
        Context.OBJECT_FACTORIES, environment, nameCtx);

    if (factories == null)
        return null;

    ObjectFactory factory;
    Object answer = null;
    // Try each factory until one succeeds
    while (answer == null && factories.hasMore()) {
        factory = (ObjectFactory)factories.next();
        if (factory instanceof DirObjectFactory) {
            answer = ((DirObjectFactory)factory).
                getObjectInstance(obj, name, nameCtx, environment, attrs);
        } else {
            answer =
                factory.getObjectInstance(obj, name, nameCtx, environment);
        }
    }
    return answer;
}
 
Example #3
Source File: ContextTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {
  // InitialContextFactoryImpl impl = new InitialContextFactoryImpl();
  //	impl.setAsInitial();
  Hashtable table = new Hashtable();
  table
  .put(
      Context.INITIAL_CONTEXT_FACTORY,
  "com.gemstone.gemfire.internal.jndi.InitialContextFactoryImpl");
  //	table.put(Context.URL_PKG_PREFIXES,
  // "com.gemstone.gemfire.internal.jndi");
  initialCtx = new InitialContext(table);
  initialCtx.bind("java:gf/env/datasource/oracle", "a");
  gfCtx = (Context) initialCtx.lookup("java:gf");
  envCtx = (Context) gfCtx.lookup("env");
  datasourceCtx = (Context) envCtx.lookup("datasource");
}
 
Example #4
Source File: CacheTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private Object loadFromDatabase(Object ob)
{
  Object obj =  null;
  try{
	Context ctx = CacheFactory.getAnyInstance().getJNDIContext();
	DataSource ds = (DataSource)ctx.lookup("java:/XAPooledDataSource");
	Connection conn = ds.getConnection();
	Statement stm = conn.createStatement();
	String str = "update "+ tableName +" set name ='newname' where id = ("+(new Integer(ob.toString())).intValue()+")";
	stm.executeUpdate(str);
	ResultSet rs = stm.executeQuery("select name from "+ tableName +" where id = ("+(new Integer(ob.toString())).intValue()+")");
	rs.next();
	obj = rs.getString(1);
	stm.close();
	conn.close();
	return obj;
  }catch(Exception e){
	e.printStackTrace();
  }
  return obj;
}
 
Example #5
Source File: TestNamingContext.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug53465() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

    File appDir =
        new File("test/webapp-3.0");
    // app dir is relative to server home
    org.apache.catalina.Context ctxt =
            tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug53465.jsp", bc, null);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(bc.toString().contains("<p>10</p>"));

    ContextEnvironment ce =
            ctxt.getNamingResources().findEnvironment("bug53465");
    Assert.assertEquals("Bug53465MappedName", ce.getProperty("mappedName"));
}
 
Example #6
Source File: DefaultInstanceManager.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
public DefaultInstanceManager(Context context, Map<String, Map<String, String>> injectionMap, org.apache.catalina.Context catalinaContext, ClassLoader containerClassLoader) {
    classLoader = catalinaContext.getLoader().getClassLoader();
    privileged = catalinaContext.getPrivileged();
    this.containerClassLoader = containerClassLoader;
    ignoreAnnotations = catalinaContext.getIgnoreAnnotations();
    StringManager sm = StringManager.getManager(Constants.Package);
    restrictedServlets = loadProperties(
            "org/apache/catalina/core/RestrictedServlets.properties",
            sm.getString("defaultInstanceManager.restrictedServletsResource"),
            catalinaContext.getLogger());
    restrictedListeners = loadProperties(
            "org/apache/catalina/core/RestrictedListeners.properties",
            "defaultInstanceManager.restrictedListenersResources",
            catalinaContext.getLogger());
    restrictedFilters = loadProperties(
            "org/apache/catalina/core/RestrictedFilters.properties",
            "defaultInstanceManager.restrictedFiltersResource",
            catalinaContext.getLogger());
    this.context = context;
    this.injectionMap = injectionMap;
    this.postConstructMethods = catalinaContext.findPostConstructMethods();
    this.preDestroyMethods = catalinaContext.findPreDestroyMethods();
}
 
Example #7
Source File: UserTransactionFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
    // get the transaction manager
    final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
    if (transactionManager == null) {
        throw new NamingException("transaction manager not found");
    }

    // if transaction manager implements user transaction we are done
    if (transactionManager instanceof UserTransaction) {
        return transactionManager;
    }

    // wrap transaction manager with user transaction
    return new CoreUserTransaction(transactionManager);
}
 
Example #8
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 #9
Source File: QuarkusDirContextFactory.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
    final String className = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
    try {
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return (InitialContextFactory) Class.forName(className, true, cl).newInstance();
    } catch (Exception e) {
        NoInitialContextException ne = new NoInitialContextException(
                "Cannot instantiate class: " + className);
        ne.setRootCause(e);
        throw ne;
    }
}
 
Example #10
Source File: ExecServer.java    From oodt with Apache License 2.0 6 votes vote down vote up
public void run() {
	while (shouldKeepBinding()) {
	  try {
		Context objectContext = configuration.getObjectContext();
		objectContext.rebind(name, server.getServant());
		objectContext.close();
	  } catch (Exception ex) {
		System.err.println("Exception binding at " + new Date() + "; will keep trying...");
		ex.printStackTrace();
	  } finally {
		try {
		  Thread.sleep(REBIND_PERIOD);
		} catch (InterruptedException ignore) {
		}
	  }
	}
}
 
Example #11
Source File: ConnectionPoolingTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testConnectionPoolFunctions() {
  try {
    Context ctx = cache.getJNDIContext();
    ds = (GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource");
    PoolClient_1 clientA = new PoolClient_1();
    ThreadA = new Thread(clientA, "ThreadA");
    PoolClient_2 clientB = new PoolClient_2();
    ThreadB = new Thread(clientB, "ThreadB");
    // ThreadA.setDaemon(true);
    //ThreadB.setDaemon(true);
    ThreadA.start();
  }
  catch (Exception e) {
    fail("Exception occured in testConnectionPoolFunctions due to " + e);
    e.printStackTrace();
  }
}
 
Example #12
Source File: PluginServiceFactoryTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createJndiProperties() {
    // given
    Properties props = createConnectionProperties(jndiName);

    // when
    Properties jndiProps = PluginServiceFactory.createJndiProperties(props);

    // then
    assertEquals(props.get(Context.PROVIDER_URL),
            jndiProps.get(Context.PROVIDER_URL));
    assertEquals(props.get(Context.INITIAL_CONTEXT_FACTORY),
            jndiProps.get(Context.INITIAL_CONTEXT_FACTORY));
    assertEquals(props.get(ORBINITIALHOST), jndiProps.get(ORBINITIALHOST));
    assertEquals(props.get(ORBINITIALPORT), jndiProps.get(ORBINITIALPORT));
    assertEquals(4, jndiProps.size());
    assertNull(props.get(PluginServiceFactory.JNDI_NAME));

}
 
Example #13
Source File: LdapConnector.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
private Hashtable<String, String> createEnv(final String user, final String password)
{
  // Set up the environment for creating the initial context
  final Hashtable<String, String> env = new Hashtable<String, String>();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, ldapConfig.getCompleteServerUrl());
  final String authentication = ldapConfig.getAuthentication();
  if (StringUtils.isNotBlank(authentication) == true) {
    env.put(Context.SECURITY_AUTHENTICATION, ldapConfig.getAuthentication());
    if ("none".equals(authentication) == false || user != null || password != null) {
      env.put(Context.SECURITY_PRINCIPAL, user);
      env.put(Context.SECURITY_CREDENTIALS, password);
    }
  }
  if (ldapConfig != null && StringUtils.isNotBlank(ldapConfig.getSslCertificateFile()) == true) {
    env.put("java.naming.ldap.factory.socket", "org.projectforge.ldap.MySSLSocketFactory");
  }
  log.info("Trying to connect the LDAP server: url=["
      + ldapConfig.getCompleteServerUrl()
      + "], authentication=["
      + ldapConfig.getAuthentication()
      + "], principal=["
      + user
      + "]");
  return env;
}
 
Example #14
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testIndexOnCommitForDestroy() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.destroy(x);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #15
Source File: NamingManager.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #16
Source File: JTAUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void listTableData(String tableName) throws NamingException, SQLException {
  Context ctx = CacheHelper.getCache().getJNDIContext();
  DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
  
  String sql = "select * from " + tableName;
  Log.getLogWriter().info("listTableData: " + sql);
  
  Connection conn = ds.getConnection();
  Statement sm = conn.createStatement();
  ResultSet rs = sm.executeQuery(sql);
  while (rs.next()) {
    Log.getLogWriter().info("id " + rs.getString(1) + " name " + rs.getString(2));
  }
  rs.close();
  conn.close();
}
 
Example #17
Source File: OpenEJBXmlByModuleTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws OpenEJBException, NamingException, IOException {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();

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

    final AppModule app = new AppModule(OpenEJBXmlByModuleTest.class.getClassLoader(), OpenEJBXmlByModuleTest.class.getSimpleName());

    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new SingletonBean(UselessBean.class));
    app.getEjbModules().add(new EjbModule(ejbJar));
    app.getEjbModules().iterator().next().getAltDDs().put("resources.xml", getClass().getClassLoader().getResource("META-INF/resource/appresource.openejb.xml"));

    assembler.createApplication(config.configureApplication(app));

    final Properties properties = new Properties();
    properties.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
    properties.setProperty("openejb.embedded.initialcontext.close", "destroy");

    // some hack to be sure to call destroy()
    context = new InitialContext(properties);

    bean = (UselessBean) context.lookup("UselessBeanLocalBean");
}
 
Example #18
Source File: LdapConnectionTest.java    From scriptella-etl with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if LDAP connection correctly initialized.
 */
public void test() {
    Map<String, String> params = new HashMap<String, String>();
    String dn = "dc=scriptella";
    params.put(LdapConnection.SEARCH_BASEDN_KEY, dn);
    params.put(LdapConnection.SEARCH_SCOPE_KEY, "subtree");
    params.put(LdapConnection.FILE_MAXLENGTH_KEY, "100");
    final String url = "ldap://127.0.0.1:389/";
    ConnectionParameters cp = new MockConnectionParameters(params, url);
    ctxInitialized = false;
    LdapConnection con = new LdapConnection(cp) {
        @Override
        protected void initializeContext(Hashtable<String, Object> env) {
            ctxInitialized = true;
            //Simple checks if environment has been correctly set up
            assertEquals(url, env.get(Context.PROVIDER_URL));
            assertNotNull(env.get(Context.INITIAL_CONTEXT_FACTORY));

        }
    };
    assertEquals(dn, con.getBaseDn());
    assertEquals(SearchControls.SUBTREE_SCOPE, con.getSearchControls().getSearchScope());
    assertEquals(100, (long) con.getMaxFileLength());
    assertTrue(ctxInitialized);
}
 
Example #19
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static boolean undeploy(final StandardContext standardContext, final Container host) {
    final Container child = host.findChild(standardContext.getName());

    // skip undeployment if redeploying (StandardContext.redeploy())
    if (child instanceof org.apache.catalina.Context && org.apache.catalina.Context.class.cast(child).getPaused()) {
        return true;
    }

    // skip undeployment if restarting
    final TomEEWebappClassLoader tomEEWebappClassLoader = lazyClassLoader(
        org.apache.catalina.Context.class.isInstance(child) ? org.apache.catalina.Context.class.cast(child) : null);
    if (tomEEWebappClassLoader != null && tomEEWebappClassLoader.isRestarting()) {
        return true;
    }

    if (child != null) {
        host.removeChild(standardContext);
        return true;
    }
    return false;
}
 
Example #20
Source File: ParallelizeTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
    System.out.println("ParallelizeAntRunnerTest.MyContextFactory.getInitialContext()");
    InitialContext mockedInitialContext = PowerMockito.mock(InitialContext.class);
    NamingEnumeration<NameClassPair> mockedEnumeration = PowerMockito.mock(NamingEnumeration.class);
    // Look at this again ...
    PowerMockito.mockStatic(NamingEnumeration.class);
    //
    PowerMockito.when(mockedEnumeration.hasMore()).thenReturn(true, true, true, true, false);
    PowerMockito.when(mockedEnumeration.next()).thenReturn(
            new NameClassPair("data.dir", String.class.getName()),
            new NameClassPair("parallelize", String.class.getName()),
            new NameClassPair("mutant.coverage", String.class.getName()),
            new NameClassPair("ant.home", String.class.getName())//
    );

    PowerMockito.when(mockedInitialContext.toString()).thenReturn("Mocked Initial Context");
    PowerMockito.when(mockedInitialContext.list("java:/comp/env")).thenReturn(mockedEnumeration);

    Context mockedEnvironmentContext = PowerMockito.mock(Context.class);
    PowerMockito.when(mockedInitialContext.lookup("java:/comp/env")).thenReturn(mockedEnvironmentContext);

    PowerMockito.when(mockedEnvironmentContext.lookup("mutant.coverage")).thenReturn("enabled");
    // FIXME
    PowerMockito.when(mockedEnvironmentContext.lookup("parallelize")).thenReturn("enabled");

    PowerMockito.when(mockedEnvironmentContext.lookup("data.dir"))
            .thenReturn(codedefendersHome.getAbsolutePath());

    PowerMockito.when(mockedEnvironmentContext.lookup("ant.home")).thenReturn("/usr/local");

    return mockedInitialContext;
}
 
Example #21
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 #22
Source File: JndiReference.java    From tomee with Apache License 2.0 5 votes vote down vote up
public Object getObject() throws NamingException {
    final Context externalContext = getContext();
    synchronized (externalContext) {
        /* According to the JNDI SPI specification multiple threads may not access the same JNDI 
        Context *instance* concurrently. Since we don't know the origines of the federated context we must
        synchonrize access to it.  JNDI SPI Sepecifiation 1.2 Section 2.2
        */
        return externalContext.lookup(jndiName);
    }
}
 
Example #23
Source File: JmsTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create the mock objects for testing.
 */
@Before
public void setupMocks() throws Exception {
	this.jndiContext = mock(Context.class);
	this.connectionFactory = mock(ConnectionFactory.class);
	this.connection = mock(Connection.class);
	this.session = mock(Session.class);
	this.queue = mock(Queue.class);

	given(this.connectionFactory.createConnection()).willReturn(this.connection);
	given(this.connection.createSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(this.session);
	given(this.session.getTransacted()).willReturn(useTransactedSession());
	given(this.jndiContext.lookup("testDestination")).willReturn(this.queue);
}
 
Example #24
Source File: BDBStoreUpgradeTestPreparer.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/**
 * Create a BDBStoreUpgradeTestPreparer instance
 */
public BDBStoreUpgradeTestPreparer () throws Exception
{
    // The configuration for the Qpid InitialContextFactory has been supplied in
    // a jndi.properties file in the classpath, which results in it being picked
    // up automatically by the InitialContext constructor.
    Context context = new InitialContext();

    _connFac = (ConnectionFactory) context.lookup("myConnFactory");
    _topciConnFac = (TopicConnectionFactory) context.lookup("myTopicConnFactory");
}
 
Example #25
Source File: JMSQueueMessageProducer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public JMSQueueMessageProducer(JMSBrokerConfiguration jmsBrokerConfiguration) throws NamingException {
    Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, jmsBrokerConfiguration.getInitialNamingFactory());
    if (jmsBrokerConfiguration.getProviderURL().startsWith(MB_BROKER_URL_PREFIX)) {
        //setting property for Qpid running on WSO2 MB
        properties.put("connectionfactory.QueueConnectionFactory", jmsBrokerConfiguration.getProviderURL());
    } else {
        //setting property for ActiveMQ
        properties.setProperty(Context.PROVIDER_URL, jmsBrokerConfiguration.getProviderURL());
    }
    Context context = new InitialContext(properties);
    connectionFactory = (QueueConnectionFactory) context.lookup("QueueConnectionFactory");
}
 
Example #26
Source File: NamingContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Creates and binds a new context. Creates a new context with the given
 * name and binds it in the target context (that named by all but
 * terminal atomic component of the name). All intermediate contexts and
 * the target context must already exist.
 *
 * @param name the name of the context to create; may not be empty
 * @return the newly created context
 * @exception NameAlreadyBoundException if name is already bound
 * @exception javax.naming.directory.InvalidAttributesException if creation
 * of the sub-context requires specification of mandatory attributes
 * @exception NamingException if a naming exception is encountered
 */
@Override
public Context createSubcontext(Name name) throws NamingException {
    if (!checkWritable()) {
        return null;
    }

    NamingContext newContext = new NamingContext(env, this.name);
    bind(name, newContext);

    newContext.setExceptionOnFailedWrite(getExceptionOnFailedWrite());

    return newContext;
}
 
Example #27
Source File: LocalContext.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public InitialContextFactory createInitialContextFactory(Hashtable env) throws NamingException {
	String className = (String)(env == null ? null : env.get(Context.INITIAL_CONTEXT_FACTORY));
	if (className != null) {
		try {
			return (InitialContextFactory)Class.forName(className).newInstance();
		} catch (Exception e) {
			throw new NamingException(e.getMessage());
		}
	}
	return new LocalContext(env);
}
 
Example #28
Source File: TxnManagerMultiThreadDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void destroyTable(String tblName) throws NamingException,
    SQLException {
  //the sleep below is given to give the time to threads to start and perform
  // before destroyTable is called.
  try {
    Thread.sleep(10 * 1000);
  }
  catch (InterruptedException ie) {
    fail("interrupted");
  }
  try {
    String tableName = tblName;
    getLogWriter().fine("Destroying table: " + tableName);
    cache = TxnManagerMultiThreadDUnitTest.getCache();
    Context ctx = cache.getJNDIContext();
    DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
    Connection conn = ds.getConnection();
    getLogWriter().fine(" trying to drop table: " + tableName);
    String sql = "drop table " + tableName;
    Statement sm = conn.createStatement();
    sm.execute(sql);
    conn.close();
    getLogWriter().fine("destroyTable is Successful!");
  }
  catch (NamingException ne) {
    getLogWriter().fine("destroy table naming exception: " + ne);
    throw ne;
  }
  catch (SQLException se) {
    getLogWriter().fine("destroy table sql exception: " + se);
    throw se;
  }
  finally {
    getLogWriter().fine("Closing cache...");
    closeCache();
  }
}
 
Example #29
Source File: NameNode.java    From tomee with Apache License 2.0 5 votes vote down vote up
public NameNode(final NameNode parent, final ParsedName name, final Object obj, final NameNode parentTree) {
    atomicName = name.getComponent();
    atomicHash = name.getComponentHashCode();
    this.parent = parent;
    this.parentTree = parentTree;
    if (name.next()) {
        subTree = new NameNode(this, name, obj, this);
    } else if (obj instanceof Context) {
        myObject = new Federation();
        ((Federation) myObject).add((Context) obj);
    } else {
        myObject = obj;
    }
}
 
Example #30
Source File: EJBServiceAccess.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T getService(Class<T> clazz) {
    try {
        Context context = new InitialContext();
        T service = clazz.cast(context.lookup(clazz.getName()));
        return service;
    } catch (NamingException e) {
        throw new SaaSSystemException("Service lookup failed!", e);
    }
}