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.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableRangeSet;
13 import com.google.common.collect.Range;
14 import com.google.common.collect.RangeSet;
15 import com.google.common.collect.TreeRangeSet;
16 import com.google.common.io.BaseEncoding;
17 import javax.xml.bind.DatatypeConverter;
18 import org.opendaylight.yangtools.yang.data.api.codec.BinaryCodec;
19 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
20 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
22 abstract class BinaryStringCodec extends TypeDefinitionAwareCodec<byte[], BinaryTypeDefinition>
23 implements BinaryCodec<String> {
24 private static final class Restricted extends BinaryStringCodec {
25 private final RangeSet<Integer> ranges;
27 Restricted(final BinaryTypeDefinition typeDef) {
30 final RangeSet<Integer> r = TreeRangeSet.create();
31 for (LengthConstraint c : typeDef.getLengthConstraints()) {
32 r.add(Range.closed(c.getMin().intValue(), c.getMax().intValue()));
35 ranges = ImmutableRangeSet.copyOf(r);
39 void validate(final byte[] value) {
40 Preconditions.checkArgument(ranges.contains(value.length),
41 "Value length %s does not match constraints %s", value.length, ranges);
45 private static final class Unrestricted extends BinaryStringCodec {
46 Unrestricted(final BinaryTypeDefinition typeDef) {
51 void validate(final byte[] value) {
56 BinaryStringCodec(final BinaryTypeDefinition typeDef) {
57 super(Optional.of(typeDef), byte[].class);
60 static TypeDefinitionAwareCodec<?, BinaryTypeDefinition> from(final BinaryTypeDefinition type) {
61 return type.getLengthConstraints().isEmpty() ? new Unrestricted(type) : new Restricted(type);
65 public String serialize(final byte[] data) {
66 return data == null ? "" : BaseEncoding.base64().encode(data);
70 public byte[] deserialize(final String stringRepresentation) {
71 if (stringRepresentation == null) {
75 final byte[] ret = DatatypeConverter.parseBase64Binary(stringRepresentation);
80 abstract void validate(byte[] value);