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 static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.RangeSet;
14 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
15 import org.opendaylight.yangtools.yang.data.api.codec.StringCodec;
16 import org.opendaylight.yangtools.yang.data.api.codec.YangInvalidValueException;
17 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
18 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
21 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
24 public class StringStringCodec extends TypeDefinitionAwareCodec<String, StringTypeDefinition>
25 implements StringCodec<String> {
26 private final LengthConstraint lengthConstraint;
28 StringStringCodec(final StringTypeDefinition typeDef) {
29 super(requireNonNull(typeDef), String.class);
30 lengthConstraint = typeDef.getLengthConstraint().orElse(null);
33 public static StringStringCodec from(final StringTypeDefinition normalizedType) {
34 return normalizedType.getPatternConstraints().isEmpty() ? new StringStringCodec(normalizedType)
35 : new StringPatternCheckingCodec(normalizedType);
39 protected final String deserializeImpl(final String stringRepresentation) {
40 validate(stringRepresentation);
41 return stringRepresentation;
45 protected final String serializeImpl(final String data) {
49 void validate(final String str) {
50 if (lengthConstraint != null) {
51 final RangeSet<Integer> ranges = lengthConstraint.getAllowedRanges();
52 if (!ranges.contains(str.length())) {
53 throw new YangInvalidValueException(ErrorType.PROTOCOL, lengthConstraint,
54 "String " + str + " does not match allowed lengths " + ranges);