Bug 735 - Part 1: Update ietf-restconf and ietf-yangtypes to newer versions
[yangtools.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / 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.yangtools.sal.binding.generator.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.ImmutableSet;
13 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
14 import org.opendaylight.yangtools.concepts.ObjectRegistration;
15 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
16 import org.opendaylight.yangtools.sal.binding.generator.api.ModuleInfoRegistry;
17 import org.opendaylight.yangtools.sal.binding.generator.util.ClassLoaderUtils;
18 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
19 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
20 import org.opendaylight.yangtools.yang.model.api.Module;
21 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
22 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
23 import org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider;
24 import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
25 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.lang.ref.WeakReference;
32 import java.util.Set;
33 import java.util.concurrent.ConcurrentHashMap;
34 import java.util.concurrent.ConcurrentMap;
35
36 public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy //
37         implements //
38         AdvancedSchemaSourceProvider<InputStream>, ModuleInfoRegistry, SchemaContextProvider {
39
40     private ModuleInfoBackedContext(ClassLoadingStrategy loadingStrategy) {
41         this.backingLoadingStrategy = loadingStrategy;
42     }
43
44     public static ModuleInfoBackedContext create() {
45         return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
46     }
47
48     public static ModuleInfoBackedContext create(ClassLoadingStrategy loadingStrategy) {
49         return new ModuleInfoBackedContext(loadingStrategy);
50     }
51
52     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
53
54     private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader = new ConcurrentHashMap<>();
55     private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo = new ConcurrentHashMap<>();
56
57     private final ClassLoadingStrategy backingLoadingStrategy;
58
59     @Override
60     public Class<?> loadClass(String fullyQualifiedName) throws ClassNotFoundException {
61         String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName);
62
63         WeakReference<ClassLoader> classLoaderRef = packageNameToClassLoader.get(modulePackageName);
64         ClassLoader classloader = null;
65         if (classLoaderRef != null && (classloader = classLoaderRef.get()) != null) {
66             return ClassLoaderUtils.loadClass(classloader, fullyQualifiedName);
67         }
68         if (backingLoadingStrategy == null) {
69             throw new ClassNotFoundException(fullyQualifiedName);
70         }
71         Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
72         if (BindingReflections.isBindingClass(cls)) {
73             boolean newModule = resolveModuleInfo(cls);
74             if (newModule) {
75                 recreateSchemaContext();
76             }
77         }
78         return cls;
79     }
80
81
82     private synchronized Optional<SchemaContext> recreateSchemaContext() {
83         try {
84             ImmutableList<InputStream> streams = getAvailableStreams();
85             YangParserImpl parser = new YangParserImpl();
86             Set<Module> modules = parser.parseYangModelsFromStreams(streams);
87             SchemaContext schemaContext = parser.resolveSchemaContext(modules);
88             return Optional.of(schemaContext);
89         } catch (IOException e) {
90             LOG.error("Schema was not recreated.",e);
91         }
92         return Optional.absent();
93     }
94
95     // TODO finish schema parsing and expose as SchemaService
96     // Unite with current SchemaService
97     // Implement remove ModuleInfo to update SchemaContext
98
99     public synchronized Optional<SchemaContext> tryToCreateSchemaContext() {
100         return recreateSchemaContext();
101     }
102
103     private ImmutableList<InputStream> getAvailableStreams() throws IOException {
104         ImmutableSet<YangModuleInfo> moduleInfos = ImmutableSet.copyOf(sourceIdentifierToModuleInfo.values());
105
106         ImmutableList.Builder<InputStream> sourceStreams = ImmutableList.<InputStream> builder();
107         for (YangModuleInfo moduleInfo : moduleInfos) {
108             sourceStreams.add(moduleInfo.getModuleSourceStream());
109         }
110         return sourceStreams.build();
111     }
112
113     private boolean resolveModuleInfo(Class<?> cls) {
114         try {
115             return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
116         } catch (Exception e) {
117             throw new IllegalStateException(e);
118         }
119     }
120
121     private boolean resolveModuleInfo(YangModuleInfo moduleInfo) {
122
123         SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
124         YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
125         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
126         if (previous == null) {
127             String modulePackageName = moduleInfo.getClass().getPackage().getName();
128             packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<ClassLoader>(moduleClassLoader));
129
130             for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
131                 resolveModuleInfo(importedInfo);
132             }
133         } else {
134             return false;
135         }
136         return true;
137     }
138
139     private SourceIdentifier sourceIdentifierFrom(YangModuleInfo moduleInfo) {
140         return SourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
141     }
142
143     public void addModuleInfos(Iterable<? extends YangModuleInfo> moduleInfos) {
144         for (YangModuleInfo yangModuleInfo : moduleInfos) {
145             registerModuleInfo(yangModuleInfo);
146         }
147     }
148
149     @Override
150     public ObjectRegistration<YangModuleInfo> registerModuleInfo(YangModuleInfo yangModuleInfo) {
151         YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
152
153         resolveModuleInfo(yangModuleInfo);
154
155         return registration;
156     }
157
158     @Override
159     public Optional<InputStream> getSchemaSource(SourceIdentifier sourceIdentifier) {
160         YangModuleInfo info = sourceIdentifierToModuleInfo.get(sourceIdentifier);
161         if (info == null) {
162             return Optional.absent();
163         }
164         try {
165             return Optional.of(info.getModuleSourceStream());
166         } catch (IOException e) {
167             return Optional.absent();
168         }
169     }
170
171     @Override
172     public Optional<InputStream> getSchemaSource(String moduleName, Optional<String> revision) {
173         return getSchemaSource(SourceIdentifier.create(moduleName, revision));
174     }
175
176     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
177
178         private final ModuleInfoBackedContext context;
179
180         public YangModuleInfoRegistration(YangModuleInfo instance, ModuleInfoBackedContext context) {
181             super(instance);
182             this.context = context;
183         }
184
185         @Override
186         protected void removeRegistration() {
187             context.remove(this);
188         }
189
190     }
191
192     private void remove(YangModuleInfoRegistration registration) {
193         // FIXME implement
194     }
195
196     @Override
197     public SchemaContext getSchemaContext() {
198         return tryToCreateSchemaContext().get();
199     }
200 }