2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5 * and is available at http://www.eclipse.org/legal/epl-v10.html
7 package org.opendaylight.yangtools.yang.parser.util;
9 import static java.util.Arrays.asList;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Sets;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.List;
26 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
27 import org.opendaylight.yangtools.yang.model.api.Module;
28 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
31 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
36 * Creates a module dependency graph from provided {@link ModuleBuilder}s and
37 * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
38 * returns modules in order in which they should be processed (e.g. if A imports
39 * B, sort returns {B, A}).
41 public final class ModuleDependencySort {
43 private static final Date DEFAULT_REVISION = new Date(0);
44 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
47 * It is not desirable to instance this class
49 private ModuleDependencySort() {
54 * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
56 private static final Function<TopologicalSort.Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<TopologicalSort.Node, ModuleBuilder>() {
58 public ModuleBuilder apply(final TopologicalSort.Node input) {
59 // Cast to ModuleBuilder from Node and return
60 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
61 return moduleOrModuleBuilder.getModuleBuilder();
66 * Topological sort of module builder dependency graph.
68 * @return Sorted list of Module builders. Modules can be further processed
71 public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
72 return sort(asList(builders));
75 public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
76 List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(
77 Collections.<Module>emptySet(),builders));
78 return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
81 public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
82 List<ModuleOrModuleBuilder> all = ModuleOrModuleBuilder.fromAll(context.getModules(), asList(builders));
84 List<TopologicalSort.Node> sorted = sortInternal(all);
85 // Cast to ModuleBuilder from Node if possible and return
86 return Lists.transform(sorted, new Function<TopologicalSort.Node, ModuleBuilder>() {
89 public ModuleBuilder apply(final TopologicalSort.Node input) {
90 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
91 if (moduleOrModuleBuilder.isModuleBuilder()) {
92 return moduleOrModuleBuilder.getModuleBuilder();
101 * Topological sort of module dependency graph.
103 * @return Sorted list of Modules. Modules can be further processed in
106 public static List<Module> sort(final Module... modules) {
107 List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(asList(modules),
108 Collections.<ModuleBuilder>emptyList()));
109 // Cast to Module from Node and return
110 return Lists.transform(sorted, new Function<TopologicalSort.Node, Module>() {
113 public Module apply(final TopologicalSort.Node input) {
114 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
115 return moduleOrModuleBuilder.getModule();
120 private static List<TopologicalSort.Node> sortInternal(final Iterable<ModuleOrModuleBuilder> modules) {
121 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
123 Set<TopologicalSort.Node> nodes = Sets.newHashSet();
124 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
125 for (ModuleNodeImpl node : map.values()) {
130 return TopologicalSort.sort(nodes);
134 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<ModuleOrModuleBuilder> builders) {
135 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
137 processModules(moduleGraph, builders);
138 processDependencies(moduleGraph, builders);
144 * Extract module:revision from module builders
146 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
147 final Iterable<ModuleOrModuleBuilder> mmbs) {
148 Map<URI, Object> allNS = new HashMap<>();
150 // Create edges in graph
151 for (ModuleOrModuleBuilder mmb : mmbs) {
152 Map<String, Date> imported = Maps.newHashMap();
156 Set<ModuleImport> imports;
159 if (mmb.isModule()) {
160 Module module = mmb.getModule();
161 fromName = module.getName();
162 fromRevision = module.getRevision();
163 imports = module.getImports();
164 ns = module.getNamespace();
166 ModuleBuilder moduleBuilder = mmb.getModuleBuilder();
167 fromName = moduleBuilder.getName();
168 fromRevision = moduleBuilder.getRevision();
169 imports = moduleBuilder.getModuleImports();
170 ns = moduleBuilder.getNamespace();
173 // check for existence of module with same namespace
174 if (allNS.containsKey(ns)) {
175 Object mod = allNS.get(ns);
177 Date revision = null;
178 if (mod instanceof Module) {
179 name = ((Module) mod).getName();
180 revision = ((Module) mod).getRevision();
181 } else if (mod instanceof ModuleBuilder) {
182 name = ((ModuleBuilder) mod).getName();
183 revision = ((ModuleBuilder) mod).getRevision();
185 if (!(fromName.equals(name))) {
187 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
188 fromName, fromRevision, ns, name, revision);
194 // no need to check if other Type of object, check is performed in
197 if (fromRevision == null) {
198 fromRevision = DEFAULT_REVISION;
201 for (ModuleImport imprt : imports) {
202 String toName = imprt.getModuleName();
203 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
205 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
207 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
210 * Check imports: If module is imported twice with different
211 * revisions then throw exception
213 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
214 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
215 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
216 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
219 imported.put(toName, toRevision);
227 * Get imported module by its name and revision from moduleGraph
229 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
230 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
231 ModuleNodeImpl to = null;
233 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
234 // If revision is not specified in import, but module exists
235 // with different revisions, take first
236 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
237 && toRevision.equals(DEFAULT_REVISION)) {
238 to = moduleGraph.get(toName).values().iterator().next();
240 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
241 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
242 formatRevDate(to.getRevision())));
244 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
245 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
246 LOGGER.warn("Available models: {}", moduleGraph);
247 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
248 fromName, formatRevDate(fromRevision)));
251 to = moduleGraph.get(toName).get(toRevision);
256 private static void ex(final String message) {
257 throw new YangValidationException(message);
261 * Extract dependencies from module builders or modules to fill dependency
264 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
265 final Iterable<ModuleOrModuleBuilder> builders) {
268 for (ModuleOrModuleBuilder momb : builders) {
273 if (momb.isModule()) {
274 name = momb.getModule().getName();
275 rev = momb.getModule().getRevision();
277 name = momb.getModuleBuilder().getName();
278 rev = momb.getModuleBuilder().getRevision();
282 rev = DEFAULT_REVISION;
285 if (moduleGraph.get(name) == null) {
286 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
289 if (moduleGraph.get(name).get(rev) != null) {
290 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
293 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, momb));
297 private static String formatRevDate(final Date rev) {
298 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
302 static class ModuleNodeImpl extends NodeImpl {
303 private final String name;
304 private final Date revision;
305 private final ModuleOrModuleBuilder originalObject;
307 public ModuleNodeImpl(final String name, final Date revision, final ModuleOrModuleBuilder builder) {
309 this.revision = revision;
310 this.originalObject = builder;
313 public String getName() {
317 public Date getRevision() {
322 public int hashCode() {
323 final int prime = 31;
325 result = prime * result + ((name == null) ? 0 : name.hashCode());
326 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
331 public boolean equals(final Object obj) {
338 if (getClass() != obj.getClass()) {
341 ModuleNodeImpl other = (ModuleNodeImpl) obj;
343 if (other.name != null) {
346 } else if (!name.equals(other.name)) {
349 if (revision == null) {
350 if (other.revision != null) {
353 } else if (!revision.equals(other.revision)) {
360 public String toString() {
361 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
364 public ModuleOrModuleBuilder getReference() {
365 return originalObject;
371 class ModuleOrModuleBuilder {
372 private final Optional<Module> maybeModule;
373 private final Optional<ModuleBuilder> maybeModuleBuilder;
375 ModuleOrModuleBuilder(Module module) {
376 maybeModule = Optional.of(module);
377 maybeModuleBuilder = Optional.absent();
380 ModuleOrModuleBuilder(ModuleBuilder moduleBuilder) {
381 maybeModule = Optional.absent();
382 maybeModuleBuilder = Optional.of(moduleBuilder);
385 return maybeModule.isPresent();
387 boolean isModuleBuilder(){
388 return maybeModuleBuilder.isPresent();
391 return maybeModule.get();
393 ModuleBuilder getModuleBuilder(){
394 return maybeModuleBuilder.get();
397 static List<ModuleOrModuleBuilder> fromAll(Collection<Module> modules, Collection<ModuleBuilder> moduleBuilders) {
398 List<ModuleOrModuleBuilder> result = new ArrayList<>(modules.size() + moduleBuilders.size());
399 for(Module m: modules){
400 result.add(new ModuleOrModuleBuilder(m));
402 for (ModuleBuilder mb : moduleBuilders) {
403 result.add(new ModuleOrModuleBuilder(mb));