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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Function;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Maps;
14 import com.google.common.collect.Sets;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Date;
21 import java.util.HashMap;
22 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.Node;
32 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * Creates a module dependency graph from provided {@link ModuleBuilder}s and
38 * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
39 * returns modules in order in which they should be processed (e.g. if A imports
40 * B, sort returns {B, A}).
42 public final class ModuleDependencySort {
44 private static final Date DEFAULT_REVISION = new Date(0);
45 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
48 * It is not desirable to instance this class
50 private ModuleDependencySort() {
54 * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
56 private static final Function<Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<Node, ModuleBuilder>() {
58 public ModuleBuilder apply(final Node input) {
59 // Cast to ModuleBuilder from Node and return
60 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
65 * Topological sort of module builder dependency graph.
67 * @return Sorted list of Module builders. Modules can be further processed
70 public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
71 List<Node> sorted = sortInternal(Arrays.asList(builders));
72 return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
75 public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
76 ModuleBuilder[] array = new ModuleBuilder[builders.size()];
77 builders.toArray(array);
81 public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
82 List<Object> modules = new ArrayList<Object>();
83 Collections.addAll(modules, builders);
84 modules.addAll(context.getModules());
86 List<Node> sorted = sortInternal(modules);
87 // Cast to ModuleBuilder from Node if possible and return
88 return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
91 public ModuleBuilder apply(final Node input) {
92 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
93 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
102 * Topological sort of module dependency graph.
104 * @return Sorted list of Modules. Modules can be further processed in
107 public static List<Module> sort(final Module... modules) {
108 List<Node> sorted = sortInternal(Arrays.asList(modules));
109 // Cast to Module from Node and return
110 return Lists.transform(sorted, new Function<Node, Module>() {
113 public Module apply(final Node input) {
114 return (Module) ((ModuleNodeImpl) input).getReference();
119 private static List<Node> sortInternal(final List<?> modules) {
120 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
122 Set<Node> nodes = Sets.newHashSet();
123 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
124 for (ModuleNodeImpl node : map.values()) {
129 return TopologicalSort.sort(nodes);
133 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final List<?> builders) {
134 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
136 processModules(moduleGraph, builders);
137 processDependencies(moduleGraph, builders);
143 * Extract module:revision from module builders
145 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
146 Map<URI, Object> allNS = new HashMap<>();
148 // Create edges in graph
149 for (Object mb : builders) {
150 Map<String, Date> imported = Maps.newHashMap();
152 String fromName = null;
153 Date fromRevision = null;
154 Set<ModuleImport> imports = null;
157 if (mb instanceof Module) {
158 fromName = ((Module) mb).getName();
159 fromRevision = ((Module) mb).getRevision();
160 imports = ((Module) mb).getImports();
161 ns = ((Module)mb).getNamespace();
162 } else if (mb instanceof ModuleBuilder) {
163 fromName = ((ModuleBuilder) mb).getName();
164 fromRevision = ((ModuleBuilder) mb).getRevision();
165 imports = ((ModuleBuilder) mb).getModuleImports();
166 ns = ((ModuleBuilder)mb).getNamespace();
169 // check for existence of module with same namespace
170 if (allNS.containsKey(ns)) {
171 Object mod = allNS.get(ns);
173 Date revision = null;
174 if (mod instanceof Module) {
175 name = ((Module) mod).getName();
176 revision = ((Module) mod).getRevision();
177 } else if (mod instanceof ModuleBuilder) {
178 name = ((ModuleBuilder) mod).getName();
179 revision = ((ModuleBuilder) mod).getRevision();
181 if (!(fromName.equals(name))) {
183 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
184 fromName, fromRevision, ns, name, revision);
190 // no need to check if other Type of object, check is performed in
193 if (fromRevision == null) {
194 fromRevision = DEFAULT_REVISION;
197 for (ModuleImport imprt : imports) {
198 String toName = imprt.getModuleName();
199 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
201 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
203 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
206 * Check imports: If module is imported twice with different
207 * revisions then throw exception
209 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
210 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
211 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
212 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
215 imported.put(toName, toRevision);
223 * Get imported module by its name and revision from moduleGraph
225 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
226 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
227 ModuleNodeImpl to = null;
229 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
230 // If revision is not specified in import, but module exists
231 // with different revisions, take first
232 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
233 && toRevision.equals(DEFAULT_REVISION)) {
234 to = moduleGraph.get(toName).values().iterator().next();
236 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
237 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
238 formatRevDate(to.getRevision())));
240 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
241 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
242 LOGGER.warn("Available models: {}", moduleGraph);
243 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
244 fromName, formatRevDate(fromRevision)));
247 to = moduleGraph.get(toName).get(toRevision);
252 private static void ex(final String message) {
253 throw new YangValidationException(message);
257 * Extract dependencies from module builders or modules to fill dependency
260 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
263 for (Object mb : builders) {
268 if (mb instanceof Module) {
269 name = ((Module) mb).getName();
270 rev = ((Module) mb).getRevision();
271 } else if (mb instanceof ModuleBuilder) {
272 name = ((ModuleBuilder) mb).getName();
273 rev = ((ModuleBuilder) mb).getRevision();
275 throw new IllegalStateException(String.format(
276 "Unexpected type of node for sort, expected only:%s, %s, got:%s", Module.class,
277 ModuleBuilder.class, mb.getClass()));
281 rev = DEFAULT_REVISION;
284 if (moduleGraph.get(name) == null) {
285 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
288 if (moduleGraph.get(name).get(rev) != null) {
289 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
292 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
296 private static String formatRevDate(final Date rev) {
297 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
301 static class ModuleNodeImpl extends NodeImpl {
302 private final String name;
303 private final Date revision;
304 private final Object originalObject;
306 public ModuleNodeImpl(final String name, final Date revision, final Object builder) {
308 this.revision = revision;
309 this.originalObject = builder;
312 public String getName() {
316 public Date getRevision() {
321 public int hashCode() {
322 final int prime = 31;
324 result = prime * result + ((name == null) ? 0 : name.hashCode());
325 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
330 public boolean equals(final Object obj) {
337 if (getClass() != obj.getClass()) {
340 ModuleNodeImpl other = (ModuleNodeImpl) obj;
342 if (other.name != null) {
345 } else if (!name.equals(other.name)) {
348 if (revision == null) {
349 if (other.revision != null) {
352 } else if (!revision.equals(other.revision)) {
359 public String toString() {
360 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
363 public Object getReference() {
364 return originalObject;