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 com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ImmutableRangeSet;
14 import com.google.common.collect.Range;
15 import com.google.common.collect.RangeSet;
16 import com.google.common.collect.TreeRangeSet;
17 import com.google.common.io.BaseEncoding;
18 import java.util.Optional;
19 import javax.xml.bind.DatatypeConverter;
20 import org.opendaylight.yangtools.yang.data.api.codec.BinaryCodec;
21 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
22 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
25 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
28 public abstract class BinaryStringCodec extends TypeDefinitionAwareCodec<byte[], BinaryTypeDefinition>
29 implements BinaryCodec<String> {
30 private static final class Restricted extends BinaryStringCodec {
31 private final RangeSet<Integer> ranges;
33 Restricted(final BinaryTypeDefinition typeDef) {
36 final RangeSet<Integer> r = TreeRangeSet.create();
37 for (LengthConstraint c : typeDef.getLengthConstraints()) {
38 r.add(Range.closed(c.getMin().intValue(), c.getMax().intValue()));
41 ranges = ImmutableRangeSet.copyOf(r);
45 void validate(final byte[] value) {
46 checkArgument(ranges.contains(value.length), "Value length %s does not match constraints %s", value.length,
51 private static final class Unrestricted extends BinaryStringCodec {
52 Unrestricted(final BinaryTypeDefinition typeDef) {
57 void validate(final byte[] value) {
62 BinaryStringCodec(final BinaryTypeDefinition typeDef) {
63 super(Optional.of(typeDef), byte[].class);
66 public static BinaryStringCodec from(final BinaryTypeDefinition type) {
67 return type.getLengthConstraints().isEmpty() ? new Unrestricted(type) : new Restricted(type);
71 public String serialize(final byte[] data) {
72 return data == null ? "" : BaseEncoding.base64().encode(data);
76 public byte[] deserialize(final String stringRepresentation) {
77 if (stringRepresentation == null) {
81 final byte[] ret = DatatypeConverter.parseBase64Binary(stringRepresentation);
86 abstract void validate(byte[] value);