BUG-865: remove use of deprecated APIs
[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 com.google.common.io.ByteSource;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.lang.ref.WeakReference;
17 import java.util.Collection;
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.parser.api.YangSyntaxErrorException;
30 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
31 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
36         implements 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             Collection<ByteSource> streams = getAvailableStreams();
83             YangParserImpl parser = new YangParserImpl();
84             SchemaContext schemaContext = parser.parseSources(streams);
85             return Optional.of(schemaContext);
86         } catch (IOException | YangSyntaxErrorException e) {
87             LOG.error("Schema was not recreated.", e);
88         }
89         return Optional.absent();
90     }
91
92     // TODO finish schema parsing and expose as SchemaService
93     // Unite with current SchemaService
94     // Implement remove ModuleInfo to update SchemaContext
95
96     public synchronized Optional<SchemaContext> tryToCreateSchemaContext() {
97         return recreateSchemaContext();
98     }
99
100     private Collection<ByteSource> getAvailableStreams() throws IOException {
101         ImmutableSet<YangModuleInfo> moduleInfos = ImmutableSet.copyOf(sourceIdentifierToModuleInfo.values());
102
103         ImmutableList.Builder<ByteSource> sourceStreams = ImmutableList.<ByteSource> builder();
104         for (final YangModuleInfo moduleInfo : moduleInfos) {
105             sourceStreams.add(new ByteSource() {
106
107                 @Override
108                 public InputStream openStream() throws IOException {
109                     return moduleInfo.getModuleSourceStream();
110                 }
111             });
112             ;
113         }
114         return sourceStreams.build();
115     }
116
117     private boolean resolveModuleInfo(final Class<?> cls) {
118         try {
119             return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
120         } catch (Exception e) {
121             throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
122         }
123     }
124
125     private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
126
127         SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
128         YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
129         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
130         if (previous == null) {
131             String modulePackageName = moduleInfo.getClass().getPackage().getName();
132             packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<ClassLoader>(moduleClassLoader));
133
134             for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
135                 resolveModuleInfo(importedInfo);
136             }
137         } else {
138             return false;
139         }
140         return true;
141     }
142
143     private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
144         return SourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
145     }
146
147     public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
148         for (YangModuleInfo yangModuleInfo : moduleInfos) {
149             registerModuleInfo(yangModuleInfo);
150         }
151     }
152
153     @Override
154     public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
155         YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
156
157         resolveModuleInfo(yangModuleInfo);
158
159         return registration;
160     }
161
162     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
163
164         private final ModuleInfoBackedContext context;
165
166         public YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
167             super(instance);
168             this.context = context;
169         }
170
171         @Override
172         protected void removeRegistration() {
173             context.remove(this);
174         }
175
176     }
177
178     private void remove(final YangModuleInfoRegistration registration) {
179         // FIXME implement
180     }
181
182     @Override
183     public SchemaContext getSchemaContext() {
184         final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
185         if (contextOptional.isPresent()) {
186             return contextOptional.get();
187
188         }
189         throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");
190     }
191 }