/** * In this method we are trying to create an InitialContext from the FooInitialContextFactory by setting the * java.naming.factory.initial environment variable. */ @Test(dependsOnMethods = "testJNDIContextManagerWithEnvironmentContextFactoryException") public void testJNDIContextManagerWithEnvironmentContextFactory() throws NamingException { ServiceRegistration serviceRegistration = bundleContext.registerService( new String[]{InitialContextFactory.class.getName(), FooInitialContextFactory.class.getName()}, new FooInitialContextFactory(), null); Map<String, String> environment = new HashMap<String, String>(1); environment.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, FooInitialContextFactory.class.getName()); Context initialContext = jndiContextManager.newInitialContext(environment); initialContext.bind("contextFactoryClass", "org.wso2.carbon.jndi.internal.InMemoryInitialContextFactory"); String contextFactoryClass = (String) initialContext.lookup("contextFactoryClass"); assertEquals(contextFactoryClass, FooInitialContextFactory.class.getName(), "Specified InitialContextFactory " + "has not been picked up to create the requested initial context."); // Unregistering the FooInitialContextFactory service. serviceRegistration.unregister(); }
/** * In this method we are testing the functionality of the JNDIContextManager when there exists * an InitialContextFactory service which throws a NamingException. */ @Test(dependsOnMethods = "testCustomInitialContextFactories", expectedExceptions = {NamingException.class}, expectedExceptionsMessageRegExp = "InitialContext cannot be created due to a network failure.") public void testCustomInitialContextFactoryWithException() throws NamingException { // To test null from getInitialContext methods. Dictionary<String, Object> propertyMap = new Hashtable<>(); propertyMap.put("service.ranking", 40); ServiceRegistration<InitialContextFactory> exceptionFactorySR = bundleContext.registerService( InitialContextFactory.class, new ExceptionInitialContextFactory(), propertyMap); try { Context initialContext = jndiContextManager.newInitialContext(); } finally { // Unregistering the InitialContextFactory which throws an exception. exceptionFactorySR.unregister(); } }
@Override public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> hashtable) throws NamingException { // check if we are inside the Marmotta or outside; inside the Marmotta we return our own context factory, // outside the system default try { return (InitialContextFactory) Thread.currentThread().getContextClassLoader().loadClass(MarmottaContextFactory.class.getName()).getMethod("getInstance").invoke(null); } catch (Exception e) { String factoryName = Context.INITIAL_CONTEXT_FACTORY; try { return (InitialContextFactory) Thread.currentThread().getContextClassLoader().loadClass(factoryName).newInstance(); } catch (Exception e1) { throw new NamingException("default context factory "+factoryName+" could not be initialised"); } } }
/** * Builds {@link InitialContextFactory} from passed requested ( * {@link String}) class name * * @param requestedFactory * @return {@link InitialContextFactory} * @throws NoInitialContextException */ private InitialContextFactory simulateBuilderLessNamingManager(String requestedFactory) throws NoInitialContextException { InitialContextFactory factory; Class<?> requestedClass; try { requestedClass = ClassUtils.initClassForName(requestedFactory); Object instance = ClassUtils.instantiate(requestedClass); factory = ObjectUtils.cast(instance, InitialContextFactory.class); } catch (IOException ex) { NoInitialContextException nex = new NoInitialContextException(COULD_NOT_FIND_ERROR); nex.setRootCause(ex); throw nex; } return factory; }
/** * This method test the code which retrieve the caller's BundleContext instance from the * osgi.service.jndi.bundleContext environment variable defined in the OSGi JNDI Specification. */ @Test(dependsOnMethods = "testJNDIContextManagerService") public void testJNDITraditionalClientWithEnvironmentBC() throws NamingException { // Getting the BundleContext of the org.wso2.carbon.jndi bundle. BundleContext carbonJNDIBundleContext = Arrays.asList(bundleContext.getBundles()) .stream() .filter(bundle -> "org.wso2.carbon.jndi".equals(bundle.getSymbolicName())) .map(Bundle::getBundleContext) .findAny() .get(); // This is used to get the caller's bundle context object. BundleContextICFServiceFactory bundleContextICFServiceFactory = new BundleContextICFServiceFactory(); Dictionary<String, Object> propertyMap = new Hashtable<>(); propertyMap.put("service.ranking", 10); ServiceRegistration serviceRegistration = bundleContext.registerService(InitialContextFactory.class.getName(), bundleContextICFServiceFactory, propertyMap); //Setting carbonJNDIBundleContext as the value of osgi.service.jndi.bundleContext property. Hashtable<String, Object> environment = new Hashtable<>(1); environment.put("osgi.service.jndi.bundleContext", carbonJNDIBundleContext); InitialContext initialContext = new InitialContext(environment); initialContext.createSubcontext("java:comp/bundleContext"); assertEquals(bundleContextICFServiceFactory.getFirstConsumersBundleContext().getBundle().getSymbolicName(), carbonJNDIBundleContext.getBundle().getSymbolicName(), "Value of the osgi.service.jndi.bundleContext " + "environment variable has not been picked up"); serviceRegistration.unregister(); }
/** * This method test the code which retrieve the caller's BundleContext instance from the * Thread Context ClassLoader. */ @Test(dependsOnMethods = "testJNDITraditionalClientWithEnvironmentBC") public void testJNDITraditionalClientWithTCCL() throws NamingException { DummyBundleClassLoader dummyBundleClassLoader = new DummyBundleClassLoader(this.getClass().getClassLoader(), bundleContext.getBundle()); Dictionary<String, Object> propertyMap = new Hashtable<>(); propertyMap.put("service.ranking", 10); ServiceRegistration serviceRegistration = bundleContext.registerService(InitialContextFactory.class.getName(), new FooInitialContextFactory(), propertyMap); ClassLoader currentTCCL = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(dummyBundleClassLoader); InitialContext initialContext = new InitialContext(); initialContext.createSubcontext("java:comp/tccl"); } finally { Thread.currentThread().setContextClassLoader(currentTCCL); } assertEquals(true, dummyBundleClassLoader.isGetBundleMethodInvoked(), "TCCL has not used to get the " + "caller's Bundle"); serviceRegistration.unregister(); }
@Override public void start(BundleContext bundleContext) throws Exception { try { NamingManager.setInitialContextFactoryBuilder(new DefaultContextFactoryBuilder()); NamingManager.setObjectFactoryBuilder(new DefaultObjectFactoryBuilder()); Dictionary<String, String> propertyMap = new Hashtable<>(); propertyMap.put(JNDIConstants.JNDI_URLSCHEME, "java"); bundleContext.registerService(ObjectFactory.class, new JavaURLContextFactory(), propertyMap); //register osgi url scheme Dictionary<String, String> osgiPropertyMap = new Hashtable<>(); osgiPropertyMap.put(JNDIConstants.JNDI_URLSCHEME, "osgi"); bundleContext.registerService(ObjectFactory.class.getName(), new OSGiURLContextServiceFactory(), osgiPropertyMap); // InitialContextFactory Provider should be registered with its implementation class as well as the // InitialContextFactory class. bundleContext.registerService(InitialContextFactory.class, new InMemoryInitialContextFactory(), null); logger.debug("Registering JNDIContextManager OSGi service."); bundleContext.registerService(JNDIContextManager.class, new JNDIContextManagerServiceFactory(), null); } catch (Throwable e) { logger.error(e.getMessage(), e); } }
/** * Create a service filter which matches OSGi services registered with two values for the objectClass property. * <p> * User defined initial context factory class name and the InitialContextFactory class name are those two values of * the objectClass property. * * @param userDefinedICFClassName value of java.naming.factory.initial property * @return filter string */ private String getServiceFilter(String userDefinedICFClassName) { // Here I've initially user StringBuilder, but IntelliJ IDEA suggested to replace StringBuilder usage with // Strings becuause for this specific case, String concatenation is at least as efficient or more efficent // than the original StringBuilder or StringBuffer user. return "(&" + "(" + OBJECT_CLASS + "=" + userDefinedICFClassName + ")" + "(" + OBJECT_CLASS + "=" + InitialContextFactory.class.getName() + ")" + ")"; }
/** * @param builderOptional an {@code Optional} describing InitialContextFactoryBuilder instance. * @param environment The possibly null environment * specifying information to be used in the creation * of the initial context. * @return an {@code Optional} describing the created InitialContextFactory instance. */ public static Optional<InitialContextFactory> getContextFactory( Optional<InitialContextFactoryBuilder> builderOptional, Hashtable<?, ?> environment) { return builderOptional.map(builder -> { try { return builder.createInitialContextFactory(environment); } catch (NamingException ignored) { // According to the OSGi JNDI service specification this exception should not thrown to the caller. logger.debug(ignored.getMessage(), ignored); return null; } }); }
/** * @param bundleContext caller BundleContext. * @param serviceRefCollection collection of {@code ServiceReference} objects of InitialContextFactory. * @param environment The possibly null environment * specifying information to be used in the creation * of the initial context. * @return an {@code Optional} describing created initial context from the factory. * @throws NamingException upon any error that occurs during context creation */ public static Optional<Context> getInitialContextFromFactory( BundleContext bundleContext, Collection<ServiceReference<InitialContextFactory>> serviceRefCollection, Hashtable<?, ?> environment) throws NamingException { return serviceRefCollection .stream() // .sorted(new ServiceRankComparator()) .map(serviceReference -> getService(bundleContext, serviceReference)) .flatMap(factoryOptional -> factoryOptional.map(Stream::of).orElseGet(Stream::empty)) .map(rethrowFunction(contextFactory -> contextFactory.getInitialContext(environment))) .filter(context -> context != null) .findFirst(); }
@Override protected void setUp() throws Exception { super.setUp(); configureEnvironment(); InitialContextFactory factory = new ActiveMQInitialContextFactory(); context = factory.getInitialContext(environment); assertTrue("No context created", context != null); }
public ResourcePoint() { try { InitialContextFactory factory = createInitialContextFactory(); ctx = factory.getInitialContext(new Hashtable<>()); } catch (NamingException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } }
public InitialContextFactory createInitialContextFactory() { try { return createInitialContextFactory(new Hashtable<>()); } catch (NamingException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } }
@BeforeClass public static void beforeClass() throws Exception { URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties"); configuration = new PropertiesConfiguration(sqlProperties); if (!configuration.containsKey("jdbc.url")) { throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url")); } String url = configuration.getString("jdbc.url"); //obtain the connection that we will later supply from JNDI SqlgPlugin p = findSqlgPlugin(url); Assert.assertNotNull(p); ds = new C3p0DataSourceFactory().setup(p.getDriverFor(url), configuration).getDatasource(); //change the connection url to be a JNDI one configuration.setProperty("jdbc.url", "jndi:testConnection"); //set up the initial context NamingManager.setInitialContextFactoryBuilder(environment -> { InitialContextFactory mockFactory = mock(InitialContextFactory.class); Context mockContext = mock(Context.class); when(mockFactory.getInitialContext(any())).thenReturn(mockContext); when(mockContext.lookup("testConnection")).thenReturn(ds); return mockFactory; }); }
public InitialContextFactory createInitialContextFactory(Hashtable<?,?> envmt) throws NamingException { NamingManagerTest.issueIndicatedExceptions(envmt); if (NamingManagerTest.returnNullIndicated(envmt)) { return null; } return new MockInitialContextFactory(envmt); }
/** * Initializes {@link InitialContextFactory} from passed class name * * @param requestedFactory * @return {@link InitialContextFactory} instance from factory class name * @throws NoInitialContextException */ private InitialContextFactory instantiateFromName(String requestedFactory) throws NoInitialContextException { InitialContextFactory initialContextFactory; if (requestedFactory == null) { initialContextFactory = new LightmareContextFactory(); } else { initialContextFactory = simulateBuilderLessNamingManager(requestedFactory); } return initialContextFactory; }
/** * Initializes {@link InitialContextFactory} implementation for passed * parameters */ @Override public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> env) throws NamingException { InitialContextFactory initialContextFactory; String requestedFactory = getRequestedFactory(env); initialContextFactory = instantiateFromName(requestedFactory); return initialContextFactory; }
@Override public InitialContextFactory createInitialContextFactory(Hashtable env) throws NamingException { return new LocalContext(env); }
/** * In this method we are testing the functionality of the JNDIContextManager when there are multiple * InitialContextFactory services with different service.ranking property value. * <p> * We also test the situation with an InitialContextFactory which returns a null context. */ @Test(dependsOnMethods = "testJNDIContextManagerWithEnvironmentContextFactory") public void testCustomInitialContextFactories() throws NamingException { Dictionary<String, Object> propertyMap = new Hashtable<>(); propertyMap.put("service.ranking", 10); ServiceRegistration<InitialContextFactory> fooICFServiceRef = bundleContext.registerService( InitialContextFactory.class, new FooInitialContextFactory(), propertyMap); Context initialContext = jndiContextManager.newInitialContext(); // Here we expect returned Context to be an instance of the TestContext. Following bind operation is ignored // in the TestContext class. It is hard coded to return the created InitialContextFactory if you invoke the // TestContext.lookup("contextFactoryClass"). In this case it should be the FooInitialContextFactory initialContext.bind("contextFactoryClass", "org.wso2.carbon.jndi.internal.InMemoryInitialContextFactory"); String contextFactoryClass = (String) initialContext.lookup("contextFactoryClass"); assertEquals(contextFactoryClass, FooInitialContextFactory.class.getName(), "Specified InitialContextFactory " + "has not been picked up to create the requested initial context."); // Now we are registering another InitialContextFactory with a higher service.ranking value. propertyMap = new Hashtable<>(); propertyMap.put("service.ranking", 20); ServiceRegistration<InitialContextFactory> barICFServiceRef = bundleContext.registerService( InitialContextFactory.class, new BarInitialContextFactory(), propertyMap); initialContext = jndiContextManager.newInitialContext(); initialContext.bind("contextFactoryClass", "org.wso2.carbon.jndi.internal.InMemoryInitialContextFactory"); contextFactoryClass = (String) initialContext.lookup("contextFactoryClass"); assertEquals(contextFactoryClass, BarInitialContextFactory.class.getName(), "Specified InitialContextFactory " + "has not been picked up to create the requested initial context."); // To test null from getInitialContext methods. propertyMap = new Hashtable<>(); propertyMap.put("service.ranking", 30); ServiceRegistration<InitialContextFactory> nullICFServiceRef = bundleContext.registerService( InitialContextFactory.class, new NullInitialContextFactory(), propertyMap); initialContext = jndiContextManager.newInitialContext(); initialContext.bind("contextFactoryClass", "org.wso2.carbon.jndi.internal.InMemoryInitialContextFactory"); contextFactoryClass = (String) initialContext.lookup("contextFactoryClass"); assertEquals(contextFactoryClass, BarInitialContextFactory.class.getName(), "Specified InitialContextFactory " + "has not been picked up to create the requested initial context."); // Unregistering all the registered ICF services. fooICFServiceRef.unregister(); barICFServiceRef.unregister(); nullICFServiceRef.unregister(); }
@Override public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { return null; }
@Override public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { return new DefaultContextFactory(); }
@Override public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { return new Factory(environment); }
@Override public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { return this; }
public InitialContextFactory createInitialContextFactory(Hashtable environment) throws NamingException { // return new MockContextFactory(); return null; }
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { return new MockContextFactory(); }