2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
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 com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.Futures;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.lang.ref.WeakReference;
19 import java.util.Collection;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
23 import org.opendaylight.yangtools.concepts.ObjectRegistration;
24 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
25 import org.opendaylight.yangtools.sal.binding.generator.api.ModuleInfoRegistry;
26 import org.opendaylight.yangtools.util.ClassLoaderUtils;
27 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
28 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
32 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
33 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
34 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
36 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
37 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
38 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
43 implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider<YangTextSchemaSource> {
45 private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
46 this.backingLoadingStrategy = loadingStrategy;
49 public static ModuleInfoBackedContext create() {
50 return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
53 public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) {
54 return new ModuleInfoBackedContext(loadingStrategy);
57 private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
59 private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader = new ConcurrentHashMap<>();
60 private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo = new ConcurrentHashMap<>();
62 private final ClassLoadingStrategy backingLoadingStrategy;
65 public Class<?> loadClass(final String fullyQualifiedName) throws ClassNotFoundException {
66 String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName);
68 WeakReference<ClassLoader> classLoaderRef = packageNameToClassLoader.get(modulePackageName);
69 ClassLoader classloader = null;
70 if (classLoaderRef != null && (classloader = classLoaderRef.get()) != null) {
71 return ClassLoaderUtils.loadClass(classloader, fullyQualifiedName);
73 if (backingLoadingStrategy == null) {
74 throw new ClassNotFoundException(fullyQualifiedName);
76 Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
77 if (BindingReflections.isBindingClass(cls)) {
78 boolean newModule = resolveModuleInfo(cls);
80 recreateSchemaContext();
88 private synchronized Optional<SchemaContext> recreateSchemaContext() {
90 Collection<ByteSource> streams = getAvailableStreams();
91 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
93 SchemaContext schemaContext = reactor.buildEffective(streams);
94 return Optional.of(schemaContext);
95 } catch (IOException | SourceException | ReactorException e) {
96 LOG.error("Schema was not recreated.", e);
98 return Optional.absent();
101 // TODO finish schema parsing and expose as SchemaService
102 // Unite with current SchemaService
103 // Implement remove ModuleInfo to update SchemaContext
105 public synchronized Optional<SchemaContext> tryToCreateSchemaContext() {
106 return recreateSchemaContext();
109 private Collection<ByteSource> getAvailableStreams() throws IOException {
110 ImmutableSet<YangModuleInfo> moduleInfos = ImmutableSet.copyOf(sourceIdentifierToModuleInfo.values());
112 ImmutableList.Builder<ByteSource> sourceStreams = ImmutableList.<ByteSource> builder();
113 for (final YangModuleInfo moduleInfo : moduleInfos) {
114 sourceStreams.add(new ByteSource() {
117 public InputStream openStream() throws IOException {
118 return moduleInfo.getModuleSourceStream();
123 return sourceStreams.build();
126 private boolean resolveModuleInfo(final Class<?> cls) {
128 return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
129 } catch (Exception e) {
130 throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
134 private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
136 SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
137 YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
138 ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
139 if (previous == null) {
140 String modulePackageName = moduleInfo.getClass().getPackage().getName();
141 packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<ClassLoader>(moduleClassLoader));
143 for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
144 resolveModuleInfo(importedInfo);
152 private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
153 return SourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
156 public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
157 for (YangModuleInfo yangModuleInfo : moduleInfos) {
158 registerModuleInfo(yangModuleInfo);
163 public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
164 YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
166 resolveModuleInfo(yangModuleInfo);
171 @Override public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
172 final SourceIdentifier sourceIdentifier) {
173 final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
175 if (yangModuleInfo == null) {
176 LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier, sourceIdentifierToModuleInfo.keySet());
178 .immediateFailedCheckedFuture(new SchemaSourceException("Unknown schema source: " + sourceIdentifier));
182 .immediateCheckedFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier, new ByteSource() {
183 @Override public InputStream openStream() throws IOException {
184 return yangModuleInfo.getModuleSourceStream();
189 private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
191 private final ModuleInfoBackedContext context;
193 public YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
195 this.context = context;
199 protected void removeRegistration() {
200 context.remove(this);
205 private void remove(final YangModuleInfoRegistration registration) {
210 public SchemaContext getSchemaContext() {
211 final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
212 if (contextOptional.isPresent()) {
213 return contextOptional.get();
216 throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");