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