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