Reorganize ModuleInfoBackedContext
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / impl / ModuleInfoBackedContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.generator.impl;
9
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;
20 import java.util.Set;
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;
41
42 public final class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
43         implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider<YangTextSchemaSource> {
44     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
45
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>>() {
50                     @Override
51                     public LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext> load(
52                             final ClassLoadingStrategy strategy) {
53                         return CacheBuilder.newBuilder().weakValues().build(
54                             new CacheLoader<Set<YangModuleInfo>, ModuleInfoBackedContext>() {
55                                 @Override
56                                 public ModuleInfoBackedContext load(final Set<YangModuleInfo> key) {
57                                     final ModuleInfoBackedContext context = ModuleInfoBackedContext.create(strategy);
58                                     context.addModuleInfos(key);
59                                     return context;
60                                 }
61                             });
62                     }
63             });
64
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;
71
72     private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
73         this.backingLoadingStrategy = loadingStrategy;
74     }
75
76     @Beta
77     public static ModuleInfoBackedContext cacheContext(final ClassLoadingStrategy loadingStrategy,
78             final ImmutableSet<YangModuleInfo> infos) {
79         return CONTEXT_CACHES.getUnchecked(loadingStrategy).getUnchecked(infos);
80     }
81
82     public static ModuleInfoBackedContext create() {
83         return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
84     }
85
86     public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) {
87         return new ModuleInfoBackedContext(loadingStrategy);
88     }
89
90     @Override
91     public SchemaContext getSchemaContext() {
92         final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
93         if (contextOptional.isPresent()) {
94             return contextOptional.get();
95
96         }
97         throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");
98     }
99
100     @Override
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);
108             }
109         }
110
111         if (backingLoadingStrategy == null) {
112             throw new ClassNotFoundException(fullyQualifiedName);
113         }
114
115         final Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
116         if (BindingReflections.isBindingClass(cls)) {
117             resolveModuleInfo(cls);
118         }
119
120         return cls;
121     }
122
123     @Override
124     public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
125         YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
126         resolveModuleInfo(yangModuleInfo);
127         return registration;
128     }
129
130     @Override
131     public ListenableFuture<? extends YangTextSchemaSource> getSource(
132         final SourceIdentifier sourceIdentifier) {
133         final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
134
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));
140         }
141
142         return Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
143             yangModuleInfo.getYangTextByteSource()));
144     }
145
146     public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
147         for (YangModuleInfo yangModuleInfo : moduleInfos) {
148             registerModuleInfo(yangModuleInfo);
149         }
150     }
151
152     // TODO finish schema parsing and expose as SchemaService
153     // Unite with current SchemaService
154     // Implement remove ModuleInfo to update SchemaContext
155
156     public Optional<SchemaContext> tryToCreateSchemaContext() {
157         return ctxResolver.getSchemaContext();
158     }
159
160     @SuppressWarnings("checkstyle:illegalCatch")
161     private boolean resolveModuleInfo(final Class<?> cls) {
162         try {
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);
166         }
167     }
168
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) {
175             return false;
176         }
177
178         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
179         try {
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);
185             }
186         } catch (Exception e) {
187             LOG.error("Not including {} in YANG sources because of error.", moduleInfo, e);
188         }
189         return true;
190     }
191
192     private void remove(final YangModuleInfoRegistration registration) {
193         // FIXME implement
194     }
195
196     private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier,
197             final YangModuleInfo moduleInfo) {
198         return YangTextSchemaSource.delegateForByteSource(identifier, moduleInfo.getYangTextByteSource());
199     }
200
201     private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
202         final QName name = moduleInfo.getName();
203         return RevisionSourceIdentifier.create(name.getLocalName(), name.getRevision());
204     }
205
206     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
207         private final ModuleInfoBackedContext context;
208
209         YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
210             super(instance);
211             this.context = context;
212         }
213
214         @Override
215         protected void removeRegistration() {
216             context.remove(this);
217         }
218     }
219 }