--- /dev/null
+/*
+ * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.mdsal.binding.javav2.generator.yang.types;
+
+import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl.addUnitsToGenTO;
+import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import java.io.Serializable;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
+import org.opendaylight.mdsal.binding.javav2.generator.util.TypeConstants;
+import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
+import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.EnumerationBuilderImpl;
+import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
+import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
+import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType;
+import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration;
+import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
+import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
+import org.opendaylight.mdsal.binding.javav2.model.api.Type;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
+import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
+import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
+import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+
+/**
+ * Auxiliary util class for {@link TypeProviderImpl} class
+ */
+@Beta
+final class TypeGenHelper {
+
+ private TypeGenHelper() {
+ throw new UnsupportedOperationException("Util class");
+ }
+
+ /**
+ * Gets base type definition for <code>extendTypeDef</code>. The method is
+ * recursively called until non <code>ExtendedType</code> type is found.
+ *
+ * @param extendTypeDef
+ * type definition for which is the base type definition sought
+ * @return type definition which is base type for <code>extendTypeDef</code>
+ * @throws IllegalArgumentException
+ * if <code>extendTypeDef</code> equal null
+ */
+ static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
+ Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
+
+ TypeDefinition<?> ret = extendTypeDef;
+ while (ret.getBaseType() != null) {
+ ret = ret.getBaseType();
+ }
+
+ return ret;
+ }
+
+ /**
+ * Creates generated TO with data about inner extended type
+ * <code>innerExtendedType</code>, about the package name
+ * <code>typedefName</code> and about the generated TO name
+ * <code>typedefName</code>.
+ *
+ * It is supposed that <code>innerExtendedType</code> is already present in
+ * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
+ * be possible set it as extended type for the returning generated TO.
+ *
+ * @param typedef
+ * Type Definition
+ * @param innerExtendedType
+ * extended type which is part of some other extended type
+ * @param basePackageName
+ * string with the package name of the module
+ * @param moduleName
+ * Module Name
+ * @return generated TO which extends generated TO for
+ * <code>innerExtendedType</code>
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>extendedType</code> equals null</li>
+ * <li>if <code>basePackageName</code> equals null</li>
+ * <li>if <code>typedefName</code> equals null</li>
+ * </ul>
+ */
+ static GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final
+ TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName, final SchemaContext
+ schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
+ Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
+
+ final String typedefName = typedef.getQName().getLocalName();
+ final String classTypedefName = BindingMapping.getClassName(typedefName);
+ final String innerTypeDef = innerExtendedType.getQName().getLocalName();
+ final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+
+ genTOBuilder.setDescription(typedefDescription);
+ genTOBuilder.setReference(typedef.getReference());
+ genTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot());
+ genTOBuilder.setModuleName(moduleName);
+ genTOBuilder.setTypedef(true);
+ Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
+ genTOBuilder.setRestrictions(r);
+ if (typedef.getStatus() == Status.DEPRECATED) {
+ genTOBuilder.addAnnotation("", "Deprecated");
+ }
+
+ if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
+ genTOBuilder.setIsUnion(true);
+ }
+
+ Map<Date, Map<String, Type>> modulesByDate = null;
+ Map<String, Type> typeMap = null;
+ final Module parentModule = findParentModule(schemaContext, innerExtendedType);
+ if (parentModule != null) {
+ modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
+ typeMap = modulesByDate.get(parentModule.getRevision());
+ }
+
+ if (typeMap != null) {
+ Type type = typeMap.get(innerTypeDef);
+ if (type instanceof GeneratedTransferObject) {
+ genTOBuilder.setExtendsType((GeneratedTransferObject) type);
+ }
+ }
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ makeSerializable(genTOBuilder);
+
+ return genTOBuilder.toInstance();
+ }
+
+ /**
+ * Wraps base YANG type to generated TO.
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param typedef
+ * type definition which is converted to the TO
+ * @param javaType
+ * JAVA <code>Type</code> to which is <code>typedef</code> mapped
+ * @return generated transfer object which represent<code>javaType</code>
+ */
+ static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
+ Preconditions.checkNotNull(javaType, "javaType cannot be null");
+ final String propertyName = "value";
+
+ final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
+ genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
+ final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
+ genPropBuilder.setReturnType(javaType);
+ genTOBuilder.addEqualsIdentity(genPropBuilder);
+ genTOBuilder.addHashIdentity(genPropBuilder);
+ genTOBuilder.addToStringProperty(genPropBuilder);
+ if (typedef.getStatus() == Status.DEPRECATED) {
+ genTOBuilder.addAnnotation("", "Deprecated");
+ }
+ if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
+ final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
+ addStringRegExAsConstant(genTOBuilder, regExps);
+ }
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ genTOBuilder.setTypedef(true);
+ makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
+ return genTOBuilder.toInstance();
+ }
+
+ /**
+ * Converts the pattern constraints from <code>typedef</code> to the list of
+ * the strings which represents these constraints.
+ *
+ * @param typedef
+ * extended type in which are the pattern constraints sought
+ * @return list of strings which represents the constraint patterns
+ * @throws IllegalArgumentException
+ * if <code>typedef</code> equals null
+ *
+ */
+ static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
+ Preconditions.checkArgument(typedef != null, "typedef can't be null");
+
+ final List<PatternConstraint> patternConstraints;
+ if (typedef instanceof StringTypeDefinition) {
+ patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
+ } else {
+ patternConstraints = ImmutableList.of();
+ }
+
+ final List<String> regExps = new ArrayList<>(patternConstraints.size());
+ for (PatternConstraint patternConstraint : patternConstraints) {
+ final String regEx = patternConstraint.getRegularExpression();
+ final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
+ regExps.add(modifiedRegEx);
+ }
+
+ return regExps;
+ }
+
+ /**
+ * Finds out for each type definition how many immersion (depth) is
+ * necessary to get to the base type. Every type definition is inserted to
+ * the map which key is depth and value is list of type definitions with
+ * equal depth. In next step are lists from this map concatenated to one
+ * list in ascending order according to their depth. All type definitions
+ * are in the list behind all type definitions on which depends.
+ *
+ * @param unsortedTypeDefinitions
+ * list of type definitions which should be sorted by depth
+ * @return list of type definitions sorted according their each other
+ * dependencies (type definitions which are depend on other type
+ * definitions are in list behind them).
+ */
+ static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
+ final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
+ List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
+
+ Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
+ for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
+ final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
+ List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
+ typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
+ }
+
+ // SortedMap guarantees order corresponding to keys in ascending order
+ typeDefinitionsDepths.values().forEach(sortedTypeDefinition::addAll);
+
+ return sortedTypeDefinition;
+ }
+
+ /**
+ *
+ * Adds to the <code>genTOBuilder</code> the constant which contains regular
+ * expressions from the <code>regularExpressions</code>
+ *
+ * @param genTOBuilder
+ * generated TO builder to which are
+ * <code>regular expressions</code> added
+ * @param regularExpressions
+ * list of string which represent regular expressions
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>genTOBuilder</code> equals null</li>
+ * <li>if <code>regularExpressions</code> equals null</li>
+ * </ul>
+ */
+ static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
+ if (genTOBuilder == null) {
+ throw new IllegalArgumentException("Generated transfer object builder can't be null");
+ }
+ if (regularExpressions == null) {
+ throw new IllegalArgumentException("List of regular expressions can't be null");
+ }
+ if (!regularExpressions.isEmpty()) {
+ genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
+ regularExpressions);
+ }
+ }
+
+ /**
+ * Returns how many immersion is necessary to get from the type definition
+ * to the base type.
+ *
+ * @param typeDefinition
+ * type definition for which is depth sought.
+ * @return number of immersions which are necessary to get from the type
+ * definition to the base type
+ */
+ private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
+ if (typeDefinition == null) {
+ return 1;
+ }
+ TypeDefinition<?> baseType = typeDefinition.getBaseType();
+ if (baseType == null) {
+ return 1;
+ }
+
+ int depth = 1;
+ if (baseType.getBaseType() != null) {
+ depth = depth + getTypeDefinitionDepth(baseType);
+ } else if (baseType instanceof UnionTypeDefinition) {
+ List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
+ int maxChildDepth = 0;
+ int childDepth = 1;
+ for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
+ childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
+ if (childDepth > maxChildDepth) {
+ maxChildDepth = childDepth;
+ }
+ }
+ return maxChildDepth;
+ }
+ return depth;
+ }
+
+ static List<TypeDefinition<?>> getAllTypedefs(final Module module) {
+ final List<TypeDefinition<?>> ret = new ArrayList<>();
+
+ fillRecursively(ret, module);
+
+ final Set<NotificationDefinition> notifications = module.getNotifications();
+ for (NotificationDefinition notificationDefinition : notifications) {
+ fillRecursively(ret, notificationDefinition);
+ }
+
+ final Set<RpcDefinition> rpcs = module.getRpcs();
+ for (RpcDefinition rpcDefinition : rpcs) {
+ ret.addAll(rpcDefinition.getTypeDefinitions());
+ ContainerSchemaNode input = rpcDefinition.getInput();
+ if (input != null) {
+ fillRecursively(ret, input);
+ }
+ ContainerSchemaNode output = rpcDefinition.getOutput();
+ if (output != null) {
+ fillRecursively(ret, output);
+ }
+ }
+
+ final Collection<DataSchemaNode> potentials = module.getChildNodes();
+
+ for (DataSchemaNode potential : potentials) {
+ if (potential instanceof ActionNodeContainer) {
+ final Set<ActionDefinition> actions = ((ActionNodeContainer) potential).getActions();
+ for (ActionDefinition action: actions) {
+ ContainerSchemaNode input = action.getInput();
+ if (input != null) {
+ fillRecursively(ret, input);
+ }
+ ContainerSchemaNode output = action.getOutput();
+ if (output != null) {
+ fillRecursively(ret, output);
+ }
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ private static void fillRecursively(final List<TypeDefinition<?>> list, final DataNodeContainer container) {
+ final Collection<DataSchemaNode> childNodes = container.getChildNodes();
+ if (childNodes != null) {
+ childNodes.stream().filter(childNode -> !childNode.isAugmenting()).forEach(childNode -> {
+ if (childNode instanceof ContainerSchemaNode) {
+ fillRecursively(list, (ContainerSchemaNode) childNode);
+ } else if (childNode instanceof ListSchemaNode) {
+ fillRecursively(list, (ListSchemaNode) childNode);
+ } else if (childNode instanceof ChoiceSchemaNode) {
+ final Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
+ if (cases != null) {
+ for (final ChoiceCaseNode caseNode : cases) {
+ fillRecursively(list, caseNode);
+ }
+ }
+ }
+ });
+ }
+
+ list.addAll(container.getTypeDefinitions());
+
+ final Set<GroupingDefinition> groupings = container.getGroupings();
+ if (groupings != null) {
+ for (GroupingDefinition grouping : groupings) {
+ fillRecursively(list, grouping);
+ }
+ }
+ }
+
+ /**
+ * Add {@link Serializable} to implemented interfaces of this TO. Also
+ * compute and add serialVersionUID property.
+ *
+ * @param gto
+ * transfer object which needs to be serializable
+ */
+ static void makeSerializable(final GeneratedTOBuilderImpl gto) {
+ gto.addImplementsType(Types.typeForClass(Serializable.class));
+ GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
+ prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
+ gto.setSUID(prop);
+ }
+
+ /**
+ * Converts <code>enumTypeDef</code> to
+ * {@link Enumeration
+ * enumeration}.
+ *
+ * @param enumTypeDef
+ * enumeration type definition which is converted to enumeration
+ * @param enumName
+ * string with name which is used as the enumeration name
+ * @return enumeration type which is built with data (name, enum values)
+ * from <code>enumTypeDef</code>
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>enumTypeDef</code> equals null</li>
+ * <li>if enum values of <code>enumTypeDef</code> equal null</li>
+ * <li>if Q name of <code>enumTypeDef</code> equal null</li>
+ * <li>if name of <code>enumTypeDef</code> equal null</li>
+ * </ul>
+ */
+ static Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName, final
+ SchemaNode parentNode, final SchemaContext schemaContext) {
+ Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
+ Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
+ "Local Name in EnumTypeDefinition QName cannot be NULL!");
+
+ final String enumerationName = BindingMapping.getClassName(enumName);
+
+ Module module = findParentModule(schemaContext, parentNode);
+ final String basePackageName = BindingMapping.getRootPackageName(module);
+
+ final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ enumBuilder.setDescription(enumTypedefDescription);
+ enumBuilder.setReference(enumTypeDef.getReference());
+ enumBuilder.setModuleName(module.getName());
+ enumBuilder.setSchemaPath((List) enumTypeDef.getPath().getPathFromRoot());
+ enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
+ return enumBuilder.toInstance(null);
+ }
+
+ /**
+ * Converts <code>typedef</code> to the generated TO builder.
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param typedef
+ * type definition from which is the generated TO builder created
+ * @return generated TO builder which contains data from
+ * <code>typedef</code> and <code>basePackageName</code>
+ */
+ private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
+
+ final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath
+ (), BindingNamespaceType.Typedef);
+ final String typeDefTOName = typedef.getQName().getLocalName();
+
+ if ((packageName != null) && (typeDefTOName != null)) {
+ final String genTOName = BindingMapping.getClassName(typeDefTOName);
+ final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+
+ newType.setDescription(typedefDescription);
+ newType.setReference(typedef.getReference());
+ newType.setSchemaPath((List) typedef.getPath().getPathFromRoot());
+ newType.setModuleName(moduleName);
+
+ return newType;
+ }
+ return null;
+ }
+
+ static Module getParentModule(final SchemaNode node, final SchemaContext schemaContext) {
+ QName qname = node.getPath().getPathFromRoot().iterator().next();
+ URI namespace = qname.getNamespace();
+ Date revision = qname.getRevision();
+ return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
+ }
+}
package org.opendaylight.mdsal.binding.javav2.generator.yang.types;
+import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.addStringRegExAsConstant;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.baseTypeDefForExtendedType;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.getAllTypedefs;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.getParentModule;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.makeSerializable;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.provideGeneratedTOFromExtendedType;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.provideTypeForEnum;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.resolveRegExpressionsFromTypedef;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.sortTypeDefinitionAccordingDepth;
+import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.wrapJavaTypeIntoTO;
+import static org.opendaylight.mdsal.binding.javav2.util.BindingMapping.getRootPackageName;
+import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
+import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
+import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
+
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.Sets;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
+import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
+import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
+import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
+import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
+import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
+import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration;
+import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty;
+import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
import org.opendaylight.mdsal.binding.javav2.model.api.Type;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
+import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
+import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
+import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
+import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Beta
public final class TypeProviderImpl implements TypeProvider {
+ private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
+ private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
+
/**
* Contains the schema data red from YANG files.
*/
*/
private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
-
/**
* Map which maps schema paths to JAVA <code>Type</code>.
*/
this.genTypeDefsContextMap = new HashMap<>();
this.referencedTypes = new HashMap<>();
this.additionalTypes = new HashMap<>();
+ resolveTypeDefsFromContext(schemaContext, genTypeDefsContextMap, additionalTypes);
}
@Override
- public Type javaTypeForSchemaDefinitionType(TypeDefinition<?> type, SchemaNode parentNode) {
- return null;
+ public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, SchemaNode parentNode) {
+ return javaTypeForSchemaDefinitionType(type, parentNode, null);
}
+ /**
+ * Converts schema definition type <code>typeDefinition</code> to JAVA
+ * <code>Type</code>
+ *
+ * @param type
+ * type definition which is converted to JAVA type
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>typeDefinition</code> equal null</li>
+ * <li>if Qname of <code>typeDefinition</code> equal null</li>
+ * <li>if name of <code>typeDefinition</code> equal null</li>
+ * </ul>
+ */
@Override
public Type javaTypeForSchemaDefinitionType(TypeDefinition<?> type, SchemaNode parentNode, Restrictions restrictions) {
- return null;
+ return javaTypeForSchemaDefType(type, parentNode, restrictions, this.schemaContext, this.genTypeDefsContextMap);
}
@Override
return null;
}
+ /**
+ * Passes through all modules and through all its type definitions and
+ * convert it to generated types.
+ *
+ * The modules are firstly sorted by mutual dependencies. The modules are
+ * sequentially passed. All type definitions of a module are at the
+ * beginning sorted so that type definition with less amount of references
+ * to other type definition are processed first.<br />
+ * For each module is created mapping record in the map
+ * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
+ * which map current module name to the map which maps type names to
+ * returned types (generated types).
+ *
+ */
+ private void resolveTypeDefsFromContext(final SchemaContext schemaContext, Map<String, Map<Date, Map<String,
+ Type>>> genTypeDefsContextMap, Map<Module, Set<Type>> additionalTypes) {
+
+ final Set<Module> modules = schemaContext.getModules();
+ Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
+ final Module[] modulesArray = new Module[modules.size()];
+ int i = 0;
+ for (Module modul : modules) {
+ modulesArray[i++] = modul;
+ }
+ final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
+ .sort(modulesArray);
+
+ for (final Module module : modulesSortedByDependency) {
+ Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
+ if (dateTypeMap == null) {
+ dateTypeMap = new HashMap<>();
+ }
+ dateTypeMap.put(module.getRevision(), Collections.emptyMap());
+ genTypeDefsContextMap.put(module.getName(), dateTypeMap);
+ }
+
+ modulesSortedByDependency.stream().filter(module -> module != null).forEach(module -> {
+ final String basePackageName = getRootPackageName(module);
+ final List<TypeDefinition<?>> typeDefinitions = getAllTypedefs(module);
+ final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
+ if (listTypeDefinitions != null) {
+ for (final TypeDefinition<?> typedef : listTypeDefinitions) {
+ typedefToGeneratedType(basePackageName, module, typedef, genTypeDefsContextMap,
+ additionalTypes, schemaContext);
+ }
+ }
+ });
+ }
+
/**
* Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
*
*/
public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
- if (typeDefinition.getQName() == null) {
- throw new IllegalArgumentException(
- "Type Definition cannot have non specified QName (QName cannot be NULL!)");
- }
Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
"Type Definitions Local Name cannot be NULL!");
final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
- final Module module = SchemaContextUtil.findParentModule(schemaContext, parentNode);
+ final Module module = findParentModule(schemaContext, parentNode);
if (module != null) {
final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
}
/**
- * Gets base type definition for <code>extendTypeDef</code>. The method is
- * recursively called until non <code>ExtendedType</code> type is found.
+ * Puts <code>refType</code> to map with key <code>refTypePath</code>
*
- * @param extendTypeDef
- * type definition for which is the base type definition sought
- * @return type definition which is base type for <code>extendTypeDef</code>
+ * @param refTypePath
+ * schema path used as the map key
+ * @param refType
+ * type which represents the map value
* @throws IllegalArgumentException
- * if <code>extendTypeDef</code> equal null
+ * <ul>
+ * <li>if <code>refTypePath</code> equal null</li>
+ * <li>if <code>refType</code> equal null</li>
+ * </ul>
+ *
*/
- private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
- Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
+ public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
+ Preconditions.checkArgument(refTypePath != null,
+ "Path reference of Enumeration Type Definition cannot be NULL!");
+ Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
+ referencedTypes.put(refTypePath, refType);
+ }
- TypeDefinition<?> ret = extendTypeDef;
- while (ret.getBaseType() != null) {
- ret = ret.getBaseType();
+ /**
+ * Converts <code>typeDef</code> which should be of the type
+ * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
+ *
+ * All the bits of the typeDef are added to returning generated TO as
+ * properties.
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param typeDef
+ * type definition from which is the generated TO builder created
+ * @param typeDefName
+ * string with the name for generated TO builder
+ * @return generated TO builder which represents <code>typeDef</code>
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>typeDef</code> equals null</li>
+ * <li>if <code>basePackageName</code> equals null</li>
+ * </ul>
+ */
+ public static GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final
+ TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
+
+ Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
+ Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
+
+ if (typeDef instanceof BitsTypeDefinition) {
+ BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
+
+ final String typeName = BindingMapping.getClassName(typeDefName);
+ final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
+ final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
+
+ genTOBuilder.setDescription(typedefDescription);
+ genTOBuilder.setReference(typeDef.getReference());
+ genTOBuilder.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
+ genTOBuilder.setModuleName(moduleName);
+ genTOBuilder.setBaseType(typeDef);
+
+ final List<Bit> bitList = bitsTypeDefinition.getBits();
+ GeneratedPropertyBuilder genPropertyBuilder;
+ for (final Bit bit : bitList) {
+ String name = bit.getName();
+ genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
+ genPropertyBuilder.setReadOnly(true);
+ genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
+
+ genTOBuilder.addEqualsIdentity(genPropertyBuilder);
+ genTOBuilder.addHashIdentity(genPropertyBuilder);
+ genTOBuilder.addToStringProperty(genPropertyBuilder);
+ }
+
+ return genTOBuilder;
}
+ return null;
+ }
- return ret;
+ /**
+ * Converts <code>typedef</code> to generated TO with
+ * <code>typeDefName</code>. Every union type from <code>typedef</code> is
+ * added to generated TO builder as property.
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param typedef
+ * type definition which should be of type
+ * <code>UnionTypeDefinition</code>
+ * @param typeDefName
+ * string with name for generated TO
+ * @return generated TO builder which represents <code>typedef</code>
+ * @throws NullPointerException
+ * <ul>
+ * <li>if <code>basePackageName</code> is null</li>
+ * <li>if <code>typedef</code> is null</li>
+ * <li>if Qname of <code>typedef</code> is null</li>
+ * </ul>
+ */
+ public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
+ final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode, final SchemaContext
+ schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+ Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
+ Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
+ Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
+
+ final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
+ final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
+ final Module module = findParentModule(schemaContext, parentNode);
+
+ final GeneratedTOBuilderImpl unionGenTOBuilder;
+ if (typeDefName != null && !typeDefName.isEmpty()) {
+ final String typeName = BindingMapping.getClassName(typeDefName);
+ unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ unionGenTOBuilder.setDescription(typedefDescription);
+ unionGenTOBuilder.setReference(typedef.getReference());
+ unionGenTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot());
+ unionGenTOBuilder.setModuleName(module.getName());
+ } else {
+ unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
+ }
+
+ generatedTOBuilders.add(unionGenTOBuilder);
+ unionGenTOBuilder.setIsUnion(true);
+ final List<String> regularExpressions = new ArrayList<>();
+ for (final TypeDefinition<?> unionType : unionTypes) {
+ final String unionTypeName = unionType.getQName().getLocalName();
+ if (unionType.getBaseType() != null) {
+ resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
+ parentNode, schemaContext, genTypeDefsContextMap);
+ } else if (unionType instanceof UnionTypeDefinition) {
+ generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
+ basePackageName, parentNode, schemaContext, genTypeDefsContextMap));
+ } else if (unionType instanceof EnumTypeDefinition) {
+ final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
+ unionTypeName, unionGenTOBuilder);
+ updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
+ } else {
+ final Type javaType = javaTypeForSchemaDefType(unionType, parentNode, null, schemaContext,
+ genTypeDefsContextMap);
+ updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
+ }
+ }
+ if (!regularExpressions.isEmpty()) {
+ addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
+ }
+
+ //storeGenTO(typedef, unionGenTOBuilder, parentNode);
+
+ return generatedTOBuilders;
}
public Map<Module, Set<Type>> getAdditionalTypes() {
return additionalTypes;
}
+ public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
+ if (!Strings.isNullOrEmpty(units)) {
+ to.addConstant(Types.STRING, "Units", "\"" + units + "\"");
+ GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
+ prop.setReturnType(Types.STRING);
+ to.addToStringProperty(prop);
+ }
+ }
+
+ private Type javaTypeForSchemaDefType(final TypeDefinition<?> typeDefinition, final SchemaNode
+ parentNode, final Restrictions r, final SchemaContext schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+ Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
+ String typedefName = typeDefinition.getQName().getLocalName();
+ Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
+
+ // Deal with base types
+ if (typeDefinition.getBaseType() == null) {
+ // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
+ // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
+ // a base type which holds these constraints.
+ if (typeDefinition instanceof DecimalTypeDefinition) {
+ final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
+ if (ret != null) {
+ return ret;
+ }
+ }
+
+ // Deal with leafrefs/identityrefs
+ Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, schemaContext, genTypeDefsContextMap);
+ if (ret != null) {
+ return ret;
+ }
+
+ ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode);
+ if (ret == null) {
+ LOG.debug("Failed to resolve Java type for {}", typeDefinition);
+ }
+
+ return ret;
+ }
+
+ Type returnType = javaTypeForExtendedType(typeDefinition, schemaContext, genTypeDefsContextMap);
+ if (r != null && returnType instanceof GeneratedTransferObject) {
+ GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
+ Module module = findParentModule(schemaContext, parentNode);
+ String basePackageName = BindingMapping.getRootPackageName(module);
+ String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition
+ .getPath(), BindingNamespaceType.Typedef);
+ String genTOName = BindingMapping.getClassName(typedefName);
+ String name = packageName + "." + genTOName;
+ if (!(returnType.getFullyQualifiedName().equals(name))) {
+ returnType = shadedTOWithRestrictions(gto, r);
+ }
+ }
+ return returnType;
+ }
+
+ /**
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param module
+ * string with the name of the module for to which the
+ * <code>typedef</code> belongs
+ * @param typedef
+ * type definition of the node for which should be creted JAVA
+ * <code>Type</code> (usually generated TO)
+ * @return JAVA <code>Type</code> representation of <code>typedef</code> or
+ * <code>null</code> value if <code>basePackageName</code> or
+ * <code>modulName</code> or <code>typedef</code> or Q name of
+ * <code>typedef</code> equals <code>null</code>
+ */
+ private Type typedefToGeneratedType(final String basePackageName, final Module module, final
+ TypeDefinition<?> typedef, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, Map<Module,
+ Set<Type>> additionalTypes, final SchemaContext schemaContext) {
+ final String moduleName = module.getName();
+ final Date moduleRevision = module.getRevision();
+ if ((basePackageName != null) && (moduleName != null) && (typedef != null)) {
+ final String typedefName = typedef.getQName().getLocalName();
+ final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
+ if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
+ && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
+ Type returnType;
+ if (innerTypeDefinition.getBaseType() != null) {
+ returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
+ module.getName(), schemaContext, genTypeDefsContextMap);
+ } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
+ final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
+ (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef, schemaContext, genTypeDefsContextMap);
+ genTOBuilder.setTypedef(true);
+ genTOBuilder.setIsUnion(true);
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
+ returnType = genTOBuilder.toInstance();
+ // union builder
+ GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
+ genTOBuilder.getName() + "Builder");
+ unionBuilder.setIsUnionBuilder(true);
+ MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
+ method.setReturnType(returnType);
+ method.addParameter(Types.STRING, "defaultValue");
+ method.setAccessModifier(AccessModifier.PUBLIC);
+ method.setStatic(true);
+ Set<Type> types = additionalTypes.get(module);
+ if (types == null) {
+ types = Sets.newHashSet(unionBuilder.toInstance());
+ additionalTypes.put(module, types);
+ } else {
+ types.add(unionBuilder.toInstance());
+ }
+ } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
+ // enums are automatically Serializable
+ final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
+ // TODO units for typedef enum
+ returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef, schemaContext);
+ } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
+ final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
+ final GeneratedTOBuilder genTOBuilder =
+ provideGeneratedTOBuilderForBitsTypeDefinition(
+ basePackageName, bitsTypeDefinition, typedefName, module.getName());
+ genTOBuilder.setTypedef(true);
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
+ returnType = genTOBuilder.toInstance();
+ } else {
+ final Type javaType = javaTypeForSchemaDefType(innerTypeDefinition, typedef, null,
+ schemaContext, genTypeDefsContextMap);
+ returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
+ }
+ if (returnType != null) {
+ final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
+ Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
+ if (typeMap != null) {
+ if (typeMap.isEmpty()) {
+ typeMap = new HashMap<>(4);
+ modulesByDate.put(moduleRevision, typeMap);
+ }
+ typeMap.put(typedefName, returnType);
+ }
+ return returnType;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns JAVA <code>Type</code> for instances of the type
+ * <code>ExtendedType</code>.
+ *
+ * @param typeDefinition
+ * type definition which is converted to JAVA <code>Type</code>
+ * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
+ */
+ private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final SchemaContext
+ schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ final String typedefName = typeDefinition.getQName().getLocalName();
+ final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
+ Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, schemaContext, genTypeDefsContextMap);
+ if (returnType == null) {
+ if (baseTypeDef instanceof EnumTypeDefinition) {
+ final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
+ returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition, schemaContext);
+ } else {
+ final Module module = findParentModule(schemaContext, typeDefinition);
+ Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
+ if (module != null) {
+ final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
+ final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
+ if (genTOs != null) {
+ returnType = genTOs.get(typedefName);
+ }
+ if (returnType == null) {
+ returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
+ baseTypeDef, typeDefinition, r);
+ }
+ }
+ }
+ }
+ return returnType;
+ }
+
+ /**
+ * Returns JAVA <code>Type</code> for instances of the type
+ * <code>LeafrefTypeDefinition</code> or
+ * <code>IdentityrefTypeDefinition</code>.
+ *
+ * @param typeDefinition
+ * type definition which is converted to JAVA <code>Type</code>
+ * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
+ */
+ private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
+ final SchemaContext schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+ if (typeDefinition instanceof LeafrefTypeDefinition) {
+ final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
+ if (isLeafRefSelfReference(leafref, parentNode, schemaContext)) {
+ throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
+ " StackOverFlowError detected.");
+ }
+ return provideTypeForLeafref(leafref, parentNode, schemaContext, genTypeDefsContextMap);
+ } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
+ final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
+ return provideTypeForIdentityref(idref, schemaContext);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
+ *
+ * The path of <code>leafrefType</code> is followed to find referenced node
+ * and its <code>Type</code> is returned.
+ *
+ * @param leafrefType
+ * leafref type definition for which is the type sought
+ * @return JAVA <code>Type</code> of data schema node which is referenced in
+ * <code>leafrefType</code>
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>leafrefType</code> equal null</li>
+ * <li>if path statement of <code>leafrefType</code> equal null</li>
+ * </ul>
+ *
+ */
+ public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
+ final SchemaContext schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ Type returnType = null;
+ Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
+
+ Preconditions.checkArgument(leafrefType.getPathStatement() != null,
+ "The Path Statement for Leafref Type Definition cannot be NULL!");
+
+ final RevisionAwareXPath xpath = leafrefType.getPathStatement();
+ final String strXPath = xpath.toString();
+
+ if (strXPath != null) {
+ if (strXPath.indexOf('[') == -1) {
+ final Module module = findParentModule(schemaContext, parentNode);
+ Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
+
+ final SchemaNode dataNode;
+ if (xpath.isAbsolute()) {
+ dataNode = findDataSchemaNode(schemaContext, module, xpath);
+ } else {
+ dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
+ }
+ Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
+ strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName().getModule());
+
+ if (leafContainsEnumDefinition(dataNode)) {
+ returnType = referencedTypes.get(dataNode.getPath());
+ } else if (leafListContainsEnumDefinition(dataNode)) {
+ returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
+ } else {
+ returnType = resolveTypeFromDataSchemaNode(dataNode, schemaContext, genTypeDefsContextMap);
+ }
+ } else {
+ returnType = Types.typeForClass(Object.class);
+ }
+ }
+ Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
+ strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName().getModule());
+ return returnType;
+ }
+
+ /**
+ * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
+ * so then checks if it is of type <code>EnumTypeDefinition</code>.
+ *
+ * @param dataNode
+ * data schema node for which is checked if it is leaf and if it
+ * is of enum type
+ * @return boolean value
+ * <ul>
+ * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
+ * <li>false - other cases</li>
+ * </ul>
+ */
+ private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
+ if (dataNode instanceof LeafSchemaNode) {
+ final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
+ //CompatUtils is not used here anymore
+ if (leaf.getType() instanceof EnumTypeDefinition) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
+ * it so then checks if it is of type <code>EnumTypeDefinition</code>.
+ *
+ * @param dataNode
+ * data schema node for which is checked if it is leaflist and if
+ * it is of enum type
+ * @return boolean value
+ * <ul>
+ * <li>true - if <code>dataNode</code> is leaflist of type
+ * enumeration</li>
+ * <li>false - other cases</li>
+ * </ul>
+ */
+ private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
+ if (dataNode instanceof LeafListSchemaNode) {
+ final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
+ if (leafList.getType() instanceof EnumTypeDefinition) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Converts <code>dataNode</code> to JAVA <code>Type</code>.
+ *
+ * @param dataNode
+ * contains information about YANG type
+ * @return JAVA <code>Type</code> representation of <code>dataNode</code>
+ */
+ private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final SchemaContext schemaContext,
+ Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+ Type returnType = null;
+ if (dataNode != null) {
+ if (dataNode instanceof LeafSchemaNode) {
+ final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
+ //not using CompatUtils here anymore
+ final TypeDefinition<?> type = leaf.getType();
+ returnType = javaTypeForSchemaDefType(type, leaf, null, schemaContext, genTypeDefsContextMap);
+ } else if (dataNode instanceof LeafListSchemaNode) {
+ final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
+ returnType = javaTypeForSchemaDefType(leafList.getType(), leafList, null, schemaContext, genTypeDefsContextMap);
+ }
+ }
+ return returnType;
+ }
+
+ /**
+ * Seeks for identity reference <code>idref</code> the JAVA
+ * <code>type</code>.<br />
+ * <br />
+ *
+ * <i>Example:<br />
+ * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
+ * then returning type is <b>{@code Class<? extends Idn>}</b></i>
+ *
+ * @param idref
+ * identityref type definition for which JAVA <code>Type</code>
+ * is sought
+ * @return JAVA <code>Type</code> of the identity which is refrenced through
+ * <code>idref</code>
+ */
+ private static Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref, final SchemaContext schemaContext) {
+ //TODO: incompatibility with Binding spec v2, get first or only one
+ QName baseIdQName = idref.getIdentities().iterator().next().getQName();
+ Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
+ baseIdQName.getRevision());
+ IdentitySchemaNode identity = null;
+ for (IdentitySchemaNode id : module.getIdentities()) {
+ if (id.getQName().equals(baseIdQName)) {
+ identity = id;
+ }
+ }
+ Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
+
+ final String basePackageName = BindingMapping.getRootPackageName(module);
+ final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath
+ (), BindingNamespaceType.Typedef);
+ final String genTypeName = BindingMapping.getClassName(identity.getQName());
+
+ Type baseType = Types.typeForClass(Class.class);
+ Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
+ return Types.parameterizedTypeFor(baseType, paramType);
+ }
+
+ /**
+ * Converts <code>typedef</code> to the generated TO builder.
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param typedef
+ * type definition from which is the generated TO builder created
+ * @return generated TO builder which contains data from
+ * <code>typedef</code> and <code>basePackageName</code>
+ */
+ private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
+
+ final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath
+ (), BindingNamespaceType.Typedef);
+ final String typeDefTOName = typedef.getQName().getLocalName();
+
+ if ((packageName != null) && (typeDefTOName != null)) {
+ final String genTOName = BindingMapping.getClassName(typeDefTOName);
+ final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+
+ newType.setDescription(typedefDescription);
+ newType.setReference(typedef.getReference());
+ newType.setSchemaPath((List) typedef.getPath().getPathFromRoot());
+ newType.setModuleName(moduleName);
+
+ return newType;
+ }
+ return null;
+ }
+
+ private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
+ GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
+ GeneratedTransferObject parent = gto.getSuperType();
+ if (parent != null) {
+ gtob.setExtendsType(parent);
+ }
+ gtob.setRestrictions(r);
+ for (GeneratedProperty gp : gto.getProperties()) {
+ GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
+ gpb.setValue(gp.getValue());
+ gpb.setReadOnly(gp.isReadOnly());
+ gpb.setAccessModifier(gp.getAccessModifier());
+ gpb.setReturnType(gp.getReturnType());
+ gpb.setFinal(gp.isFinal());
+ gpb.setStatic(gp.isStatic());
+ }
+ return gtob.toInstance();
+ }
+
+ /**
+ * Adds a new property with the name <code>propertyName</code> and with type
+ * <code>type</code> to <code>unonGenTransObject</code>.
+ *
+ * @param unionGenTransObject
+ * generated TO to which should be property added
+ * @param type
+ * JAVA <code>type</code> of the property which should be added
+ * to <code>unionGentransObject</code>
+ * @param propertyName
+ * string with name of property which should be added to
+ * <code>unionGentransObject</code>
+ */
+ private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
+ if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
+ final GeneratedPropertyBuilder propBuilder = unionGenTransObject
+ .addProperty(BindingMapping.getPropertyName(propertyName));
+ propBuilder.setReturnType(type);
+
+ unionGenTransObject.addEqualsIdentity(propBuilder);
+ unionGenTransObject.addHashIdentity(propBuilder);
+ unionGenTransObject.addToStringProperty(propBuilder);
+ }
+ }
+
+ /**
+ * Wraps code which handle case when union subtype is also of the type
+ * <code>UnionType</code>.
+ *
+ * In this case the new generated TO is created for union subtype (recursive
+ * call of method
+ * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
+ * String, SchemaNode, SchemaContext, Map)}
+ * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
+ * <code>parentUnionGenTOBuilder</code> is created property which type is
+ * equal to new generated TO.
+ *
+ * @param parentUnionGenTOBuilder
+ * generated TO builder to which is the property with the child
+ * union subtype added
+ * @param basePackageName
+ * string with the name of the module package
+ * @param unionSubtype
+ * type definition which represents union subtype
+ * @return list of generated TO builders. The number of the builders can be
+ * bigger one due to recursive call of
+ * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
+ */
+ private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder
+ parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName,
+ final SchemaNode parentNode, final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
+ final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
+ basePackageName, unionSubtype, newTOBuilderName, parentNode, schemaContext, genTypeDefsContextMap);
+
+ final GeneratedPropertyBuilder propertyBuilder;
+ propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
+ propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
+ parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
+ parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
+
+ return subUnionGenTOBUilders;
+ }
+
+ /**
+ * Converts output list of generated TO builders to one TO builder (first
+ * from list) which contains the remaining builders as its enclosing TO.
+ *
+ * @param basePackageName
+ * string with name of package to which the module belongs
+ * @param typedef
+ * type definition which should be of type
+ * <code>UnionTypeDefinition</code>
+ * @param typeDefName
+ * string with name for generated TO
+ * @return generated TO builder with the list of enclosed generated TO
+ * builders
+ */
+ private GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
+ final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode, final SchemaContext
+ schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
+ typedef, typeDefName, parentNode, schemaContext, genTypeDefsContextMap);
+ Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
+
+ final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
+ for (GeneratedTOBuilder genTOBuilder : builders) {
+ resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
+ }
+
+ resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
+ return resultTOBuilder;
+ }
+
+ /**
+ * Wraps code which handle case when union subtype is of the type
+ * <code>ExtendedType</code>.
+ *
+ * If TO for this type already exists it is used for the creation of the
+ * property in <code>parentUnionGenTOBuilder</code>. In other case the base
+ * type is used for the property creation.
+ *
+ * @param parentUnionGenTOBuilder
+ * generated TO builder in which new property is created
+ * @param unionSubtype
+ * type definition of the <code>ExtendedType</code> type which
+ * represents union subtype
+ * @param regularExpressions
+ * list of strings with the regular expressions
+ * @param parentNode
+ * parent Schema Node for Extended Subtype
+ *
+ */
+ private static void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final
+ TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode,
+ final SchemaContext schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ final String unionTypeName = unionSubtype.getQName().getLocalName();
+ final Type genTO = findGenTO(unionTypeName, unionSubtype, schemaContext, genTypeDefsContextMap);
+ if (genTO != null) {
+ updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
+ } else {
+ final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
+ if (unionTypeName.equals(baseType.getQName().getLocalName())) {
+ final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
+ parentNode);
+ if (javaType != null) {
+ updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
+ }
+ }
+ if (baseType instanceof StringTypeDefinition) {
+ regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
+ }
+ }
+ }
+
+ /**
+ * Returns string which contains the same value as <code>name</code> but
+ * integer suffix is incremented by one. If <code>name</code> contains no
+ * number suffix then number 1 is added.
+ *
+ * @param name
+ * string with name of augmented node
+ * @return string with the number suffix incremented by one (or 1 is added)
+ */
+ private static String provideAvailableNameForGenTOBuilder(final String name) {
+ Matcher mtch = NUMBERS_PATTERN.matcher(name);
+ if (mtch.find()) {
+ final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
+ return name.substring(0, mtch.start()) + newSuffix;
+ } else {
+ return name + 1;
+ }
+ }
+
+ /**
+ * Searches for generated TO for <code>searchedTypeDef</code> type
+ * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
+ *
+ * @param searchedTypeName
+ * string with name of <code>searchedTypeDef</code>
+ * @return generated TO for <code>searchedTypeDef</code> or
+ * <code>null</code> it it doesn't exist
+ */
+ private static Type findGenTO(final String searchedTypeName, final SchemaNode parentNode,
+ final SchemaContext schemaContext, Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+
+ final Module typeModule = findParentModule(schemaContext, parentNode);
+ if (typeModule != null && typeModule.getName() != null) {
+ final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
+ final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
+ if (genTOs != null) {
+ return genTOs.get(searchedTypeName);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
+ * taken from <code>enumTypeDef</code>.
+ *
+ * @param enumTypeDef
+ * enumeration type definition is source of enumeration data for
+ * <code>typeBuilder</code>
+ * @param enumName
+ * string with the name of enumeration
+ * @param typeBuilder
+ * generated type builder to which is enumeration added
+ * @return enumeration type which contains enumeration data form
+ * <code>enumTypeDef</code>
+ * @throws IllegalArgumentException
+ * <ul>
+ * <li>if <code>enumTypeDef</code> equals null</li>
+ * <li>if enum values of <code>enumTypeDef</code> equal null</li>
+ * <li>if Q name of <code>enumTypeDef</code> equal null</li>
+ * <li>if name of <code>enumTypeDef</code> equal null</li>
+ * <li>if name of <code>typeBuilder</code> equal null</li>
+ * </ul>
+ *
+ */
+ private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
+ Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
+ Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
+ "Local Name in EnumTypeDefinition QName cannot be NULL!");
+ Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
+
+ final String enumerationName = BindingMapping.getClassName(enumName);
+
+ final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ enumBuilder.setDescription(enumTypedefDescription);
+ enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
+ return enumBuilder.toInstance(enumBuilder);
+ }
+
+ private static boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode,
+ final SchemaContext schemaContext) {
+ final SchemaNode leafRefValueNode;
+ final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
+ final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
+ .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
+
+ ///// skip leafrefs in augments - they're checked once augments are resolved
+ final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
+ boolean isAugmenting = false;
+ DataNodeContainer current = null;
+ DataSchemaNode dataChildByName;
+
+ while (iterator.hasNext() && !isAugmenting) {
+ final QName next = iterator.next();
+ if (current == null) {
+ dataChildByName = schemaContext.getDataChildByName(next);
+ } else {
+ dataChildByName = current.getDataChildByName(next);
+ }
+ if (dataChildByName != null) {
+ isAugmenting = dataChildByName.isAugmenting();
+ } else {
+ return false;
+ }
+ if (dataChildByName instanceof DataNodeContainer) {
+ current = (DataNodeContainer) dataChildByName;
+ }
+ }
+ if (isAugmenting) {
+ return false;
+ }
+ /////
+
+ Module parentModule = getParentModule(parentNode, schemaContext);
+ if (!leafRefStrippedXPath.isAbsolute()) {
+ leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
+ parentNode, leafRefStrippedXPath);
+ } else {
+ leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
+ }
+ return (leafRefValueNode != null) && leafRefValueNode.equals(parentNode);
+ }
+
+
}
import com.google.common.annotations.Beta;
import com.google.common.base.CharMatcher;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import com.google.common.collect.Iterables;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.Iterator;
+import java.util.List;
+import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
+import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
+import org.opendaylight.mdsal.binding.javav2.model.api.Type;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
+import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.TypeMemberBuilder;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
+import org.opendaylight.yangtools.yang.model.util.type.DecimalTypeBuilder;
/**
* Standard Util class that contains various method for converting
private static final CharMatcher LT_MATCHER = CharMatcher.is('<');
private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
+ private static final Comparator<TypeMemberBuilder<?>> SUID_MEMBER_COMPARATOR =
+ Comparator.comparing(TypeMemberBuilder::getName);
+
+ private static final Comparator<Type> SUID_NAME_COMPARATOR =
+ Comparator.comparing(Type::getFullyQualifiedName);
+
+ private static final Restrictions EMPTY_RESTRICTIONS = new Restrictions() {
+ @Override
+ public List<LengthConstraint> getLengthConstraints() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<PatternConstraint> getPatternConstraints() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<RangeConstraint> getRangeConstraints() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return true;
+ }
+ };
private BindingGeneratorUtil() {
throw new UnsupportedOperationException("Utility class");
}
+ /**
+ * Encodes angle brackets in yang statement description
+ * @param description description of a yang statement which is used to generate javadoc comments
+ * @return string with encoded angle brackets
+ */
+ public static String encodeAngleBrackets(final String description) {
+ String newDesc = description;
+ if (newDesc != null) {
+ newDesc = LT_MATCHER.replaceFrom(newDesc, "<");
+ newDesc = GT_MATCHER.replaceFrom(newDesc, ">");
+ }
+ return newDesc;
+ }
+
+ public static long computeDefaultSUID(final GeneratedTypeBuilderBase<?> to) {
+ final ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ try (final DataOutputStream dout = new DataOutputStream(bout)) {
+ dout.writeUTF(to.getName());
+ dout.writeInt(to.isAbstract() ? 3 : 7);
+
+ for (Type ifc : sortedCollection(SUID_NAME_COMPARATOR, to.getImplementsTypes())) {
+ dout.writeUTF(ifc.getFullyQualifiedName());
+ }
+
+ for (GeneratedPropertyBuilder gp : sortedCollection(SUID_MEMBER_COMPARATOR, to.getProperties())) {
+ dout.writeUTF(gp.getName());
+ }
+
+ for (MethodSignatureBuilder m : sortedCollection(SUID_MEMBER_COMPARATOR, to.getMethodDefinitions())) {
+ if (!(m.getAccessModifier().equals(AccessModifier.PRIVATE))) {
+ dout.writeUTF(m.getName());
+ dout.write(m.getAccessModifier().ordinal());
+ }
+ }
+
+ dout.flush();
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to hash object " + to, e);
+ }
+
+ final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray());
+ long hash = 0;
+ for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
+ hash = (hash << 8) | (hashBytes[i] & 0xFF);
+ }
+ return hash;
+ }
+
/**
* Creates package name from specified <code>basePackageName</code> (package
* name for module) and <code>schemaPath</code>.
return generateNormalizedPackageName(basePackageName, pathFromRoot, size, namespaceType);
}
+ public static Restrictions getRestrictions(final TypeDefinition<?> type) {
+ if (type == null || type.getBaseType() == null) {
+ if (type instanceof DecimalTypeDefinition) {
+ final DecimalTypeDefinition decimal = (DecimalTypeDefinition) type;
+ final DecimalTypeBuilder tmpBuilder = BaseTypes.decimalTypeBuilder(decimal.getPath());
+ tmpBuilder.setFractionDigits(decimal.getFractionDigits());
+ final DecimalTypeDefinition tmp = tmpBuilder.build();
+
+ if (!tmp.getRangeConstraints().equals(decimal.getRangeConstraints())) {
+ return new Restrictions() {
+ @Override
+ public boolean isEmpty() {
+ return false;
+ }
+
+ @Override
+ public List<RangeConstraint> getRangeConstraints() {
+ return decimal.getRangeConstraints();
+ }
+
+ @Override
+ public List<PatternConstraint> getPatternConstraints() {
+ return ImmutableList.of();
+ }
+
+ @Override
+ public List<LengthConstraint> getLengthConstraints() {
+ return ImmutableList.of();
+ }
+ };
+ }
+ }
+
+ return EMPTY_RESTRICTIONS;
+ }
+
+ final List<LengthConstraint> length;
+ final List<PatternConstraint> pattern;
+ final List<RangeConstraint> range;
+
+ /*
+ * Take care of extended types.
+ *
+ * Other types which support constraints are check afterwards. There is a slight twist with them, as returned
+ * constraints are the effective view, e.g. they are inherited from base type. Since the constraint is already
+ * enforced by the base type, we want to skip them and not perform duplicate checks.
+ *
+ * We end up emitting ConcreteType instances for YANG base types, which leads to their constraints not being
+ * enforced (most notably decimal64). Therefore we need to make sure we do not strip the next-to-last
+ * restrictions.
+ */
+ if (type instanceof BinaryTypeDefinition) {
+ final BinaryTypeDefinition binary = (BinaryTypeDefinition)type;
+ final BinaryTypeDefinition base = binary.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ length = currentOrEmpty(binary.getLengthConstraints(), base.getLengthConstraints());
+ } else {
+ length = binary.getLengthConstraints();
+ }
+
+ pattern = ImmutableList.of();
+ range = ImmutableList.of();
+ } else if (type instanceof DecimalTypeDefinition) {
+ length = ImmutableList.of();
+ pattern = ImmutableList.of();
+
+ final DecimalTypeDefinition decimal = (DecimalTypeDefinition)type;
+ final DecimalTypeDefinition base = decimal.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ range = currentOrEmpty(decimal.getRangeConstraints(), base.getRangeConstraints());
+ } else {
+ range = decimal.getRangeConstraints();
+ }
+ } else if (type instanceof IntegerTypeDefinition) {
+ length = ImmutableList.of();
+ pattern = ImmutableList.of();
+
+ final IntegerTypeDefinition integer = (IntegerTypeDefinition)type;
+ final IntegerTypeDefinition base = integer.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ range = currentOrEmpty(integer.getRangeConstraints(), base.getRangeConstraints());
+ } else {
+ range = integer.getRangeConstraints();
+ }
+ } else if (type instanceof StringTypeDefinition) {
+ final StringTypeDefinition string = (StringTypeDefinition)type;
+ final StringTypeDefinition base = string.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ length = currentOrEmpty(string.getLengthConstraints(), base.getLengthConstraints());
+ } else {
+ length = string.getLengthConstraints();
+ }
+
+ pattern = uniquePatterns(string);
+ range = ImmutableList.of();
+ } else if (type instanceof UnsignedIntegerTypeDefinition) {
+ length = ImmutableList.of();
+ pattern = ImmutableList.of();
+
+ final UnsignedIntegerTypeDefinition unsigned = (UnsignedIntegerTypeDefinition)type;
+ final UnsignedIntegerTypeDefinition base = unsigned.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ range = currentOrEmpty(unsigned.getRangeConstraints(), base.getRangeConstraints());
+ } else {
+ range = unsigned.getRangeConstraints();
+ }
+ } else {
+ length = ImmutableList.of();
+ pattern = ImmutableList.of();
+ range = ImmutableList.of();
+ }
+
+ // Now, this may have ended up being empty, too...
+ if (length.isEmpty() && pattern.isEmpty() && range.isEmpty()) {
+ return EMPTY_RESTRICTIONS;
+ }
+
+ // Nope, not empty allocate a holder
+ return new Restrictions() {
+ @Override
+ public List<RangeConstraint> getRangeConstraints() {
+ return range;
+ }
+ @Override
+ public List<PatternConstraint> getPatternConstraints() {
+ return pattern;
+ }
+ @Override
+ public List<LengthConstraint> getLengthConstraints() {
+ return length;
+ }
+ @Override
+ public boolean isEmpty() {
+ return false;
+ }
+ };
+ }
+
/**
* Creates package name from specified <code>basePackageName</code> (package
* name for module) and <code>schemaPath</code> which crosses an augmentation.
return generateNormalizedPackageName(basePackageName, pathFromRoot, size, null);
}
+ private static final ThreadLocal<MessageDigest> SHA1_MD = new ThreadLocal<MessageDigest>() {
+ @Override
+ protected MessageDigest initialValue() {
+ try {
+ return MessageDigest.getInstance("SHA");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("Failed to get a SHA digest provider", e);
+ }
+ }
+ };
+
private static String generateNormalizedPackageName(final String base, final Iterable<QName> path, final int
size, final BindingNamespaceType namespaceType) {
final StringBuilder builder = new StringBuilder(base);
return normalizedPackageName;
}
- /**
- * Encodes angle brackets in yang statement description
- * @param description description of a yang statement which is used to generate javadoc comments
- * @return string with encoded angle brackets
- */
- public static String encodeAngleBrackets(final String description) {
- String newDesc = description;
- if (newDesc != null) {
- newDesc = LT_MATCHER.replaceFrom(newDesc, "<");
- newDesc = GT_MATCHER.replaceFrom(newDesc, ">");
+ private static <T> Iterable<T> sortedCollection(final Comparator<? super T> comparator, final Collection<T> input) {
+ if (input.size() > 1) {
+ final List<T> ret = new ArrayList<>(input);
+ ret.sort(comparator);
+ return ret;
+ } else {
+ return input;
}
- return newDesc;
+ }
+
+ private static <T> List<T> currentOrEmpty(final List<T> current, final List<T> base) {
+ return current.equals(base) ? ImmutableList.of() : current;
+ }
+
+ private static List<PatternConstraint> uniquePatterns(final StringTypeDefinition type) {
+ final List<PatternConstraint> constraints = type.getPatternConstraints();
+ if (constraints.isEmpty()) {
+ return constraints;
+ }
+
+ final Builder<PatternConstraint> builder = ImmutableList.builder();
+ boolean filtered = false;
+ for (PatternConstraint c : constraints) {
+ if (containsConstraint(type.getBaseType(), c)) {
+ filtered = true;
+ } else {
+ builder.add(c);
+ }
+ }
+
+ return filtered ? builder.build() : constraints;
+ }
+
+ private static boolean containsConstraint(final StringTypeDefinition type, final PatternConstraint constraint) {
+ for (StringTypeDefinition wlk = type; wlk != null; wlk = wlk.getBaseType()) {
+ if (wlk.getPatternConstraints().contains(constraint)) {
+ return true;
+ }
+ }
+
+ return false;
}
//TODO: further implementation of static util methods...