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