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> {
44 private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
46 private static final LoadingCache<ClassLoadingStrategy,
47 LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>> CONTEXT_CACHES = CacheBuilder.newBuilder()
48 .weakKeys().build(new CacheLoader<ClassLoadingStrategy,
49 LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>>() {
51 public LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext> load(
52 final ClassLoadingStrategy strategy) {
53 return CacheBuilder.newBuilder().weakValues().build(
54 new CacheLoader<Set<YangModuleInfo>, ModuleInfoBackedContext>() {
56 public ModuleInfoBackedContext load(final Set<YangModuleInfo> key) {
57 final ModuleInfoBackedContext context = ModuleInfoBackedContext.create(strategy);
58 context.addModuleInfos(key);
65 private final YangTextSchemaContextResolver ctxResolver = YangTextSchemaContextResolver.create("binding-context");
66 private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader =
67 new ConcurrentHashMap<>();
68 private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo =
69 new ConcurrentHashMap<>();
70 private final ClassLoadingStrategy backingLoadingStrategy;
72 private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
73 this.backingLoadingStrategy = loadingStrategy;
77 public static ModuleInfoBackedContext cacheContext(final ClassLoadingStrategy loadingStrategy,
78 final ImmutableSet<YangModuleInfo> infos) {
79 return CONTEXT_CACHES.getUnchecked(loadingStrategy).getUnchecked(infos);
82 public static ModuleInfoBackedContext create() {
83 return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
86 public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) {
87 return new ModuleInfoBackedContext(loadingStrategy);
91 public SchemaContext getSchemaContext() {
92 final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
93 if (contextOptional.isPresent()) {
94 return contextOptional.get();
97 throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");
101 public Class<?> loadClass(final String fullyQualifiedName) throws ClassNotFoundException {
102 final String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName);
103 final WeakReference<ClassLoader> classLoaderRef = packageNameToClassLoader.get(modulePackageName);
104 if (classLoaderRef != null) {
105 final ClassLoader classLoader = classLoaderRef.get();
106 if (classLoader != null) {
107 return ClassLoaderUtils.loadClass(classLoader, fullyQualifiedName);
111 if (backingLoadingStrategy == null) {
112 throw new ClassNotFoundException(fullyQualifiedName);
115 final Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
116 if (BindingReflections.isBindingClass(cls)) {
117 resolveModuleInfo(cls);
124 public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
125 YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
126 resolveModuleInfo(yangModuleInfo);
131 public ListenableFuture<? extends YangTextSchemaSource> getSource(
132 final SourceIdentifier sourceIdentifier) {
133 final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
135 if (yangModuleInfo == null) {
136 LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier,
137 sourceIdentifierToModuleInfo.keySet());
138 return Futures.immediateFailedFuture(new SchemaSourceException(
139 "Unknown schema source: " + sourceIdentifier));
142 return Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
143 yangModuleInfo.getYangTextByteSource()));
146 public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
147 for (YangModuleInfo yangModuleInfo : moduleInfos) {
148 registerModuleInfo(yangModuleInfo);
152 // TODO finish schema parsing and expose as SchemaService
153 // Unite with current SchemaService
154 // Implement remove ModuleInfo to update SchemaContext
156 public Optional<SchemaContext> tryToCreateSchemaContext() {
157 return ctxResolver.getSchemaContext();
160 @SuppressWarnings("checkstyle:illegalCatch")
161 private boolean resolveModuleInfo(final Class<?> cls) {
163 return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
164 } catch (Exception e) {
165 throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
169 @SuppressWarnings("checkstyle:illegalCatch")
170 @SuppressFBWarnings("REC_CATCH_EXCEPTION")
171 private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
172 final SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
173 final YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
174 if (previous != null) {
178 ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
180 String modulePackageName = moduleInfo.getClass().getPackage().getName();
181 packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<>(moduleClassLoader));
182 ctxResolver.registerSource(toYangTextSource(identifier, moduleInfo));
183 for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
184 resolveModuleInfo(importedInfo);
186 } catch (Exception e) {
187 LOG.error("Not including {} in YANG sources because of error.", moduleInfo, e);
192 private void remove(final YangModuleInfoRegistration registration) {
196 private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier,
197 final YangModuleInfo moduleInfo) {
198 return YangTextSchemaSource.delegateForByteSource(identifier, moduleInfo.getYangTextByteSource());
201 private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
202 final QName name = moduleInfo.getName();
203 return RevisionSourceIdentifier.create(name.getLocalName(), name.getRevision());
206 private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
207 private final ModuleInfoBackedContext context;
209 YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
211 this.context = context;
215 protected void removeRegistration() {
216 context.remove(this);