Reduce visibility of codec methods
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / AbstractIntegerStringCodec.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.data.impl.codec;
9
10 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.INT16_QNAME;
11 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.INT32_QNAME;
12 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.INT64_QNAME;
13 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.INT8_QNAME;
14 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.UINT16_QNAME;
15 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.UINT32_QNAME;
16 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.UINT64_QNAME;
17 import static org.opendaylight.yangtools.yang.model.util.BaseTypes.UINT8_QNAME;
18
19 import com.google.common.base.CharMatcher;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Preconditions;
22 import com.google.common.collect.Range;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.regex.Pattern;
27 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
28 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
29 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
30 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
31
32 abstract class AbstractIntegerStringCodec<N extends Number & Comparable<N>, T extends TypeDefinition<T>> extends TypeDefinitionAwareCodec<N, T>{
33
34     private static final Pattern INT_PATTERN = Pattern.compile("[+-]?[1-9][0-9]*$");
35     private static final Pattern HEX_PATTERN = Pattern.compile("[+-]?0[xX][0-9a-fA-F]+");
36     private static final Pattern OCT_PATTERN = Pattern.compile("[+-]?0[1-7][0-7]*$");
37
38     // For up to two characters, this is very fast
39     private static final CharMatcher X_MATCHER = CharMatcher.anyOf("xX");
40
41     private static final String INCORRECT_LEXICAL_REPRESENTATION = "Incorrect lexical representation of integer value: %s."
42             + "\nAn integer value can be defined as: "
43             + "\n  - a decimal number,"
44             + "\n  - a hexadecimal number (prefix 0x)," + "%n  - an octal number (prefix 0)."
45             + "\nSigned values are allowed. Spaces between digits are NOT allowed.";
46
47
48     private final List<Range<N>> rangeConstraints;
49
50     protected AbstractIntegerStringCodec(final Optional<T> typeDefinition, final List<RangeConstraint> constraints , final Class<N> outputClass) {
51         super(typeDefinition, outputClass);
52         if (constraints.isEmpty()) {
53             rangeConstraints = Collections.emptyList();
54         } else {
55             final List<Range<N>> builder = new ArrayList<>(constraints.size());
56             for (final RangeConstraint yangConstraint : constraints) {
57                 builder.add(createRange(yangConstraint.getMin(), yangConstraint.getMax()));
58             }
59             rangeConstraints = builder;
60         }
61     }
62
63     static TypeDefinitionAwareCodec<?, IntegerTypeDefinition> from(final IntegerTypeDefinition type) {
64         // FIXME: this is not necessary with yang.model.util.type
65         IntegerTypeDefinition baseType = type;
66         while (baseType.getBaseType() != null) {
67             baseType = baseType.getBaseType();
68         }
69
70         final Optional<IntegerTypeDefinition> typeOptional = Optional.of(type);
71
72         // FIXME: use DerivedTypes#isInt8() and friends
73         if (INT8_QNAME.equals(baseType.getQName())) {
74             return new Int8StringCodec(typeOptional);
75         } else if (INT16_QNAME.equals(baseType.getQName())) {
76             return new Int16StringCodec(typeOptional);
77         } else if (INT32_QNAME.equals(baseType.getQName())) {
78             return new Int32StringCodec(typeOptional);
79         } else if (INT64_QNAME.equals(baseType.getQName())) {
80             return new Int64StringCodec(typeOptional);
81         } else {
82             throw new IllegalArgumentException("Unsupported base type: " + baseType.getQName());
83         }
84     }
85
86     static TypeDefinitionAwareCodec<?, UnsignedIntegerTypeDefinition> from(final UnsignedIntegerTypeDefinition type) {
87         // FIXME: this is not necessary with yang.model.util.type
88         UnsignedIntegerTypeDefinition baseType = type;
89         while (baseType.getBaseType() != null) {
90             baseType = baseType.getBaseType();
91         }
92
93         final Optional<UnsignedIntegerTypeDefinition> typeOptional = Optional.of(type);
94
95         // FIXME: use DerivedTypes#isUint8() and friends
96         if (UINT8_QNAME.equals(baseType.getQName())) {
97             return new Uint8StringCodec(typeOptional);
98         } else if (UINT16_QNAME.equals(baseType.getQName())) {
99             return new Uint16StringCodec(typeOptional);
100         } else if (UINT32_QNAME.equals(baseType.getQName())) {
101             return new Uint32StringCodec(typeOptional);
102         } else if (UINT64_QNAME.equals(baseType.getQName())) {
103             return new Uint64StringCodec(typeOptional);
104         } else {
105             throw new IllegalArgumentException("Unsupported base type: " + baseType.getQName());
106         }
107     }
108
109     private Range<N> createRange(final Number yangMin, final Number yangMax) {
110         final N min = convertValue(yangMin);
111         final N max = convertValue(yangMax);
112         return Range.closed(min, max);
113     }
114
115     @Override
116     public final N deserialize(final String stringRepresentation) {
117         final int base = provideBase(stringRepresentation);
118         final N deserialized;
119         if (base == 16) {
120             deserialized = deserialize(normalizeHexadecimal(stringRepresentation),base);
121         } else {
122             deserialized = deserialize(stringRepresentation,base);
123         }
124         validate(deserialized);
125         return deserialized;
126     }
127
128
129     private void validate(final N value) {
130         if (rangeConstraints.isEmpty()) {
131             return;
132         }
133         for (final Range<N> constraint : rangeConstraints) {
134             if (constraint.contains(value)) {
135                 return;
136             }
137         }
138         throw new IllegalArgumentException("Value '" + value + "'  is not in required range " + rangeConstraints);
139     }
140
141     /**
142      * Deserializes value from supplied string representation
143      * is supplied radix.
144      *
145      * See {@link Integer#parseInt(String, int)} for in-depth
146      * description about string and radix relationship.
147      *
148      * @param stringRepresentation String representation
149      * @param radix numeric base.
150      * @return Deserialized value.
151      */
152     abstract N deserialize(String stringRepresentation, int radix);
153
154     abstract N convertValue(Number value);
155
156
157     protected static List<RangeConstraint> extractRange(final IntegerTypeDefinition type) {
158         if (type == null) {
159             return Collections.emptyList();
160         }
161         return type.getRangeConstraints();
162     }
163
164     protected static List<RangeConstraint> extractRange(final UnsignedIntegerTypeDefinition type) {
165         if (type == null) {
166             return Collections.emptyList();
167         }
168         return type.getRangeConstraints();
169     }
170
171     private static int provideBase(final String integer) {
172         Preconditions.checkArgument(integer != null, "String representing integer number cannot be NULL");
173
174         if (integer.length() == 1 && integer.charAt(0) == '0') {
175             return 10;
176         } else if (INT_PATTERN.matcher(integer).matches()) {
177             return 10;
178         } else if (HEX_PATTERN.matcher(integer).matches()) {
179             return 16;
180         } else if (OCT_PATTERN.matcher(integer).matches()) {
181             return 8;
182         } else {
183             throw new NumberFormatException(String.format(INCORRECT_LEXICAL_REPRESENTATION, integer));
184         }
185     }
186
187     private static String normalizeHexadecimal(final String hexInt) {
188         Preconditions.checkArgument(hexInt != null,
189                 "String representing integer number in Hexadecimal format cannot be NULL!");
190
191         return X_MATCHER.removeFrom(hexInt);
192     }
193 }