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;
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;
28 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
29 import org.opendaylight.yangtools.yang.model.api.Module;
30 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
33 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
34 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * Creates a module dependency graph from provided {@link ModuleBuilder}s and
40 * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
41 * returns modules in order in which they should be processed (e.g. if A imports
42 * B, sort returns {B, A}).
44 public final class ModuleDependencySort {
46 private static final Date DEFAULT_REVISION = new Date(0);
47 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
48 private static final Function<Node, Module> TOPOLOGY_FUNCTION = new Function<TopologicalSort.Node, Module>() {
50 public Module apply(final TopologicalSort.Node input) {
51 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
52 return moduleOrModuleBuilder.getModule();
57 * It is not desirable to instance this class
59 private ModuleDependencySort() {
64 * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
66 private static final Function<TopologicalSort.Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<TopologicalSort.Node, ModuleBuilder>() {
68 public ModuleBuilder apply(final TopologicalSort.Node input) {
69 // Cast to ModuleBuilder from Node and return
70 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
71 return moduleOrModuleBuilder.getModuleBuilder();
76 * Topological sort of module builder dependency graph.
78 * @return Sorted list of Module builders. Modules can be further processed
81 public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
82 return sort(asList(builders));
85 public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
86 List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(
87 Collections.<Module>emptySet(),builders));
88 return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
91 public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
92 List<ModuleOrModuleBuilder> all = ModuleOrModuleBuilder.fromAll(context.getModules(), asList(builders));
94 List<TopologicalSort.Node> sorted = sortInternal(all);
95 // Cast to ModuleBuilder from Node if possible and return
96 return Lists.transform(sorted, new Function<TopologicalSort.Node, ModuleBuilder>() {
99 public ModuleBuilder apply(final TopologicalSort.Node input) {
100 ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
101 if (moduleOrModuleBuilder.isModuleBuilder()) {
102 return moduleOrModuleBuilder.getModuleBuilder();
111 * Topological sort of module dependency graph.
113 * @return Sorted list of Modules. Modules can be further processed in
116 public static List<Module> sort(final Module... modules) {
117 List<TopologicalSort.Node> sorted = sortInternal(ModuleOrModuleBuilder.fromAll(asList(modules),
118 Collections.<ModuleBuilder>emptyList()));
119 // Cast to Module from Node and return
120 return Lists.transform(sorted, TOPOLOGY_FUNCTION);
123 private static List<TopologicalSort.Node> sortInternal(final Iterable<ModuleOrModuleBuilder> modules) {
124 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
126 Set<TopologicalSort.Node> nodes = Sets.newHashSet();
127 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
128 for (ModuleNodeImpl node : map.values()) {
133 return TopologicalSort.sort(nodes);
137 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<ModuleOrModuleBuilder> builders) {
138 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
140 processModules(moduleGraph, builders);
141 processDependencies(moduleGraph, builders);
147 * Extract module:revision from module builders
149 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
150 final Iterable<ModuleOrModuleBuilder> mmbs) {
151 Map<URI, Object> allNS = new HashMap<>();
153 // Create edges in graph
154 for (ModuleOrModuleBuilder mmb : mmbs) {
155 Map<String, Date> imported = Maps.newHashMap();
159 Collection<ModuleImport> imports;
162 if (mmb.isModule()) {
163 Module module = mmb.getModule();
164 fromName = module.getName();
165 fromRevision = module.getRevision();
166 imports = module.getImports();
167 ns = module.getNamespace();
169 ModuleBuilder moduleBuilder = mmb.getModuleBuilder();
170 fromName = moduleBuilder.getName();
171 fromRevision = moduleBuilder.getRevision();
172 imports = moduleBuilder.getImports().values();
173 ns = moduleBuilder.getNamespace();
176 // check for existence of module with same namespace
177 if (allNS.containsKey(ns)) {
178 Object mod = allNS.get(ns);
180 Date revision = null;
181 if (mod instanceof Module) {
182 name = ((Module) mod).getName();
183 revision = ((Module) mod).getRevision();
184 } else if (mod instanceof ModuleBuilder) {
185 name = ((ModuleBuilder) mod).getName();
186 revision = ((ModuleBuilder) mod).getRevision();
188 if (!(fromName.equals(name))) {
190 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
191 fromName, fromRevision, ns, name, revision);
197 // no need to check if other Type of object, check is performed in
200 if (fromRevision == null) {
201 fromRevision = DEFAULT_REVISION;
204 for (ModuleImport imprt : imports) {
205 String toName = imprt.getModuleName();
206 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
208 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
210 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
213 * Check imports: If module is imported twice with different
214 * revisions then throw exception
216 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
217 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
218 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
219 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
222 imported.put(toName, toRevision);
230 * Get imported module by its name and revision from moduleGraph
232 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
233 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
234 ModuleNodeImpl to = null;
236 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
237 // If revision is not specified in import, but module exists
238 // with different revisions, take first
239 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
240 && toRevision.equals(DEFAULT_REVISION)) {
241 to = moduleGraph.get(toName).values().iterator().next();
243 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
244 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
245 formatRevDate(to.getRevision())));
247 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
248 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
249 LOGGER.warn("Available models: {}", moduleGraph);
250 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
251 fromName, formatRevDate(fromRevision)));
254 to = moduleGraph.get(toName).get(toRevision);
259 private static void ex(final String message) {
260 throw new YangValidationException(message);
264 * Extract dependencies from module builders or modules to fill dependency
267 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
268 final Iterable<ModuleOrModuleBuilder> builders) {
271 for (ModuleOrModuleBuilder momb : builders) {
276 if (momb.isModule()) {
277 name = momb.getModule().getName();
278 rev = momb.getModule().getRevision();
280 name = momb.getModuleBuilder().getName();
281 rev = momb.getModuleBuilder().getRevision();
285 rev = DEFAULT_REVISION;
288 if (moduleGraph.get(name) == null) {
289 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
292 if (moduleGraph.get(name).get(rev) != null) {
293 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
296 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, momb));
300 private static String formatRevDate(final Date rev) {
301 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
305 static class ModuleNodeImpl extends NodeImpl {
306 private final String name;
307 private final Date revision;
308 private final ModuleOrModuleBuilder originalObject;
310 public ModuleNodeImpl(final String name, final Date revision, final ModuleOrModuleBuilder builder) {
312 this.revision = revision;
313 this.originalObject = builder;
316 public String getName() {
320 public Date getRevision() {
325 public int hashCode() {
326 final int prime = 31;
328 result = prime * result + ((name == null) ? 0 : name.hashCode());
329 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
334 public boolean equals(final Object obj) {
341 if (getClass() != obj.getClass()) {
344 ModuleNodeImpl other = (ModuleNodeImpl) obj;
346 if (other.name != null) {
349 } else if (!name.equals(other.name)) {
352 if (revision == null) {
353 if (other.revision != null) {
356 } else if (!revision.equals(other.revision)) {
363 public String toString() {
364 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
367 public ModuleOrModuleBuilder getReference() {
368 return originalObject;
374 class ModuleOrModuleBuilder {
375 private final Optional<Module> maybeModule;
376 private final Optional<ModuleBuilder> maybeModuleBuilder;
378 ModuleOrModuleBuilder(final Module module) {
379 maybeModule = Optional.of(module);
380 maybeModuleBuilder = Optional.absent();
383 ModuleOrModuleBuilder(final ModuleBuilder moduleBuilder) {
384 maybeModule = Optional.absent();
385 maybeModuleBuilder = Optional.of(moduleBuilder);
388 return maybeModule.isPresent();
390 boolean isModuleBuilder(){
391 return maybeModuleBuilder.isPresent();
394 return maybeModule.get();
396 ModuleBuilder getModuleBuilder(){
397 return maybeModuleBuilder.get();
400 static List<ModuleOrModuleBuilder> fromAll(final Collection<Module> modules, final Collection<ModuleBuilder> moduleBuilders) {
401 List<ModuleOrModuleBuilder> result = new ArrayList<>(modules.size() + moduleBuilders.size());
402 for(Module m: modules){
403 result.add(new ModuleOrModuleBuilder(m));
405 for (ModuleBuilder mb : moduleBuilders) {
406 result.add(new ModuleOrModuleBuilder(mb));