b05f7cb7fef0f6b1252580dee10f2e731c203fb9
[yangtools.git] / yang / yang-model-spi / src / main / java / org / opendaylight / yangtools / yang / model / spi / type / TypeBuilder.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.spi.type;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableList;
14 import java.util.Collection;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.yangtools.concepts.Builder;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
19 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
20
21 public abstract class TypeBuilder<T extends TypeDefinition<T>> implements Builder<T> {
22     private final ImmutableList.Builder<UnknownSchemaNode> unknownSchemaNodes = ImmutableList.builder();
23     private final @NonNull QName qname;
24     private final T baseType;
25
26     TypeBuilder(final T baseType, final QName qname) {
27         this.qname = requireNonNull(qname);
28         this.baseType = baseType;
29     }
30
31     /**
32      * Create a copy of specified {@link TypeDefinition} with specified {@link QName}.
33      *
34      * @param <T> Type definition type
35      * @param type Original type definition
36      * @param qname QName for the copy
37      * @return A copy of type definition
38      * @throws NullPointerException if any argument is null
39      * @throws IllegalArgumentException if {@code type} is not a recognised implementation
40      */
41     public static <T extends TypeDefinition<?>> @NonNull T copyTypeDefinition(final T type, final QName qname) {
42         if (qname.equals(type.getQName())) {
43             return type;
44         }
45         checkArgument(type instanceof AbstractTypeDefinition, "Unsupported type %s", type);
46         return (T) ((AbstractTypeDefinition<?>) type).bindTo(requireNonNull(qname));
47     }
48
49     final T getBaseType() {
50         return baseType;
51     }
52
53     final @NonNull QName getQName() {
54         return qname;
55     }
56
57     final @NonNull Collection<? extends UnknownSchemaNode> getUnknownSchemaNodes() {
58         return unknownSchemaNodes.build();
59     }
60
61     public final void addUnknownSchemaNode(final @NonNull UnknownSchemaNode node) {
62         unknownSchemaNodes.add(node);
63     }
64 }