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 java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Collections;
13 import java.util.Date;
14 import java.util.List;
18 import org.opendaylight.yangtools.yang.model.api.Module;
19 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
20 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
21 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
22 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
23 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
24 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
28 import com.google.common.annotations.VisibleForTesting;
29 import com.google.common.base.Function;
30 import com.google.common.collect.Lists;
31 import com.google.common.collect.Maps;
32 import com.google.common.collect.Sets;
35 * Creates a module dependency graph from provided {@link ModuleBuilder}s and
36 * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
37 * returns modules in order in which they should be processed (e.g. if A imports
38 * B, sort returns {B, A}).
40 public final class ModuleDependencySort {
42 private static final Date DEFAULT_REVISION = new Date(0);
43 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
46 * It is not desirable to instance this class
48 private ModuleDependencySort() {
52 * Topological sort of module builder dependency graph.
54 * @return Sorted list of Module builders. Modules can be further processed
57 public static List<ModuleBuilder> sort(ModuleBuilder... builders) {
58 List<Node> sorted = sortInternal(Arrays.asList(builders));
59 // Cast to ModuleBuilder from Node and return
60 return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
63 public ModuleBuilder apply(Node input) {
64 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
69 public static List<ModuleBuilder> sortWithContext(SchemaContext context, ModuleBuilder... builders) {
70 List<Object> modules = new ArrayList<Object>();
71 Collections.addAll(modules, builders);
72 modules.addAll(context.getModules());
74 List<Node> sorted = sortInternal(modules);
75 // Cast to ModuleBuilder from Node if possible and return
76 return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
79 public ModuleBuilder apply(Node input) {
80 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
81 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
90 * Topological sort of module dependency graph.
92 * @return Sorted list of Modules. Modules can be further processed in
95 public static List<Module> sort(Module... modules) {
96 List<Node> sorted = sortInternal(Arrays.asList(modules));
97 // Cast to Module from Node and return
98 return Lists.transform(sorted, new Function<Node, Module>() {
101 public Module apply(Node input) {
102 return (Module) ((ModuleNodeImpl) input).getReference();
107 private static List<Node> sortInternal(List<?> modules) {
108 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
110 Set<Node> nodes = Sets.newHashSet();
111 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
112 for (ModuleNodeImpl node : map.values()) {
117 return TopologicalSort.sort(nodes);
121 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(List<?> builders) {
122 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
124 processModules(moduleGraph, builders);
125 processDependencies(moduleGraph, builders);
131 * Extract module:revision from module builders
133 private static void processDependencies(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
134 Map<String, Date> imported = Maps.newHashMap();
136 // Create edges in graph
137 for (Object mb : builders) {
139 String fromName = null;
140 Date fromRevision = null;
141 Set<ModuleImport> imports = null;
143 if (mb instanceof Module) {
144 fromName = ((Module) mb).getName();
145 fromRevision = ((Module) mb).getRevision();
146 imports = ((Module) mb).getImports();
147 } else if (mb instanceof ModuleBuilder) {
148 fromName = ((ModuleBuilder) mb).getName();
149 fromRevision = ((ModuleBuilder) mb).getRevision();
150 imports = ((ModuleBuilder) mb).getModuleImports();
152 // no need to check if other Type of object, check is performed in
155 if (fromRevision == null) {
156 fromRevision = DEFAULT_REVISION;
159 for (ModuleImport imprt : imports) {
160 String toName = imprt.getModuleName();
161 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
163 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
165 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
168 * Check imports: If module is imported twice with different
169 * revisions then throw exception
171 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
172 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
173 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
174 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
177 imported.put(toName, toRevision);
185 * Get imported module by its name and revision from moduleGraph
187 private static ModuleNodeImpl getModuleByNameAndRevision(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
188 String fromName, Date fromRevision, String toName, Date toRevision) {
189 ModuleNodeImpl to = null;
191 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
192 // If revision is not specified in import, but module exists
193 // with different revisions, take first
194 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
195 && toRevision.equals(DEFAULT_REVISION)) {
196 to = moduleGraph.get(toName).values().iterator().next();
198 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
199 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
200 formatRevDate(to.getRevision())));
202 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
203 fromName, formatRevDate(fromRevision)));
206 to = moduleGraph.get(toName).get(toRevision);
211 private static void ex(String message) {
212 throw new YangValidationException(message);
216 * Extract dependencies from module builders or modules to fill dependency
219 private static void processModules(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
222 for (Object mb : builders) {
227 if (mb instanceof Module) {
228 name = ((Module) mb).getName();
229 rev = ((Module) mb).getRevision();
230 } else if (mb instanceof ModuleBuilder) {
231 name = ((ModuleBuilder) mb).getName();
232 rev = ((ModuleBuilder) mb).getRevision();
234 throw new IllegalStateException(String.format(
235 "Unexpected type of node for sort, expected only:%s, %s, got:%s", Module.class,
236 ModuleBuilder.class, mb.getClass()));
240 rev = DEFAULT_REVISION;
243 if (moduleGraph.get(name) == null) {
244 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
247 if (moduleGraph.get(name).get(rev) != null) {
248 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
251 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
255 private static String formatRevDate(Date rev) {
256 return rev.equals(DEFAULT_REVISION) ? "default" : YangParserListenerImpl.SIMPLE_DATE_FORMAT.format(rev);
260 static class ModuleNodeImpl extends NodeImpl {
261 private final String name;
262 private final Date revision;
263 private final Object originalObject;
265 public ModuleNodeImpl(String name, Date revision, Object builder) {
267 this.revision = revision;
268 this.originalObject = builder;
271 public String getName() {
275 public Date getRevision() {
280 public int hashCode() {
281 final int prime = 31;
283 result = prime * result + ((name == null) ? 0 : name.hashCode());
284 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
289 public boolean equals(Object obj) {
296 if (getClass() != obj.getClass()) {
299 ModuleNodeImpl other = (ModuleNodeImpl) obj;
301 if (other.name != null) {
304 } else if (!name.equals(other.name)) {
307 if (revision == null) {
308 if (other.revision != null) {
311 } else if (!revision.equals(other.revision)) {
318 public String toString() {
319 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
322 public Object getReference() {
323 return originalObject;