04ee96a53f4075c7a02d83a99ba59e8d3f8b14f0
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / type / BitsTypeBuilder.java
1 /*
2  * Copyright (c) 2015 Pantheon Technologies s.r.o. 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.yangtools.yang.model.util.type;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableMap.Builder;
13 import java.util.HashMap;
14 import java.util.Map;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
17 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
18 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
19
20 public final class BitsTypeBuilder extends TypeBuilder<BitsTypeDefinition> {
21     private final Builder<String, Bit> builder = ImmutableMap.builder();
22
23     BitsTypeBuilder(final SchemaPath path) {
24         super(null, path);
25     }
26
27     public BitsTypeBuilder addBit(@Nonnull final Bit item) {
28         Preconditions.checkArgument(item.getPosition() != null, "Bit %s has null position", item);
29
30         builder.put(item.getName(), item);
31         return this;
32     }
33
34     @Override
35     public BitsTypeDefinition build() {
36         final Map<String, Bit> map = builder.build();
37         final Map<Long, Bit> positionMap = new HashMap<>();
38
39         for (Bit b : map.values()) {
40             final Bit conflict = positionMap.put(b.getPosition(), b);
41             if (conflict != null) {
42                 throw new InvalidBitDefinitionException(b, "Bit %s conflicts on position with bit ", conflict);
43             }
44         }
45
46         return new BaseBitsType(getPath(), getUnknownSchemaNodes(), positionMap.values());
47     }
48 }