2 * Copyright (c) 2015 Cisco Systems, Inc. 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.data.impl.codec;
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;
19 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
22 public class StringStringCodec extends TypeDefinitionAwareCodec<String, StringTypeDefinition>
23 implements StringCodec<String> {
24 private final LengthConstraint lengthConstraint;
26 StringStringCodec(final StringTypeDefinition typeDef) {
27 super(String.class, typeDef);
28 lengthConstraint = typeDef.getLengthConstraint().orElse(null);
31 public static StringStringCodec from(final StringTypeDefinition normalizedType) {
32 return normalizedType.getPatternConstraints().isEmpty() ? new StringStringCodec(normalizedType)
33 : new StringPatternCheckingCodec(normalizedType);
37 protected final String deserializeImpl(final String stringRepresentation) {
38 validate(stringRepresentation);
39 return stringRepresentation;
43 protected final String serializeImpl(final String data) {
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);