Add reverse() method in Edge and Path classes
[controller.git] / opendaylight / config / yang-jmx-generator / src / main / java / org / opendaylight / controller / config / yangjmxgenerator / ModuleMXBeanEntryBuilder.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.controller.config.yangjmxgenerator;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Maps;
15 import com.google.common.collect.Sets;
16 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute;
17 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
18 import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
19 import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
20 import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
21 import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
22 import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
23 import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.NameConflictException;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
36 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
39 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.UsesNode;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import javax.annotation.Nullable;
45 import java.util.Arrays;
46 import java.util.Collection;
47 import java.util.Collections;
48 import java.util.HashMap;
49 import java.util.Map;
50 import java.util.Set;
51 import java.util.regex.Matcher;
52 import java.util.regex.Pattern;
53
54 import static com.google.common.base.Preconditions.checkState;
55 import static java.lang.String.format;
56 import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.createConfigQName;
57
58 final class ModuleMXBeanEntryBuilder {
59
60     private Module currentModule;
61     private Map<QName, ServiceInterfaceEntry> qNamesToSIEs;
62     private SchemaContext schemaContext;
63     private TypeProviderWrapper typeProviderWrapper;
64     private String packageName;
65
66     public ModuleMXBeanEntryBuilder setModule(Module module) {
67         this.currentModule = module;
68         return this;
69     }
70
71     public ModuleMXBeanEntryBuilder setqNamesToSIEs(Map<QName, ServiceInterfaceEntry> qNamesToSIEs) {
72         this.qNamesToSIEs = qNamesToSIEs;
73         return this;
74     }
75
76     public ModuleMXBeanEntryBuilder setSchemaContext(SchemaContext schemaContext) {
77         this.schemaContext = schemaContext;
78         return this;
79     }
80
81     public ModuleMXBeanEntryBuilder setTypeProviderWrapper(TypeProviderWrapper typeProviderWrapper) {
82         this.typeProviderWrapper = typeProviderWrapper;
83         return this;
84     }
85
86     public ModuleMXBeanEntryBuilder setPackageName(String packageName) {
87         this.packageName = packageName;
88         return this;
89     }
90
91     private static final Logger logger = LoggerFactory
92             .getLogger(ModuleMXBeanEntryBuilder.class);
93
94     // TODO: the XPath should be parsed by code generator IMO
95     private static final String MAGIC_STRING = "MAGIC_STRING";
96     private static final String MODULE_CONDITION_XPATH_TEMPLATE = "^/MAGIC_STRING:modules/MAGIC_STRING:module/MAGIC_STRING:type\\s*=\\s*['\"](.+)['\"]$";
97     private static final SchemaPath expectedConfigurationAugmentationSchemaPath = new SchemaPath(
98             Arrays.asList(createConfigQName("modules"),
99                     createConfigQName("module"),
100                     createConfigQName("configuration")), true);
101     private static final SchemaPath expectedStateAugmentationSchemaPath = new SchemaPath(
102             Arrays.asList(createConfigQName("modules"),
103                     createConfigQName("module"), createConfigQName("state")),
104             true);
105     private static final Pattern PREFIX_COLON_LOCAL_NAME = Pattern
106             .compile("^(.+):(.+)$");
107
108
109     public Map<String, ModuleMXBeanEntry> build() {
110         logger.debug("Generating ModuleMXBeans of {} to package {}",
111                 currentModule.getNamespace(), packageName);
112
113         String configModulePrefix;
114         try {
115             configModulePrefix = getConfigModulePrefixFromImport(currentModule);
116         } catch (IllegalArgumentException e) {
117             // this currentModule does not import config currentModule
118             return Collections.emptyMap();
119         }
120
121         // get identities of base config:currentModule-type
122         Map<String, IdentitySchemaNode> moduleIdentities =  getIdentityMap();
123
124         Map<String, QName> uniqueGeneratedClassesNames = new HashMap<>();
125
126         // each currentModule name should have an augmentation defined
127         Map<String, IdentitySchemaNode> unaugmentedModuleIdentities = new HashMap<>(
128                 moduleIdentities);
129
130         Map<String, ModuleMXBeanEntry> result = new HashMap<>();
131
132         for (AugmentationSchema augmentation : currentModule.getAugmentations()) {
133             Set<DataSchemaNode> childNodes = augmentation.getChildNodes();
134             if (areAllChildrenChoiceCaseNodes(childNodes)) {
135                 for (ChoiceCaseNode childCase : castChildNodesToChoiceCases(childNodes)) {
136                     // TODO refactor, extract to standalone builder class
137                     processChoiceCaseNode(result, uniqueGeneratedClassesNames, configModulePrefix, moduleIdentities,
138                             unaugmentedModuleIdentities, augmentation, childCase);
139                 }
140             } // skip if child nodes are not all cases
141         }
142         // clean up nulls
143         cleanUpNulls(result);
144         // check attributes name uniqueness
145         checkAttributeNamesUniqueness(uniqueGeneratedClassesNames, result);
146         checkUnaugumentedIdentities(unaugmentedModuleIdentities);
147
148         logger.debug("Number of ModuleMXBeans to be generated: {}", result.size());
149
150         return result;
151     }
152
153     private static void cleanUpNulls(Map<String, ModuleMXBeanEntry> result) {
154         for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
155             ModuleMXBeanEntry module = entry.getValue();
156             if (module.getAttributes() == null) {
157                 module.setYangToAttributes(Collections
158                         .<String, AttributeIfc> emptyMap());
159             } else if (module.getRuntimeBeans() == null) {
160                 module.setRuntimeBeans(Collections
161                         .<RuntimeBeanEntry> emptyList());
162             }
163         }
164     }
165
166     private static void checkUnaugumentedIdentities(Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
167         if (unaugmentedModuleIdentities.size() > 0) {
168             logger.warn("Augmentation not found for all currentModule identities: {}",
169                     unaugmentedModuleIdentities.keySet());
170         }
171     }
172
173     private static void checkAttributeNamesUniqueness(Map<String, QName> uniqueGeneratedClassesNames, Map<String, ModuleMXBeanEntry> result) {
174         for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
175             checkUniqueRuntimeBeanAttributesName(entry.getValue(),
176                     uniqueGeneratedClassesNames);
177         }
178     }
179
180     private Map<String, IdentitySchemaNode> getIdentityMap() {
181         Map<String, IdentitySchemaNode> moduleIdentities = Maps.newHashMap();
182
183         for (IdentitySchemaNode id : currentModule.getIdentities()) {
184             if (id.getBaseIdentity() != null
185                     && ConfigConstants.MODULE_TYPE_Q_NAME.equals(id.getBaseIdentity().getQName())) {
186                 String identityLocalName = id.getQName().getLocalName();
187                 if (moduleIdentities.containsKey(identityLocalName)) {
188                     throw new IllegalStateException("Module name already defined in this currentModule: "
189                             + identityLocalName);
190                 } else {
191                     moduleIdentities.put(identityLocalName, id);
192                     logger.debug("Found identity {}", identityLocalName);
193                 }
194                 // validation check on unknown schema nodes
195                 boolean providedServiceWasSet = false;
196                 for (UnknownSchemaNode unknownNode : id.getUnknownSchemaNodes()) {
197                     // TODO: test this
198                     if (ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
199                         // no op: 0 or more provided identities are allowed
200                     } else if (ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
201                         // 0..1 allowed
202                         checkState(
203                                 providedServiceWasSet == false,
204                                 format("More than one language extension %s is not allowed here: %s",
205                                         ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME, id));
206                         providedServiceWasSet = true;
207                     } else {
208                         throw new IllegalStateException("Unexpected language extension " + unknownNode.getNodeType());
209                     }
210                 }
211             }
212         }
213
214         return moduleIdentities;
215     }
216
217     private Collection<ChoiceCaseNode> castChildNodesToChoiceCases(Set<DataSchemaNode> childNodes) {
218         return Collections2.transform(childNodes, new Function<DataSchemaNode, ChoiceCaseNode>() {
219             @Nullable
220             @Override
221             public ChoiceCaseNode apply(@Nullable DataSchemaNode input) {
222                 return (ChoiceCaseNode) input;
223             }
224         });
225     }
226
227     private boolean areAllChildrenChoiceCaseNodes(Set<DataSchemaNode> childNodes) {
228         for (DataSchemaNode childNode : childNodes) {
229             if (childNode instanceof ChoiceCaseNode == false)
230                 return false;
231         }
232         return true;
233     }
234
235     private void processChoiceCaseNode(Map<String, ModuleMXBeanEntry> result,
236             Map<String, QName> uniqueGeneratedClassesNames, String configModulePrefix,
237             Map<String, IdentitySchemaNode> moduleIdentities,
238             Map<String, IdentitySchemaNode> unaugmentedModuleIdentities, AugmentationSchema augmentation,
239             DataSchemaNode when) {
240
241         ChoiceCaseNode choiceCaseNode = (ChoiceCaseNode) when;
242         if (choiceCaseNode.getConstraints() == null || choiceCaseNode.getConstraints().getWhenCondition() == null) {
243             return;
244         }
245         RevisionAwareXPath xPath = choiceCaseNode.getConstraints().getWhenCondition();
246         Matcher matcher = getWhenConditionMatcher(configModulePrefix, xPath);
247         if (matcher.matches() == false) {
248             return;
249         }
250         String moduleLocalNameFromXPath = matcher.group(1);
251         IdentitySchemaNode moduleIdentity = moduleIdentities.get(moduleLocalNameFromXPath);
252         unaugmentedModuleIdentities.remove(moduleLocalNameFromXPath);
253         checkState(moduleIdentity != null, "Cannot find identity " + moduleLocalNameFromXPath
254                 + " matching augmentation " + augmentation);
255         Map<String, QName> providedServices = findProvidedServices(moduleIdentity, currentModule, qNamesToSIEs,
256                 schemaContext);
257
258         if (moduleIdentity == null) {
259             throw new IllegalStateException("Cannot find identity specified by augmentation xpath constraint: "
260                     + moduleLocalNameFromXPath + " of " + augmentation);
261         }
262         String javaNamePrefix = TypeProviderWrapper.findJavaNamePrefix(moduleIdentity);
263
264         Map<String, AttributeIfc> yangToAttributes = null;
265         // runtime-data
266         Collection<RuntimeBeanEntry> runtimeBeans = null;
267
268         if (expectedConfigurationAugmentationSchemaPath.equals(augmentation.getTargetPath())) {
269             logger.debug("Parsing configuration of {}", moduleLocalNameFromXPath);
270             yangToAttributes = fillConfiguration(choiceCaseNode, currentModule, typeProviderWrapper, qNamesToSIEs,
271                     schemaContext, packageName);
272             checkUniqueAttributesWithGeneratedClass(uniqueGeneratedClassesNames, when.getQName(), yangToAttributes);
273         } else if (expectedStateAugmentationSchemaPath.equals(augmentation.getTargetPath())) {
274             logger.debug("Parsing state of {}", moduleLocalNameFromXPath);
275             try {
276                 runtimeBeans = fillRuntimeBeans(choiceCaseNode, currentModule, typeProviderWrapper, packageName,
277                         moduleLocalNameFromXPath, javaNamePrefix);
278             } catch (NameConflictException e) {
279                 throw new NameConflictException(e.getConflictingName(), when.getQName(), when.getQName());
280             }
281             checkUniqueRuntimeBeansGeneratedClasses(uniqueGeneratedClassesNames, when, runtimeBeans);
282             Set<RuntimeBeanEntry> runtimeBeanEntryValues = Sets.newHashSet(runtimeBeans);
283             for (RuntimeBeanEntry entry : runtimeBeanEntryValues) {
284                 checkUniqueAttributesWithGeneratedClass(uniqueGeneratedClassesNames, when.getQName(),
285                         entry.getYangPropertiesToTypesMap());
286             }
287
288         } else {
289             throw new IllegalArgumentException("Cannot parse augmentation " + augmentation);
290         }
291         if (result.containsKey(moduleLocalNameFromXPath)) {
292             // either fill runtimeBeans or yangToAttributes
293             ModuleMXBeanEntry moduleMXBeanEntry = result.get(moduleLocalNameFromXPath);
294             if (yangToAttributes != null && moduleMXBeanEntry.getAttributes() == null) {
295                 moduleMXBeanEntry.setYangToAttributes(yangToAttributes);
296             } else if (runtimeBeans != null && moduleMXBeanEntry.getRuntimeBeans() == null) {
297                 moduleMXBeanEntry.setRuntimeBeans(runtimeBeans);
298             }
299         } else {
300             ModuleMXBeanEntry.ModuleMXBeanEntryInitial initial = new ModuleMXBeanEntry.ModuleMXBeanEntryInitialBuilder()
301                     .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix)
302                     .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule))
303                     .build();
304
305             // construct ModuleMXBeanEntry
306             ModuleMXBeanEntry moduleMXBeanEntry = new ModuleMXBeanEntry(initial, yangToAttributes, providedServices,
307                     runtimeBeans);
308
309             moduleMXBeanEntry.setYangModuleName(currentModule.getName());
310             moduleMXBeanEntry.setYangModuleLocalname(moduleLocalNameFromXPath);
311             result.put(moduleLocalNameFromXPath, moduleMXBeanEntry);
312         }
313     }
314
315     private void checkUniqueRuntimeBeansGeneratedClasses(Map<String, QName> uniqueGeneratedClassesNames,
316             DataSchemaNode when, Collection<RuntimeBeanEntry> runtimeBeans) {
317         for (RuntimeBeanEntry runtimeBean : runtimeBeans) {
318             final String javaNameOfRuntimeMXBean = runtimeBean.getJavaNameOfRuntimeMXBean();
319             if (uniqueGeneratedClassesNames.containsKey(javaNameOfRuntimeMXBean)) {
320                 QName firstDefinedQName = uniqueGeneratedClassesNames.get(javaNameOfRuntimeMXBean);
321                 throw new NameConflictException(javaNameOfRuntimeMXBean, firstDefinedQName, when.getQName());
322             }
323             uniqueGeneratedClassesNames.put(javaNameOfRuntimeMXBean, when.getQName());
324         }
325     }
326
327     private static void checkUniqueRuntimeBeanAttributesName(ModuleMXBeanEntry mxBeanEntry,
328             Map<String, QName> uniqueGeneratedClassesNames) {
329         for (RuntimeBeanEntry runtimeBeanEntry : mxBeanEntry.getRuntimeBeans()) {
330             for (String runtimeAttName : runtimeBeanEntry.getYangPropertiesToTypesMap().keySet()) {
331                 if (mxBeanEntry.getAttributes().keySet().contains(runtimeAttName)) {
332                     QName qName1 = uniqueGeneratedClassesNames.get(runtimeBeanEntry.getJavaNameOfRuntimeMXBean());
333                     QName qName2 = uniqueGeneratedClassesNames.get(mxBeanEntry.getGloballyUniqueName());
334                     throw new NameConflictException(runtimeAttName, qName1, qName2);
335                 }
336             }
337         }
338     }
339
340     private void checkUniqueAttributesWithGeneratedClass(Map<String, QName> uniqueGeneratedClassNames,
341             QName parentQName, Map<String, AttributeIfc> yangToAttributes) {
342         for (Map.Entry<String, AttributeIfc> attr : yangToAttributes.entrySet()) {
343             if (attr.getValue() instanceof TOAttribute) {
344                 checkUniqueTOAttr(uniqueGeneratedClassNames, parentQName, (TOAttribute) attr.getValue());
345             } else if (attr.getValue() instanceof ListAttribute
346                     && ((ListAttribute) attr.getValue()).getInnerAttribute() instanceof TOAttribute) {
347                 checkUniqueTOAttr(uniqueGeneratedClassNames, parentQName,
348                         (TOAttribute) ((ListAttribute) attr.getValue()).getInnerAttribute());
349             }
350         }
351     }
352
353     private void checkUniqueTOAttr(Map<String, QName> uniqueGeneratedClassNames, QName parentQName, TOAttribute attr) {
354         final String upperCaseCammelCase = attr.getUpperCaseCammelCase();
355         if (uniqueGeneratedClassNames.containsKey(upperCaseCammelCase)) {
356             QName firstDefinedQName = uniqueGeneratedClassNames.get(upperCaseCammelCase);
357             throw new NameConflictException(upperCaseCammelCase, firstDefinedQName, parentQName);
358         } else {
359             uniqueGeneratedClassNames.put(upperCaseCammelCase, parentQName);
360         }
361     }
362
363     private Collection<RuntimeBeanEntry> fillRuntimeBeans(ChoiceCaseNode choiceCaseNode, Module currentModule,
364             TypeProviderWrapper typeProviderWrapper, String packageName, String moduleLocalNameFromXPath,
365             String javaNamePrefix) {
366
367         return RuntimeBeanEntry.extractClassNameToRuntimeBeanMap(packageName, choiceCaseNode, moduleLocalNameFromXPath,
368                 typeProviderWrapper, javaNamePrefix, currentModule).values();
369
370     }
371
372     private Map<String, AttributeIfc> fillConfiguration(ChoiceCaseNode choiceCaseNode, Module currentModule,
373             TypeProviderWrapper typeProviderWrapper, Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
374             SchemaContext schemaContext, String packageName) {
375         Map<String, AttributeIfc> yangToAttributes = new HashMap<>();
376         for (DataSchemaNode attrNode : choiceCaseNode.getChildNodes()) {
377             AttributeIfc attributeValue = getAttributeValue(attrNode, currentModule, qNamesToSIEs, typeProviderWrapper,
378                     schemaContext, packageName);
379             yangToAttributes.put(attributeValue.getAttributeYangName(), attributeValue);
380         }
381         return yangToAttributes;
382     }
383
384     private Map<String, QName> findProvidedServices(IdentitySchemaNode moduleIdentity, Module currentModule,
385             Map<QName, ServiceInterfaceEntry> qNamesToSIEs, SchemaContext schemaContext) {
386         Map<String, QName> result = new HashMap<>();
387         for (UnknownSchemaNode unknownNode : moduleIdentity.getUnknownSchemaNodes()) {
388             if (ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
389                 String prefixAndIdentityLocalName = unknownNode.getNodeParameter();
390                 ServiceInterfaceEntry sie = findSIE(prefixAndIdentityLocalName, currentModule, qNamesToSIEs,
391                         schemaContext);
392                 result.put(sie.getFullyQualifiedName(), sie.getQName());
393             }
394         }
395         return result;
396     }
397
398     private AttributeIfc getAttributeValue(DataSchemaNode attrNode, Module currentModule,
399             Map<QName, ServiceInterfaceEntry> qNamesToSIEs, TypeProviderWrapper typeProviderWrapper,
400             SchemaContext schemaContext, String packageName) {
401
402         if (attrNode instanceof LeafSchemaNode) {
403             // simple type
404             LeafSchemaNode leaf = (LeafSchemaNode) attrNode;
405             return new JavaAttribute(leaf, typeProviderWrapper);
406         } else if (attrNode instanceof ContainerSchemaNode) {
407             // reference or TO
408             ContainerSchemaNode containerSchemaNode = (ContainerSchemaNode) attrNode;
409             Optional<? extends AbstractDependencyAttribute> dependencyAttributeOptional = extractDependency(
410                     containerSchemaNode, attrNode, currentModule, qNamesToSIEs, schemaContext);
411             if (dependencyAttributeOptional.isPresent()) {
412                 return dependencyAttributeOptional.get();
413             } else {
414                 return TOAttribute.create(containerSchemaNode, typeProviderWrapper, packageName);
415             }
416
417         } else if (attrNode instanceof LeafListSchemaNode) {
418             return ListAttribute.create((LeafListSchemaNode) attrNode, typeProviderWrapper);
419         } else if (attrNode instanceof ListSchemaNode) {
420             ListSchemaNode listSchemaNode = (ListSchemaNode) attrNode;
421             Optional<? extends AbstractDependencyAttribute> dependencyAttributeOptional = extractDependency(
422                     listSchemaNode, attrNode, currentModule, qNamesToSIEs, schemaContext);
423             if (dependencyAttributeOptional.isPresent()) {
424                 return dependencyAttributeOptional.get();
425             } else {
426                 return ListAttribute.create(listSchemaNode, typeProviderWrapper, packageName);
427             }
428         } else {
429             throw new UnsupportedOperationException("Unknown configuration node " + attrNode.toString());
430         }
431     }
432
433     private Optional<? extends AbstractDependencyAttribute> extractDependency(DataNodeContainer dataNodeContainer,
434             DataSchemaNode attrNode, Module currentModule, Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
435             SchemaContext schemaContext) {
436         if (dataNodeContainer.getUses().size() == 1 && getChildNodeSizeWithoutUses(dataNodeContainer) == 0) {
437             // reference
438             UsesNode usesNode = dataNodeContainer.getUses().iterator().next();
439             checkState(usesNode.getRefines().size() == 1, "Unexpected 'refine' child node size of " + dataNodeContainer);
440             LeafSchemaNode refine = (LeafSchemaNode) usesNode.getRefines().values().iterator().next();
441             checkState(refine.getUnknownSchemaNodes().size() == 1, "Unexpected unknown schema node size of " + refine);
442             UnknownSchemaNode requiredIdentity = refine.getUnknownSchemaNodes().iterator().next();
443             checkState(ConfigConstants.REQUIRED_IDENTITY_EXTENSION_QNAME.equals(requiredIdentity.getNodeType()),
444                     "Unexpected language extension " + requiredIdentity);
445             String prefixAndIdentityLocalName = requiredIdentity.getNodeParameter();
446             // import should point to a module
447             ServiceInterfaceEntry serviceInterfaceEntry = findSIE(prefixAndIdentityLocalName, currentModule,
448                     qNamesToSIEs, schemaContext);
449             boolean mandatory = refine.getConstraints().isMandatory();
450             AbstractDependencyAttribute reference;
451             if (dataNodeContainer instanceof ContainerSchemaNode) {
452                 reference = new DependencyAttribute(attrNode, serviceInterfaceEntry, mandatory,
453                         attrNode.getDescription());
454             } else {
455                 reference = new ListDependenciesAttribute(attrNode, serviceInterfaceEntry, mandatory,
456                         attrNode.getDescription());
457             }
458             return Optional.of(reference);
459         }
460         return Optional.absent();
461     }
462
463     private int getChildNodeSizeWithoutUses(DataNodeContainer csn) {
464         int result = 0;
465         for (DataSchemaNode dsn : csn.getChildNodes()) {
466             if (dsn.isAddedByUses() == false) {
467                 result++;
468             }
469         }
470         return result;
471     }
472
473     private ServiceInterfaceEntry findSIE(String prefixAndIdentityLocalName, Module currentModule,
474             Map<QName, ServiceInterfaceEntry> qNamesToSIEs, SchemaContext schemaContext) {
475
476         Matcher m = PREFIX_COLON_LOCAL_NAME.matcher(prefixAndIdentityLocalName);
477         Module foundModule;
478         String localSIName;
479         if (m.matches()) {
480             // if there is a prefix, look for ModuleImport with this prefix. Get
481             // Module from SchemaContext
482             String prefix = m.group(1);
483             ModuleImport moduleImport = findModuleImport(currentModule, prefix);
484             foundModule = schemaContext.findModuleByName(moduleImport.getModuleName(), moduleImport.getRevision());
485             checkState(foundModule != null, format("Module not found in SchemaContext by %s", moduleImport));
486             localSIName = m.group(2);
487         } else {
488             foundModule = currentModule; // no prefix => SIE is in currentModule
489             localSIName = prefixAndIdentityLocalName;
490         }
491         QName siQName = new QName(foundModule.getNamespace(), foundModule.getRevision(), localSIName);
492         ServiceInterfaceEntry sie = qNamesToSIEs.get(siQName);
493         checkState(sie != null, "Cannot find referenced Service Interface by " + prefixAndIdentityLocalName);
494         return sie;
495     }
496
497     private ModuleImport findModuleImport(Module module, String prefix) {
498         for (ModuleImport moduleImport : module.getImports()) {
499             if (moduleImport.getPrefix().equals(prefix)) {
500                 return moduleImport;
501             }
502         }
503         throw new IllegalStateException(format("Import not found with prefix %s in %s", prefix, module));
504     }
505
506     @VisibleForTesting
507     static Matcher getWhenConditionMatcher(String prefix, RevisionAwareXPath whenConstraint) {
508         String xpathRegex = MODULE_CONDITION_XPATH_TEMPLATE.replace(MAGIC_STRING, prefix);
509         Pattern pattern = Pattern.compile(xpathRegex);
510         return pattern.matcher(whenConstraint.toString());
511     }
512
513     String getConfigModulePrefixFromImport(Module currentModule) {
514         for (ModuleImport currentImport : currentModule.getImports()) {
515             if (currentImport.getModuleName().equals(ConfigConstants.CONFIG_MODULE)) {
516                 return currentImport.getPrefix();
517             }
518         }
519         throw new IllegalArgumentException("Cannot find import " + ConfigConstants.CONFIG_MODULE + " in "
520                 + currentModule);
521     }
522
523 }