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