2 * Copyright (c) 2013 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.yang.parser.util;
10 import static java.util.Arrays.asList;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Function;
14 import com.google.common.base.Optional;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Sets;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.List;
27 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
28 import org.opendaylight.yangtools.yang.model.api.Module;
29 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
31 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
32 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
33 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * Creates a module dependency graph from provided {@link ModuleBuilder}s and
39 * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
40 * returns modules in order in which they should be processed (e.g. if A imports
41 * B, sort returns {B, A}).
43 public final class ModuleDependencySort {
45 private static final Date DEFAULT_REVISION = SimpleDateFormatUtil.DEFAULT_DATE_REV;
46 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
47 private static final Function<Node, Module> TOPOLOGY_FUNCTION = new Function<TopologicalSort.Node, Module>() {
49 public Module apply(final TopologicalSort.Node input) {
53 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
54 return moduleOrModuleBuilder.getModule();
59 * It is not desirable to instance this class
61 private ModuleDependencySort() {
66 * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
68 private static final Function<TopologicalSort.Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<TopologicalSort.Node, ModuleBuilder>() {
70 public ModuleBuilder apply(final TopologicalSort.Node input) {
71 // Cast to ModuleBuilder from Node and return
75 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
76 return moduleOrModuleBuilder.getModuleBuilder();
81 * Topological sort of module builder dependency graph.
83 * @param builders builders of Module object
84 * @return Sorted list of Module builders. Modules can be further processed
87 public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
88 return sort(asList(builders));
91 public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
92 List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(
93 Collections.<Module>emptySet(),builders));
94 return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
97 public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
98 List<ModuleOrModuleBuilder> all = ModuleOrModuleBuilder.fromAll(context.getModules(), asList(builders));
100 List<TopologicalSort.Node> sorted = sortInternal(all);
101 // Cast to ModuleBuilder from Node if possible and return
102 return Lists.transform(sorted, new Function<TopologicalSort.Node, ModuleBuilder>() {
105 public ModuleBuilder apply(final TopologicalSort.Node input) {
109 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
110 if (moduleOrModuleBuilder.isModuleBuilder()) {
111 return moduleOrModuleBuilder.getModuleBuilder();
120 * Topological sort of module dependency graph.
122 * @param modules YANG modules
123 * @return Sorted list of Modules. Modules can be further processed in
126 public static List<Module> sort(final Module... modules) {
127 List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(asList(modules),
128 Collections.<ModuleBuilder>emptyList()));
129 // Cast to Module from Node and return
130 return Lists.transform(sorted, TOPOLOGY_FUNCTION);
133 private static List<TopologicalSort.Node> sortInternal(final Iterable<ModuleOrModuleBuilder> modules) {
134 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
136 Set<TopologicalSort.Node> nodes = Sets.newHashSet();
137 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
138 for (ModuleNodeImpl node : map.values()) {
143 return TopologicalSort.sort(nodes);
147 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<ModuleOrModuleBuilder> builders) {
148 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
150 processModules(moduleGraph, builders);
151 processDependencies(moduleGraph, builders);
157 * Extract module:revision from module builders
159 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
160 final Iterable<ModuleOrModuleBuilder> mmbs) {
161 Map<URI, ModuleOrModuleBuilder> allNS = new HashMap<>();
163 // Create edges in graph
164 for (ModuleOrModuleBuilder mmb : mmbs) {
165 Map<String, Date> imported = Maps.newHashMap();
169 Collection<ModuleImport> imports;
172 if (mmb.isModule()) {
173 Module module = mmb.getModule();
174 fromName = module.getName();
175 fromRevision = module.getRevision();
176 imports = module.getImports();
177 ns = module.getNamespace();
179 ModuleBuilder moduleBuilder = mmb.getModuleBuilder();
180 fromName = moduleBuilder.getName();
181 fromRevision = moduleBuilder.getRevision();
182 imports = moduleBuilder.getImports().values();
183 ns = moduleBuilder.getNamespace();
186 // check for existence of module with same namespace
187 if (allNS.containsKey(ns)) {
188 ModuleOrModuleBuilder mod = allNS.get(ns);
190 Date revision = null;
191 if (mod.isModule()) {
192 name = mod.getModule().getName();
193 revision = mod.getModule().getRevision();
194 } else if (mod.isModuleBuilder()) {
195 name = mod.getModuleBuilder().getName();
196 revision = mod.getModuleBuilder().getRevision();
198 if (!(fromName.equals(name))) {
200 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
201 fromName, fromRevision, ns, name, revision);
207 // no need to check if other Type of object, check is performed in
210 if (fromRevision == null) {
211 fromRevision = DEFAULT_REVISION;
214 for (ModuleImport imprt : imports) {
215 String toName = imprt.getModuleName();
216 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
218 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
220 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
223 * Check imports: If module is imported twice with different
224 * revisions then throw exception
226 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
227 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
228 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
229 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
232 imported.put(toName, toRevision);
240 * Get imported module by its name and revision from moduleGraph
242 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
243 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
244 ModuleNodeImpl to = null;
246 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
247 // If revision is not specified in import, but module exists
248 // with different revisions, take first
249 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
250 && toRevision.equals(DEFAULT_REVISION)) {
251 to = moduleGraph.get(toName).values().iterator().next();
253 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
254 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
255 formatRevDate(to.getRevision())));
257 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
258 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
259 LOGGER.warn("Available models: {}", moduleGraph);
260 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
261 fromName, formatRevDate(fromRevision)));
264 to = moduleGraph.get(toName).get(toRevision);
269 private static void ex(final String message) {
270 throw new YangValidationException(message);
274 * Extract dependencies from module builders or modules to fill dependency
277 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
278 final Iterable<ModuleOrModuleBuilder> builders) {
281 for (ModuleOrModuleBuilder momb : builders) {
286 if (momb.isModule()) {
287 name = momb.getModule().getName();
288 rev = momb.getModule().getRevision();
290 name = momb.getModuleBuilder().getName();
291 rev = momb.getModuleBuilder().getRevision();
295 rev = DEFAULT_REVISION;
298 if (moduleGraph.get(name) == null) {
299 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
302 if (moduleGraph.get(name).get(rev) != null) {
303 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
306 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, momb));
310 private static String formatRevDate(final Date rev) {
311 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
315 static class ModuleNodeImpl extends NodeImpl {
316 private final String name;
317 private final Date revision;
318 private final ModuleOrModuleBuilder originalObject;
320 public ModuleNodeImpl(final String name, final Date revision, final ModuleOrModuleBuilder builder) {
322 this.revision = revision;
323 this.originalObject = builder;
326 public String getName() {
330 public Date getRevision() {
335 public int hashCode() {
336 final int prime = 31;
338 result = prime * result + ((name == null) ? 0 : name.hashCode());
339 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
344 public boolean equals(final Object obj) {
351 if (getClass() != obj.getClass()) {
354 ModuleNodeImpl other = (ModuleNodeImpl) obj;
356 if (other.name != null) {
359 } else if (!name.equals(other.name)) {
362 if (revision == null) {
363 if (other.revision != null) {
366 } else if (!revision.equals(other.revision)) {
373 public String toString() {
374 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
377 public ModuleOrModuleBuilder getReference() {
378 return originalObject;
384 class ModuleOrModuleBuilder {
385 private final Optional<Module> maybeModule;
386 private final Optional<ModuleBuilder> maybeModuleBuilder;
388 ModuleOrModuleBuilder(final Module module) {
389 maybeModule = Optional.of(module);
390 maybeModuleBuilder = Optional.absent();
393 ModuleOrModuleBuilder(final ModuleBuilder moduleBuilder) {
394 maybeModule = Optional.absent();
395 maybeModuleBuilder = Optional.of(moduleBuilder);
398 return maybeModule.isPresent();
400 boolean isModuleBuilder(){
401 return maybeModuleBuilder.isPresent();
404 return maybeModule.get();
406 ModuleBuilder getModuleBuilder(){
407 return maybeModuleBuilder.get();
410 static List<ModuleOrModuleBuilder> fromAll(final Collection<Module> modules, final Collection<ModuleBuilder> moduleBuilders) {
411 List<ModuleOrModuleBuilder> result = new ArrayList<>(modules.size() + moduleBuilders.size());
412 for(Module m: modules){
413 result.add(new ModuleOrModuleBuilder(m));
415 for (ModuleBuilder mb : moduleBuilders) {
416 result.add(new ModuleOrModuleBuilder(mb));