/** * {@inheritDoc} */ @Override public ClassLoader getDefaultClassLoader() { return ClassLoading.getDefaultClassLoader(); }
public static Schema discoverSchema(Source ... fixedSources) throws SAXException, IOException { ArrayList<Source> schemaSources = new ArrayList<>(asList(fixedSources)); for (CacheManagerServiceConfigurationParser<?> p : servicesOfType(CacheManagerServiceConfigurationParser.class)) { schemaSources.add(p.getXmlSchema()); } for (CacheServiceConfigurationParser<?> p : servicesOfType(CacheServiceConfigurationParser.class)) { schemaSources.add(p.getXmlSchema()); } for (CacheResourceConfigurationParser p : servicesOfType(CacheResourceConfigurationParser.class)) { schemaSources.add(p.getXmlSchema()); } return newSchema(schemaSources.toArray(new Source[0])); } }
for (String className : optionalAnnotation.value()) { try { Class<?> dependencyClass = delegationChain(getDefaultClassLoader(), clazz.getClassLoader()).loadClass(className); if (Service.class.isAssignableFrom(dependencyClass)) { @SuppressWarnings("unchecked")
@Override public ServiceCreationConfiguration<TransactionManagerProvider> parseServiceCreationConfiguration(Element fragment, ClassLoader classLoader) { String localName = fragment.getLocalName(); if ("jta-tm".equals(localName)) { String transactionManagerProviderConfigurationClassName = fragment.getAttribute("transaction-manager-lookup-class"); try { Class<?> aClass = Class.forName(transactionManagerProviderConfigurationClassName, true, delegationChain( () -> Thread.currentThread().getContextClassLoader(), getClass().getClassLoader(), classLoader )); Class<? extends TransactionManagerLookup> clazz = uncheckedCast(aClass); return new LookupTransactionManagerProviderConfiguration(clazz); } catch (Exception e) { throw new XmlConfigurationException("Error configuring XA transaction manager", e); } } else { throw new XmlConfigurationException(String.format("XML configuration element <%s> in <%s> is not supported", fragment.getTagName(), (fragment.getParentNode() == null ? "null" : fragment.getParentNode().getLocalName()))); } }
/** * Constructs an instance of XmlConfiguration from the given XML DOM. * <p> * The default ClassLoader will first try to use the thread context class loader, followed by the ClassLoader that * loaded the Ehcache classes. * * @param xml XML Document Object Model * * @throws XmlConfigurationException if anything went wrong parsing the XML */ public XmlConfiguration(Document xml) throws XmlConfigurationException { this(xml, ClassLoading.getDefaultClassLoader()); }
ConfigurationParser() throws IOException, SAXException, JAXBException, ParserConfigurationException { serviceCreationConfigurationParser = ConfigurationParser.<CacheManagerServiceConfigurationParser<?>>stream( servicesOfType(CacheManagerServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheManagerServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceCreationConfigurationParser::new)); serviceConfigurationParser = ConfigurationParser.<CacheServiceConfigurationParser<?>>stream( servicesOfType(CacheServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceConfigurationParser::new)); resourceConfigurationParser = stream(servicesOfType(CacheResourceConfigurationParser.class)) .flatMap(p -> p.getResourceTypes().stream().map(t -> new AbstractMap.SimpleImmutableEntry<>(t, p))) .collect(collectingAndThen(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a.getClass().isInstance(b) ? b : a), m -> new ResourceConfigurationParser(new HashSet<>(m.values())))); schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream())); documentBuilder = documentBuilder(schema); }
/** * Constructs an instance of XmlConfiguration mapping to the XML file located at {@code url}. * <p> * The default ClassLoader will first try to use the thread context class loader, followed by the ClassLoader that * loaded the Ehcache classes. * * @param url URL pointing to the XML file's location * * @throws XmlConfigurationException if anything went wrong parsing the XML */ public XmlConfiguration(URL url) throws XmlConfigurationException { this(url, ClassLoading.getDefaultClassLoader()); }
@Override public void start(BundleContext context) throws Exception { BundleContext currentContext = CORE_BUNDLE.getAndUpdate(current -> current == null ? context : current); if (currentContext == null) { String greeting = "Detected OSGi Environment (core is in bundle: " + context.getBundle() + ")"; if ("false".equalsIgnoreCase(context.getProperty(OSGI_LOADING))) { SafeOsgi.disableOSGiServiceLoading(); LOGGER.info(greeting + ": OSGi Based Service Loading Disabled Via System/Framework Property - Extensions Outside This Bundle Will Not Be Detected"); LOGGER.debug("JDK Service Loading Sees:\n\t" + stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false) .map(sf -> sf.getServiceType().getName()).collect(joining("\n\t"))); } else { SafeOsgi.enableOSGiServiceLoading(); LOGGER.info(greeting + ": Using OSGi Based Service Loading"); } } else { throw new IllegalStateException("Multiple bundle instances running against the same core classes: existing bundle: " + currentContext.getBundle() + " new bundle: " + context.getBundle()); } }
/** * Creates a new configuration with the specified {@link CacheConfiguration cache configurations}, class loader and * {@link org.ehcache.spi.service.ServiceConfiguration service configurations}. * * @param caches a map from alias to cache configuration * @param classLoader the class loader to use for user types * @param services an array of service configurations */ public DefaultConfiguration(Map<String, CacheConfiguration<?, ?>> caches, ClassLoader classLoader, ServiceCreationConfiguration<?>... services) { this.services = unmodifiableCollection(Arrays.asList(services)); this.caches = new ConcurrentHashMap<>(caches); this.classLoader = classLoader == null ? ClassLoading.getDefaultClassLoader() : classLoader; }
/** * Ensures the {@link ClusteringCacheManagerServiceConfigurationParser} is locatable as a * {@link CacheManagerServiceConfigurationParser} instance. */ @Test public void testServiceLocator() throws Exception { assertThat(stream(spliterator(ClassLoading.servicesOfType(CacheManagerServiceConfigurationParser.class).iterator(), Long.MAX_VALUE, 0), false).map(Object::getClass).collect(Collectors.toList()), hasItem(ClusteringCacheManagerServiceConfigurationParser.class)); }
public EhcacheManager(Configuration config, UnaryOperator<ServiceLocator.DependencySet> customization, boolean useLoaderInAtomics) { final String simpleName = this.getClass().getSimpleName(); this.simpleName = (simpleName.isEmpty() ? this.getClass().getName() : simpleName); this.configuration = new DefaultConfiguration(config); this.cacheManagerClassLoader = config.getClassLoader() != null ? config.getClassLoader() : ClassLoading.getDefaultClassLoader(); this.useLoaderInAtomics = useLoaderInAtomics; validateServicesConfigs(); this.serviceLocator = resolveServices(customization); }
@Test public void testServiceLocator() throws Exception { assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(Object::getClass).collect(Collectors.toList()), hasItem(ClusteringServiceFactory.class)); } }
@Override public final ClassLoader getClassLoader() { ClassLoader classLoader = cacheBinding.getCache().getRuntimeConfiguration().getClassLoader(); return classLoader == null ? ClassLoading.getDefaultClassLoader() : classLoader; }
@Test public void testNonClustered() throws Exception { /* * Ensure the cluster provider classes are loadable through the ServiceLoader mechanism. */ assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(f -> f.getServiceType()).collect(Collectors.toList()), hasItems(ClusteredStore.Provider.class, ClusteringService.class)); CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .build()) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); cacheManager.createCache("cache-1", cacheConfiguration); cacheManager.createCache("cache-2", cacheConfiguration); cacheManager.close(); } }
@Test public void testDefaultClassLoader() throws Exception { String resource = getClass().getName().replace('.', '/').concat(".class"); ClassLoader thisLoader = getClass().getClassLoader(); ClassLoader defaultClassLoader = ClassLoading.getDefaultClassLoader(); Thread.currentThread().setContextClassLoader(null); assertSame(thisLoader.loadClass(getClass().getName()), defaultClassLoader.loadClass(getClass().getName())); assertEquals(thisLoader.getResource(resource), defaultClassLoader.getResource(resource)); assertThat(list(defaultClassLoader.getResources(resource)), is(list(thisLoader.getResources(resource)))); Thread.currentThread().setContextClassLoader(new FindNothingLoader()); assertSame(thisLoader.loadClass(getClass().getName()), defaultClassLoader.loadClass(getClass().getName())); assertEquals(thisLoader.getResource(resource), defaultClassLoader.getResource(resource)); assertThat(list(defaultClassLoader.getResources(resource)), is(list(thisLoader.getResources(resource)))); URL url = new URL("file:///tmp"); ClassLoader tc = new TestClassLoader(url); Thread.currentThread().setContextClassLoader(tc); Class<?> c = defaultClassLoader.loadClass(getClass().getName()); assertNotSame(getClass(), c); assertSame(tc, c.getClassLoader()); assertEquals(url, defaultClassLoader.getResource(resource)); assertThat(list(defaultClassLoader.getResources(resource)), contains(url, thisLoader.getResource(resource))); }
@Test public void testNonXA() throws Exception { /* * Ensure the XA provider classes are loadable through the ServiceLoader mechanism. */ assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(s -> s.getServiceType()).collect(toList()), hasItems(XAStore.Provider.class, TransactionManagerProvider.class)); CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .build()) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); cacheManager.createCache("cache-1", cacheConfiguration); cacheManager.createCache("cache-2", cacheConfiguration); cacheManager.close(); } }
cacheClassLoader = classLoader; } else { cacheClassLoader = ClassLoading.getDefaultClassLoader();
@Test public void testNoClassLoaderSpecified() { Map<String, CacheConfiguration<?, ?>> caches = newCacheMap(); caches.put("foo", new BaseCacheConfiguration<>(Object.class, Object.class, null, null, null, ResourcePoolsHelper.createHeapOnlyPools())); DefaultConfiguration config = new DefaultConfiguration(caches, null); final Store.Provider storeProvider = mock(Store.Provider.class); when(storeProvider.rank(any(Set.class), any(Collection.class))).thenReturn(1); final Store mock = mock(Store.class); final CacheEventDispatcherFactory cenlProvider = mock(CacheEventDispatcherFactory.class); final CacheEventDispatcher<Object, Object> cenlServiceMock = mock(CacheEventDispatcher.class); when(cenlProvider.createCacheEventDispatcher(mock)).thenReturn(cenlServiceMock); final Collection<Service> services = getServices(storeProvider, cenlProvider); when(storeProvider .createStore(ArgumentMatchers.<Store.Configuration>any(), ArgumentMatchers.<ServiceConfiguration[]>any())).thenReturn(mock); EhcacheManager cacheManager = new EhcacheManager(config, services); cacheManager.init(); assertSame(ClassLoading.getDefaultClassLoader(), cacheManager.getClassLoader()); assertSame(cacheManager.getClassLoader(), cacheManager.getCache("foo", Object.class, Object.class).getRuntimeConfiguration().getClassLoader()); }
@Test public void testNoClassLoaderSpecified() throws Exception { URL resource = XmlConfigurationTest.class.getResource("/configs/one-cache.xml"); XmlConfiguration config = new XmlConfiguration(new XmlConfiguration(resource)); assertSame(config.getClassLoader(), ClassLoading.getDefaultClassLoader()); assertNull(config.getCacheConfigurations().get("bar").getClassLoader()); }
@Test public void unparseServiceConfigurationWithInstance() { TestSerializer3<Integer> testSerializer3 = new TestSerializer3<>(ClassLoading.getDefaultClassLoader()); TestSerializer4<Integer> testSerializer4 = new TestSerializer4<>(ClassLoading.getDefaultClassLoader()); DefaultSerializerConfiguration<Integer> config1 = new DefaultSerializerConfiguration<>(testSerializer3, DefaultSerializerConfiguration.Type.KEY); DefaultSerializerConfiguration<Integer> config2 = new DefaultSerializerConfiguration<>(testSerializer4, DefaultSerializerConfiguration.Type.VALUE); CacheConfiguration<?, ?> cacheConfig = newCacheConfigurationBuilder(Description.class, Person.class, heap(10)) .add(config1).add(config2).build(); CacheType cacheType = new CacheType(); CacheEntryType keyType = new CacheEntryType(); keyType.setValue("foo"); cacheType.setKeyType(keyType); CacheEntryType valueType = new CacheEntryType(); valueType.setValue("bar"); cacheType.setValueType(valueType); assertThatExceptionOfType(XmlConfigurationException.class).isThrownBy(() -> new DefaultSerializerConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType)) .withMessage("%s", "XML translation for instance based initialization for " + "DefaultSerializerConfiguration is not supported"); } }