Cleaned up Java Binding code from YANG Tools
[mdsal.git] / binding / mdsal-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 java.io.IOException;
14 import java.io.InputStream;
15 import java.lang.ref.WeakReference;
16 import java.util.Set;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
20 import org.opendaylight.yangtools.concepts.ObjectRegistration;
21 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
22 import org.opendaylight.yangtools.sal.binding.generator.api.ModuleInfoRegistry;
23 import org.opendaylight.yangtools.util.ClassLoaderUtils;
24 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
25 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
26 import org.opendaylight.yangtools.yang.model.api.Module;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
29 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
30 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy //
35         implements //
36         ModuleInfoRegistry, SchemaContextProvider {
37
38     private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
39         this.backingLoadingStrategy = loadingStrategy;
40     }
41
42     public static ModuleInfoBackedContext create() {
43         return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
44     }
45
46     public static ModuleInfoBackedContext create(final ClassLoadingStrategy 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 ClassLoadingStrategy backingLoadingStrategy;
56
57     @Override
58     public Class<?> loadClass(final 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
80     private synchronized Optional<SchemaContext> recreateSchemaContext() {
81         try {
82             ImmutableList<InputStream> streams = getAvailableStreams();
83             YangParserImpl parser = new YangParserImpl();
84             Set<Module> modules = parser.parseYangModelsFromStreams(streams);
85             SchemaContext schemaContext = parser.resolveSchemaContext(modules);
86             return Optional.of(schemaContext);
87         } catch (IOException e) {
88             LOG.error("Schema was not recreated.",e);
89         }
90         return Optional.absent();
91     }
92
93     // TODO finish schema parsing and expose as SchemaService
94     // Unite with current SchemaService
95     // Implement remove ModuleInfo to update SchemaContext
96
97     public synchronized Optional<SchemaContext> tryToCreateSchemaContext() {
98         return recreateSchemaContext();
99     }
100
101     private ImmutableList<InputStream> getAvailableStreams() throws IOException {
102         ImmutableSet<YangModuleInfo> moduleInfos = ImmutableSet.copyOf(sourceIdentifierToModuleInfo.values());
103
104         ImmutableList.Builder<InputStream> sourceStreams = ImmutableList.<InputStream> builder();
105         for (YangModuleInfo moduleInfo : moduleInfos) {
106             sourceStreams.add(moduleInfo.getModuleSourceStream());
107         }
108         return sourceStreams.build();
109     }
110
111     private boolean resolveModuleInfo(final Class<?> cls) {
112         try {
113             return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
114         } catch (Exception e) {
115             throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
116         }
117     }
118
119     private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
120
121         SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
122         YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
123         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
124         if (previous == null) {
125             String modulePackageName = moduleInfo.getClass().getPackage().getName();
126             packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<ClassLoader>(moduleClassLoader));
127
128             for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
129                 resolveModuleInfo(importedInfo);
130             }
131         } else {
132             return false;
133         }
134         return true;
135     }
136
137     private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
138         return SourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
139     }
140
141     public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
142         for (YangModuleInfo yangModuleInfo : moduleInfos) {
143             registerModuleInfo(yangModuleInfo);
144         }
145     }
146
147     @Override
148     public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
149         YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
150
151         resolveModuleInfo(yangModuleInfo);
152
153         return registration;
154     }
155
156     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
157
158         private final ModuleInfoBackedContext context;
159
160         public YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
161             super(instance);
162             this.context = context;
163         }
164
165         @Override
166         protected void removeRegistration() {
167             context.remove(this);
168         }
169
170     }
171
172     private void remove(final YangModuleInfoRegistration registration) {
173         // FIXME implement
174     }
175
176     @Override
177     public SchemaContext getSchemaContext() {
178         final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
179         if (contextOptional.isPresent()) {
180             return contextOptional.get();
181
182         }
183         throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");
184     }
185 }