2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.generator.impl;
10 import com.google.common.annotations.Beta;
11 import com.google.common.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
18 import java.lang.ref.WeakReference;
19 import java.util.Optional;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
24 import org.opendaylight.mdsal.binding.generator.api.ModuleInfoRegistry;
25 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
26 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
27 import org.opendaylight.yangtools.concepts.ObjectRegistration;
28 import org.opendaylight.yangtools.util.ClassLoaderUtils;
29 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
33 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
37 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
38 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public final class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
43 implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider<YangTextSchemaSource> {
45 private static final LoadingCache<ClassLoadingStrategy,
46 LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>> CONTEXT_CACHES = CacheBuilder.newBuilder()
47 .weakKeys().build(new CacheLoader<ClassLoadingStrategy,
48 LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>>() {
50 public LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext> load(
51 final ClassLoadingStrategy strategy) {
52 return CacheBuilder.newBuilder().weakValues().build(
53 new CacheLoader<Set<YangModuleInfo>, ModuleInfoBackedContext>() {
55 public ModuleInfoBackedContext load(final Set<YangModuleInfo> key) {
56 final ModuleInfoBackedContext context = ModuleInfoBackedContext.create(strategy);
57 context.addModuleInfos(key);
64 private final YangTextSchemaContextResolver ctxResolver = YangTextSchemaContextResolver.create("binding-context");
66 private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
67 this.backingLoadingStrategy = loadingStrategy;
71 public static ModuleInfoBackedContext cacheContext(final ClassLoadingStrategy loadingStrategy,
72 final ImmutableSet<YangModuleInfo> infos) {
73 return CONTEXT_CACHES.getUnchecked(loadingStrategy).getUnchecked(infos);
76 public static ModuleInfoBackedContext create() {
77 return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
80 public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) {
81 return new ModuleInfoBackedContext(loadingStrategy);
84 private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
86 private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader =
87 new ConcurrentHashMap<>();
88 private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo =
89 new ConcurrentHashMap<>();
91 private final ClassLoadingStrategy backingLoadingStrategy;
94 public Class<?> loadClass(final String fullyQualifiedName) throws ClassNotFoundException {
95 final String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName);
96 final WeakReference<ClassLoader> classLoaderRef = packageNameToClassLoader.get(modulePackageName);
97 if (classLoaderRef != null) {
98 final ClassLoader classLoader = classLoaderRef.get();
99 if (classLoader != null) {
100 return ClassLoaderUtils.loadClass(classLoader, fullyQualifiedName);
104 if (backingLoadingStrategy == null) {
105 throw new ClassNotFoundException(fullyQualifiedName);
108 final Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
109 if (BindingReflections.isBindingClass(cls)) {
110 resolveModuleInfo(cls);
116 // TODO finish schema parsing and expose as SchemaService
117 // Unite with current SchemaService
118 // Implement remove ModuleInfo to update SchemaContext
120 public Optional<SchemaContext> tryToCreateSchemaContext() {
121 return ctxResolver.getSchemaContext();
124 @SuppressWarnings("checkstyle:illegalCatch")
125 private boolean resolveModuleInfo(final Class<?> cls) {
127 return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
128 } catch (Exception e) {
129 throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
133 @SuppressWarnings("checkstyle:illegalCatch")
134 @SuppressFBWarnings("REC_CATCH_EXCEPTION")
135 private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
136 final SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
137 final YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
138 if (previous != null) {
142 ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
144 String modulePackageName = moduleInfo.getClass().getPackage().getName();
145 packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<>(moduleClassLoader));
146 ctxResolver.registerSource(toYangTextSource(identifier, moduleInfo));
147 for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
148 resolveModuleInfo(importedInfo);
150 } catch (Exception e) {
151 LOG.error("Not including {} in YANG sources because of error.", moduleInfo, e);
156 private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier,
157 final YangModuleInfo moduleInfo) {
158 return YangTextSchemaSource.delegateForByteSource(identifier, moduleInfo.getYangTextByteSource());
161 private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
162 final QName name = moduleInfo.getName();
163 return RevisionSourceIdentifier.create(name.getLocalName(), name.getRevision());
166 public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
167 for (YangModuleInfo yangModuleInfo : moduleInfos) {
168 registerModuleInfo(yangModuleInfo);
173 public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
174 YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
175 resolveModuleInfo(yangModuleInfo);
180 public ListenableFuture<? extends YangTextSchemaSource> getSource(
181 final SourceIdentifier sourceIdentifier) {
182 final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
184 if (yangModuleInfo == null) {
185 LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier,
186 sourceIdentifierToModuleInfo.keySet());
187 return Futures.immediateFailedFuture(new SchemaSourceException(
188 "Unknown schema source: " + sourceIdentifier));
191 return Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
192 yangModuleInfo.getYangTextByteSource()));
195 private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
197 private final ModuleInfoBackedContext context;
199 YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
201 this.context = context;
205 protected void removeRegistration() {
206 context.remove(this);
211 private void remove(final YangModuleInfoRegistration registration) {
216 public SchemaContext getSchemaContext() {
217 final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
218 if (contextOptional.isPresent()) {
219 return contextOptional.get();
222 throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");