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.util.ArrayList;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.Date;
16 import java.util.HashMap;
17 import java.util.List;
21 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
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 * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
57 private static final Function<Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<Node, ModuleBuilder>() {
59 public ModuleBuilder apply(final Node input) {
60 // Cast to ModuleBuilder from Node and return
61 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
66 * Topological sort of module builder dependency graph.
68 * @return Sorted list of Module builders. Modules can be further processed
71 public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
72 List<Node> sorted = sortInternal(Arrays.asList(builders));
73 return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
76 public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
77 ModuleBuilder[] array = new ModuleBuilder[builders.size()];
78 builders.toArray(array);
82 public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
83 List<Object> modules = new ArrayList<Object>();
84 Collections.addAll(modules, builders);
85 modules.addAll(context.getModules());
87 List<Node> sorted = sortInternal(modules);
88 // Cast to ModuleBuilder from Node if possible and return
89 return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
92 public ModuleBuilder apply(final Node input) {
93 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
94 return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
103 * Topological sort of module dependency graph.
105 * @return Sorted list of Modules. Modules can be further processed in
108 public static List<Module> sort(final Module... modules) {
109 List<Node> sorted = sortInternal(Arrays.asList(modules));
110 // Cast to Module from Node and return
111 return Lists.transform(sorted, new Function<Node, Module>() {
114 public Module apply(final Node input) {
115 return (Module) ((ModuleNodeImpl) input).getReference();
120 private static List<Node> sortInternal(final List<?> modules) {
121 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
123 Set<Node> nodes = Sets.newHashSet();
124 for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
125 for (ModuleNodeImpl node : map.values()) {
130 return TopologicalSort.sort(nodes);
134 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final List<?> builders) {
135 Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
137 processModules(moduleGraph, builders);
138 processDependencies(moduleGraph, builders);
144 * Extract module:revision from module builders
146 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
147 Map<URI, Object> allNS = new HashMap<>();
149 // Create edges in graph
150 for (Object mb : builders) {
151 Map<String, Date> imported = Maps.newHashMap();
153 String fromName = null;
154 Date fromRevision = null;
155 Set<ModuleImport> imports = null;
158 if (mb instanceof Module) {
159 fromName = ((Module) mb).getName();
160 fromRevision = ((Module) mb).getRevision();
161 imports = ((Module) mb).getImports();
162 ns = ((Module)mb).getNamespace();
163 } else if (mb instanceof ModuleBuilder) {
164 fromName = ((ModuleBuilder) mb).getName();
165 fromRevision = ((ModuleBuilder) mb).getRevision();
166 imports = ((ModuleBuilder) mb).getModuleImports();
167 ns = ((ModuleBuilder)mb).getNamespace();
170 // check for existence of module with same namespace
171 if (allNS.containsKey(ns)) {
172 Object mod = allNS.get(ns);
174 Date revision = null;
175 if (mod instanceof Module) {
176 name = ((Module) mod).getName();
177 revision = ((Module) mod).getRevision();
178 } else if (mod instanceof ModuleBuilder) {
179 name = ((ModuleBuilder) mod).getName();
180 revision = ((ModuleBuilder) mod).getRevision();
182 if (!(fromName.equals(name))) {
184 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
185 fromName, fromRevision, ns, name, revision);
191 // no need to check if other Type of object, check is performed in
194 if (fromRevision == null) {
195 fromRevision = DEFAULT_REVISION;
198 for (ModuleImport imprt : imports) {
199 String toName = imprt.getModuleName();
200 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
202 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
204 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
207 * Check imports: If module is imported twice with different
208 * revisions then throw exception
210 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
211 && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
212 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
213 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
216 imported.put(toName, toRevision);
224 * Get imported module by its name and revision from moduleGraph
226 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
227 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
228 ModuleNodeImpl to = null;
230 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
231 // If revision is not specified in import, but module exists
232 // with different revisions, take first
233 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
234 && toRevision.equals(DEFAULT_REVISION)) {
235 to = moduleGraph.get(toName).values().iterator().next();
237 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
238 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
239 formatRevDate(to.getRevision())));
241 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
242 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
243 LOGGER.warn("Available models: {}", moduleGraph);
244 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
245 fromName, formatRevDate(fromRevision)));
248 to = moduleGraph.get(toName).get(toRevision);
253 private static void ex(final String message) {
254 throw new YangValidationException(message);
258 * Extract dependencies from module builders or modules to fill dependency
261 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
264 for (Object mb : builders) {
269 if (mb instanceof Module) {
270 name = ((Module) mb).getName();
271 rev = ((Module) mb).getRevision();
272 } else if (mb instanceof ModuleBuilder) {
273 name = ((ModuleBuilder) mb).getName();
274 rev = ((ModuleBuilder) mb).getRevision();
276 throw new IllegalStateException(String.format(
277 "Unexpected type of node for sort, expected only:%s, %s, got:%s", Module.class,
278 ModuleBuilder.class, mb.getClass()));
282 rev = DEFAULT_REVISION;
285 if (moduleGraph.get(name) == null) {
286 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
289 if (moduleGraph.get(name).get(rev) != null) {
290 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
293 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
297 private static String formatRevDate(final Date rev) {
298 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
302 static class ModuleNodeImpl extends NodeImpl {
303 private final String name;
304 private final Date revision;
305 private final Object originalObject;
307 public ModuleNodeImpl(final String name, final Date revision, final Object builder) {
309 this.revision = revision;
310 this.originalObject = builder;
313 public String getName() {
317 public Date getRevision() {
322 public int hashCode() {
323 final int prime = 31;
325 result = prime * result + ((name == null) ? 0 : name.hashCode());
326 result = prime * result + ((revision == null) ? 0 : revision.hashCode());
331 public boolean equals(final Object obj) {
338 if (getClass() != obj.getClass()) {
341 ModuleNodeImpl other = (ModuleNodeImpl) obj;
343 if (other.name != null) {
346 } else if (!name.equals(other.name)) {
349 if (revision == null) {
350 if (other.revision != null) {
353 } else if (!revision.equals(other.revision)) {
360 public String toString() {
361 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
364 public Object getReference() {
365 return originalObject;