org.onos.yangtools.yang.data.impl.codec.BinaryStringCodec.java Source code

Java tutorial

Introduction

Here is the source code for org.onos.yangtools.yang.data.impl.codec.BinaryStringCodec.java

Source

/*
 * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.onos.yangtools.yang.data.impl.codec;

import com.google.common.base.Optional;
import com.google.common.io.BaseEncoding;
import javax.xml.bind.DatatypeConverter;
import org.onos.yangtools.yang.data.api.codec.BinaryCodec;
import org.onos.yangtools.yang.model.api.type.BinaryTypeDefinition;

class BinaryStringCodec extends TypeDefinitionAwareCodec<byte[], BinaryTypeDefinition>
        implements BinaryCodec<String> {

    protected BinaryStringCodec(final Optional<BinaryTypeDefinition> typeDef) {
        super(typeDef, byte[].class);
    }

    static TypeDefinitionAwareCodec<?, BinaryTypeDefinition> from(final BinaryTypeDefinition type) {
        return new BinaryStringCodec(Optional.fromNullable(type));
    }

    @Override
    public String serialize(final byte[] data) {
        return data == null ? "" : BaseEncoding.base64().encode(data);
    }

    @Override
    public byte[] deserialize(final String stringRepresentation) {
        return stringRepresentation == null ? null : DatatypeConverter.parseBase64Binary(stringRepresentation);
    }
}