Define a feature-parent
[yangtools.git] / data / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / StringStringCodec.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 com.google.common.annotations.Beta;
11 import com.google.common.collect.RangeSet;
12 import org.opendaylight.yangtools.yang.common.ErrorType;
13 import org.opendaylight.yangtools.yang.data.api.codec.StringCodec;
14 import org.opendaylight.yangtools.yang.data.api.codec.YangInvalidValueException;
15 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
16 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
17
18 /**
19  * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
20  */
21 @Beta
22 public class StringStringCodec extends TypeDefinitionAwareCodec<String, StringTypeDefinition>
23         implements StringCodec<String> {
24     private final LengthConstraint lengthConstraint;
25
26     StringStringCodec(final StringTypeDefinition typeDef) {
27         super(String.class, typeDef);
28         lengthConstraint = typeDef.getLengthConstraint().orElse(null);
29     }
30
31     public static StringStringCodec from(final StringTypeDefinition normalizedType) {
32         return normalizedType.getPatternConstraints().isEmpty() ? new StringStringCodec(normalizedType)
33                 : new StringPatternCheckingCodec(normalizedType);
34     }
35
36     @Override
37     protected final String deserializeImpl(final String stringRepresentation) {
38         validate(stringRepresentation);
39         return stringRepresentation;
40     }
41
42     @Override
43     protected final String serializeImpl(final String data) {
44         return data;
45     }
46
47     void validate(final String str) {
48         if (lengthConstraint != null) {
49             final RangeSet<Integer> ranges = lengthConstraint.getAllowedRanges();
50             if (!ranges.contains(str.codePointCount(0, str.length()))) {
51                 throw new YangInvalidValueException(ErrorType.APPLICATION, lengthConstraint,
52                     "String " + str + " does not match allowed lengths " + ranges);
53             }
54         }
55     }
56 }