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 org.eclipse.jdt.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(final @NonNull 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 final EnumTypeDefinition base = getBaseType();
34 validateRestrictedEnum(item, base);
37 builder.put(item.getName(), item);
42 private static void validateRestrictedEnum(final @NonNull EnumPair item, final @NonNull EnumTypeDefinition base) {
43 boolean isASubsetOfBaseEnums = false;
44 for (EnumPair baseTypeEnumPair : base.getValues()) {
45 if (item.getName().equals(baseTypeEnumPair.getName())) {
46 if (item.getValue() != baseTypeEnumPair.getValue()) {
47 throw new InvalidEnumDefinitionException(item, "Value of enum '%s' must be the same as the value"
48 + " of corresponding enum in the base enumeration type %s.", item.getName(),
51 isASubsetOfBaseEnums = true;
56 if (!isASubsetOfBaseEnums) {
57 throw new InvalidEnumDefinitionException(item, "Enum '%s' is not a subset of its base enumeration type %s.",
58 item.getName(), base.getQName());
63 public EnumTypeDefinition buildType() {
64 final Map<String, EnumPair> map = builder.build();
65 final Map<Integer, EnumPair> positionMap = new HashMap<>();
67 for (EnumPair p : map.values()) {
68 final EnumPair conflict = positionMap.put(p.getValue(), p);
69 if (conflict != null) {
70 throw new InvalidEnumDefinitionException(p, "Enum '%s' conflicts on value with enum ", conflict);
74 return getBaseType() == null ? new BaseEnumerationType(getPath(), getUnknownSchemaNodes(), map.values())
75 : new RestrictedEnumerationType(getBaseType(), getPath(), getUnknownSchemaNodes(), map.values());