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;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import java.util.Base64;
15 import javax.xml.bind.DatatypeConverter;
16 import org.opendaylight.yangtools.yang.data.api.codec.BinaryCodec;
17 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
18 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
21 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
24 public abstract class BinaryStringCodec extends TypeDefinitionAwareCodec<byte[], BinaryTypeDefinition>
25 implements BinaryCodec<String> {
26 private static final class Restricted extends BinaryStringCodec {
27 private final LengthConstraint lengthConstraint;
29 Restricted(final BinaryTypeDefinition typeDef, final LengthConstraint lengthConstraint) {
31 this.lengthConstraint = requireNonNull(lengthConstraint);
35 void validate(final byte[] value) {
36 // FIXME: throw an exception capturing the constraint violation
37 checkArgument(lengthConstraint.getAllowedRanges().contains(value.length),
38 "Value length %s does not match constraint %s", value.length, lengthConstraint);
42 private static final class Unrestricted extends BinaryStringCodec {
43 Unrestricted(final BinaryTypeDefinition typeDef) {
48 void validate(final byte[] value) {
53 BinaryStringCodec(final BinaryTypeDefinition typeDef) {
54 super(requireNonNull(typeDef), byte[].class);
57 public static BinaryStringCodec from(final BinaryTypeDefinition type) {
58 final java.util.Optional<LengthConstraint> optConstraint = type.getLengthConstraint();
59 return optConstraint.isPresent() ? new Restricted(type, optConstraint.get()) : new Unrestricted(type);
63 public final byte[] deserializeImpl(final String product) {
64 final byte[] ret = DatatypeConverter.parseBase64Binary(product);
70 protected final String serializeImpl(final byte[] data) {
71 return Base64.getEncoder().encodeToString(data);
74 abstract void validate(byte[] value);