Merge "BUG-868: stop using getChildren()"
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / util / ModuleDependencySort.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.util;
9
10 import java.net.URI;
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;
18 import java.util.Map;
19 import java.util.Set;
20
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;
30
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;
36
37 /**
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}).
42  */
43 public final class ModuleDependencySort {
44
45     private static final Date DEFAULT_REVISION = new Date(0);
46     private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
47
48     /**
49      * It is not desirable to instance this class
50      */
51     private ModuleDependencySort() {
52     }
53
54     /**
55      * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
56      */
57     private static final Function<Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<Node, ModuleBuilder>() {
58         @Override
59         public ModuleBuilder apply(final Node input) {
60             // Cast to ModuleBuilder from Node and return
61             return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
62         }
63     };
64
65     /**
66      * Topological sort of module builder dependency graph.
67      *
68      * @return Sorted list of Module builders. Modules can be further processed
69      *         in returned order.
70      */
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);
74     }
75
76     public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
77         ModuleBuilder[] array = new ModuleBuilder[builders.size()];
78         builders.toArray(array);
79         return sort(array);
80     }
81
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());
86
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>() {
90
91             @Override
92             public ModuleBuilder apply(final Node input) {
93                 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
94                     return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
95                 } else {
96                     return null;
97                 }
98             }
99         });
100     }
101
102     /**
103      * Topological sort of module dependency graph.
104      *
105      * @return Sorted list of Modules. Modules can be further processed in
106      *         returned order.
107      */
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>() {
112
113             @Override
114             public Module apply(final Node input) {
115                 return (Module) ((ModuleNodeImpl) input).getReference();
116             }
117         });
118     }
119
120     private static List<Node> sortInternal(final List<?> modules) {
121         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
122
123         Set<Node> nodes = Sets.newHashSet();
124         for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
125             for (ModuleNodeImpl node : map.values()) {
126                 nodes.add(node);
127             }
128         }
129
130         return TopologicalSort.sort(nodes);
131     }
132
133     @VisibleForTesting
134     static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final List<?> builders) {
135         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
136
137         processModules(moduleGraph, builders);
138         processDependencies(moduleGraph, builders);
139
140         return moduleGraph;
141     }
142
143     /**
144      * Extract module:revision from module builders
145      */
146     private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
147         Map<URI, Object> allNS = new HashMap<>();
148
149         // Create edges in graph
150         for (Object mb : builders) {
151             Map<String, Date> imported = Maps.newHashMap();
152
153             String fromName = null;
154             Date fromRevision = null;
155             Set<ModuleImport> imports = null;
156             URI ns = null;
157
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();
168             }
169
170             // check for existence of module with same namespace
171             if (allNS.containsKey(ns)) {
172                 Object mod = allNS.get(ns);
173                 String name = null;
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();
181                 }
182                 if (!(fromName.equals(name))) {
183                     LOGGER.warn(
184                             "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
185                             fromName, fromRevision, ns, name, revision);
186                 }
187             } else {
188                 allNS.put(ns, mb);
189             }
190
191             // no need to check if other Type of object, check is performed in
192             // process modules
193
194             if (fromRevision == null) {
195                 fromRevision = DEFAULT_REVISION;
196             }
197
198             for (ModuleImport imprt : imports) {
199                 String toName = imprt.getModuleName();
200                 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
201
202                 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
203
204                 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
205
206                 /*
207                  * Check imports: If module is imported twice with different
208                  * revisions then throw exception
209                  */
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)));
214                 }
215
216                 imported.put(toName, toRevision);
217
218                 from.addEdge(to);
219             }
220         }
221     }
222
223     /**
224      * Get imported module by its name and revision from moduleGraph
225      */
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;
229
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();
236                 LOGGER.debug(String
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())));
240             } else {
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)));
246             }
247         } else {
248             to = moduleGraph.get(toName).get(toRevision);
249         }
250         return to;
251     }
252
253     private static void ex(final String message) {
254         throw new YangValidationException(message);
255     }
256
257     /**
258      * Extract dependencies from module builders or modules to fill dependency
259      * graph
260      */
261     private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
262
263         // Process nodes
264         for (Object mb : builders) {
265
266             String name = null;
267             Date rev = null;
268
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();
275             } else {
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()));
279             }
280
281             if (rev == null) {
282                 rev = DEFAULT_REVISION;
283             }
284
285             if (moduleGraph.get(name) == null) {
286                 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
287             }
288
289             if (moduleGraph.get(name).get(rev) != null) {
290                 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
291             }
292
293             moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
294         }
295     }
296
297     private static String formatRevDate(final Date rev) {
298         return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
299     }
300
301     @VisibleForTesting
302     static class ModuleNodeImpl extends NodeImpl {
303         private final String name;
304         private final Date revision;
305         private final Object originalObject;
306
307         public ModuleNodeImpl(final String name, final Date revision, final Object builder) {
308             this.name = name;
309             this.revision = revision;
310             this.originalObject = builder;
311         }
312
313         public String getName() {
314             return name;
315         }
316
317         public Date getRevision() {
318             return revision;
319         }
320
321         @Override
322         public int hashCode() {
323             final int prime = 31;
324             int result = 1;
325             result = prime * result + ((name == null) ? 0 : name.hashCode());
326             result = prime * result + ((revision == null) ? 0 : revision.hashCode());
327             return result;
328         }
329
330         @Override
331         public boolean equals(final Object obj) {
332             if (this == obj) {
333                 return true;
334             }
335             if (obj == null) {
336                 return false;
337             }
338             if (getClass() != obj.getClass()) {
339                 return false;
340             }
341             ModuleNodeImpl other = (ModuleNodeImpl) obj;
342             if (name == null) {
343                 if (other.name != null) {
344                     return false;
345                 }
346             } else if (!name.equals(other.name)) {
347                 return false;
348             }
349             if (revision == null) {
350                 if (other.revision != null) {
351                     return false;
352                 }
353             } else if (!revision.equals(other.revision)) {
354                 return false;
355             }
356             return true;
357         }
358
359         @Override
360         public String toString() {
361             return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
362         }
363
364         public Object getReference() {
365             return originalObject;
366         }
367
368     }
369
370 }