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;
11 import java.text.SimpleDateFormat;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.Date;
17 import java.util.HashMap;
18 import java.util.List;
22 import org.opendaylight.yangtools.yang.model.api.Module;
23 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
24 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
25 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
26 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
27 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Function;
33 import com.google.common.collect.Lists;
34 import com.google.common.collect.Maps;
35 import com.google.common.collect.Sets;
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 = new Date(0);
46 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
49 * It is not desirable to instance this class
51 private ModuleDependencySort() {
55 * Topological sort of module builder dependency graph.
57 * @return Sorted list of Module builders. Modules can be further processed
60 public static List<ModuleBuilder> sort(ModuleBuilder... builders) {
61 List<Node> sorted = sortInternal(Arrays.asList(builders));
62 // Cast to ModuleBuilder from Node and return
63 return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
66 public ModuleBuilder apply(Node input) {
67 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
72 public static List<ModuleBuilder> sort(Collection<ModuleBuilder> builders) {
73 ModuleBuilder[] array = new ModuleBuilder[builders.size()];
74 builders.toArray(array);
78 public static List<ModuleBuilder> sortWithContext(SchemaContext context, ModuleBuilder... builders) {
79 List<Object> modules = new ArrayList<Object>();
80 Collections.addAll(modules, builders);
81 modules.addAll(context.getModules());
83 List<Node> sorted = sortInternal(modules);
84 // Cast to ModuleBuilder from Node if possible and return
85 return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
88 public ModuleBuilder apply(Node input) {
89 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
90 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
99 * Topological sort of module dependency graph.
101 * @return Sorted list of Modules. Modules can be further processed in
104 public static List<Module> sort(Module... modules) {
105 List<Node> sorted = sortInternal(Arrays.asList(modules));
106 // Cast to Module from Node and return
107 return Lists.transform(sorted, new Function<Node, Module>() {
110 public Module apply(Node input) {
111 return (Module) ((ModuleNodeImpl) input).getReference();
116 private static List<Node> sortInternal(List<?> modules) {
117 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
119 Set<Node> nodes = Sets.newHashSet();
120 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
121 for (ModuleNodeImpl node : map.values()) {
126 return TopologicalSort.sort(nodes);
130 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(List<?> builders) {
131 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
133 processModules(moduleGraph, builders);
134 processDependencies(moduleGraph, builders);
140 * Extract module:revision from module builders
142 private static void processDependencies(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
143 Map<URI, Object> allNS = new HashMap<>();
145 // Create edges in graph
146 for (Object mb : builders) {
147 Map<String, Date> imported = Maps.newHashMap();
149 String fromName = null;
150 Date fromRevision = null;
151 Set<ModuleImport> imports = null;
154 if (mb instanceof Module) {
155 fromName = ((Module) mb).getName();
156 fromRevision = ((Module) mb).getRevision();
157 imports = ((Module) mb).getImports();
158 ns = ((Module)mb).getNamespace();
159 } else if (mb instanceof ModuleBuilder) {
160 fromName = ((ModuleBuilder) mb).getName();
161 fromRevision = ((ModuleBuilder) mb).getRevision();
162 imports = ((ModuleBuilder) mb).getModuleImports();
163 ns = ((ModuleBuilder)mb).getNamespace();
166 // check for existence of module with same namespace
167 if (allNS.containsKey(ns)) {
168 Object mod = allNS.get(ns);
170 Date revision = null;
171 if (mod instanceof Module) {
172 name = ((Module) mod).getName();
173 revision = ((Module) mod).getRevision();
174 } else if (mod instanceof ModuleBuilder) {
175 name = ((ModuleBuilder) mod).getName();
176 revision = ((ModuleBuilder) mod).getRevision();
178 if (!(fromName.equals(name))) {
180 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
181 fromName, fromRevision, ns, name, revision);
187 // no need to check if other Type of object, check is performed in
190 if (fromRevision == null) {
191 fromRevision = DEFAULT_REVISION;
194 for (ModuleImport imprt : imports) {
195 String toName = imprt.getModuleName();
196 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
198 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
200 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
203 * Check imports: If module is imported twice with different
204 * revisions then throw exception
206 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
207 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
208 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
209 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
212 imported.put(toName, toRevision);
220 * Get imported module by its name and revision from moduleGraph
222 private static ModuleNodeImpl getModuleByNameAndRevision(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
223 String fromName, Date fromRevision, String toName, Date toRevision) {
224 ModuleNodeImpl to = null;
226 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
227 // If revision is not specified in import, but module exists
228 // with different revisions, take first
229 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
230 && toRevision.equals(DEFAULT_REVISION)) {
231 to = moduleGraph.get(toName).values().iterator().next();
233 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
234 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
235 formatRevDate(to.getRevision())));
237 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
238 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
239 LOGGER.warn("Available models: {}", moduleGraph);
240 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
241 fromName, formatRevDate(fromRevision)));
244 to = moduleGraph.get(toName).get(toRevision);
249 private static void ex(String message) {
250 throw new YangValidationException(message);
254 * Extract dependencies from module builders or modules to fill dependency
257 private static void processModules(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
260 for (Object mb : builders) {
265 if (mb instanceof Module) {
266 name = ((Module) mb).getName();
267 rev = ((Module) mb).getRevision();
268 } else if (mb instanceof ModuleBuilder) {
269 name = ((ModuleBuilder) mb).getName();
270 rev = ((ModuleBuilder) mb).getRevision();
272 throw new IllegalStateException(String.format(
273 "Unexpected type of node for sort, expected only:%s, %s, got:%s", Module.class,
274 ModuleBuilder.class, mb.getClass()));
278 rev = DEFAULT_REVISION;
281 if (moduleGraph.get(name) == null) {
282 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
285 if (moduleGraph.get(name).get(rev) != null) {
286 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
289 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
293 private static String formatRevDate(Date rev) {
294 return rev.equals(DEFAULT_REVISION) ? "default" : new SimpleDateFormat("yyyy-MM-dd").format(rev);
298 static class ModuleNodeImpl extends NodeImpl {
299 private final String name;
300 private final Date revision;
301 private final Object originalObject;
303 public ModuleNodeImpl(String name, Date revision, Object builder) {
305 this.revision = revision;
306 this.originalObject = builder;
309 public String getName() {
313 public Date getRevision() {
318 public int hashCode() {
319 final int prime = 31;
321 result = prime * result + ((name == null) ? 0 : name.hashCode());
322 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
327 public boolean equals(Object obj) {
334 if (getClass() != obj.getClass()) {
337 ModuleNodeImpl other = (ModuleNodeImpl) obj;
339 if (other.name != null) {
342 } else if (!name.equals(other.name)) {
345 if (revision == null) {
346 if (other.revision != null) {
349 } else if (!revision.equals(other.revision)) {
356 public String toString() {
357 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
360 public Object getReference() {
361 return originalObject;