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