2 * Copyright (c) 2015 Pantheon Technologies s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.model.util.type;
10 import com.google.common.collect.ImmutableMap;
11 import com.google.common.collect.ImmutableMap.Builder;
12 import java.util.HashMap;
14 import javax.annotation.Nonnull;
15 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
16 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
17 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
19 public final class EnumerationTypeBuilder extends AbstractRestrictedTypeBuilder<EnumTypeDefinition> {
20 private final Builder<String, EnumPair> builder = ImmutableMap.builder();
22 EnumerationTypeBuilder(final SchemaPath path) {
26 EnumerationTypeBuilder(final EnumTypeDefinition baseType, final SchemaPath path) {
27 super(baseType, path);
30 public EnumerationTypeBuilder addEnum(@Nonnull final EnumPair item) {
31 // in case we are dealing with a restricted enumeration type, validate if the enum is a subset of its base type
32 if (getBaseType() != null) {
33 validateRestrictedEnum(item);
36 builder.put(item.getName(), item);
41 private void validateRestrictedEnum(@Nonnull final EnumPair item) {
42 boolean isASubsetOfBaseEnums = false;
43 for (EnumPair baseTypeEnumPair : getBaseType().getValues()) {
44 if (item.getName().equals(baseTypeEnumPair.getName())) {
45 if (item.getValue() != baseTypeEnumPair.getValue()) {
46 throw new InvalidEnumDefinitionException(item, "Value of enum '%s' must be the same as the value"
47 + " of corresponding enum in the base enumeration type %s.", item.getName(),
48 getBaseType().getQName());
50 isASubsetOfBaseEnums = true;
55 if (!isASubsetOfBaseEnums) {
56 throw new InvalidEnumDefinitionException(item, "Enum '%s' is not a subset of its base enumeration type %s.",
57 item.getName(), getBaseType().getQName());
62 public EnumTypeDefinition buildType() {
63 final Map<String, EnumPair> map = builder.build();
64 final Map<Integer, EnumPair> positionMap = new HashMap<>();
66 for (EnumPair p : map.values()) {
67 final EnumPair conflict = positionMap.put(p.getValue(), p);
68 if (conflict != null) {
69 throw new InvalidEnumDefinitionException(p, "Bit %s conflicts on position with bit ", conflict);
73 if (getBaseType() == null) {
74 return new BaseEnumerationType(getPath(), getUnknownSchemaNodes(), map.values());
76 return new RestrictedEnumerationType(getBaseType(), getPath(), getUnknownSchemaNodes(), map.values());