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;
13 import java.util.TreeMap;
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.BitsTypeDefinition;
17 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
19 public final class BitsTypeBuilder extends AbstractRestrictedTypeBuilder<BitsTypeDefinition> {
20 private final Builder<String, Bit> builder = ImmutableMap.builder();
22 BitsTypeBuilder(final SchemaPath path) {
26 BitsTypeBuilder(final BitsTypeDefinition baseType, final SchemaPath path) {
27 super(baseType, path);
30 public BitsTypeBuilder addBit(final @NonNull Bit item) {
31 // in case we are dealing with a restricted bits type, validate if the bit is a subset of its base type
32 if (getBaseType() != null) {
33 validateRestrictedBit(item);
36 builder.put(item.getName(), item);
41 private void validateRestrictedBit(final @NonNull Bit item) {
42 boolean isASubsetOfBaseBits = false;
43 for (Bit baseTypeBit : getBaseType().getBits()) {
44 if (item.getName().equals(baseTypeBit.getName())) {
45 if (item.getPosition() != baseTypeBit.getPosition()) {
46 throw new InvalidBitDefinitionException(item, "Position of bit '%s' must be the same as the "
47 + "position of corresponding bit in the base bits type %s.", item.getName(),
48 getBaseType().getQName());
50 isASubsetOfBaseBits = true;
55 if (!isASubsetOfBaseBits) {
56 throw new InvalidBitDefinitionException(item, "Bit '%s' is not a subset of its base bits type %s.",
57 item.getName(), getBaseType().getQName());
62 public BitsTypeDefinition buildType() {
63 final Map<String, Bit> map = builder.build();
64 final Map<Long, Bit> positionMap = new TreeMap<>();
66 for (Bit b : map.values()) {
67 final Bit conflict = positionMap.put(b.getPosition(), b);
68 if (conflict != null) {
69 throw new InvalidBitDefinitionException(b, "Bit %s conflicts on position with bit ", conflict);
73 return getBaseType() == null ? new BaseBitsType(getPath(), getUnknownSchemaNodes(), positionMap.values())
74 : new RestrictedBitsType(getBaseType(), getPath(), getUnknownSchemaNodes(), positionMap.values());