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
9 package org.opendaylight.yangtools.yang.data.impl.codec;
11 import com.google.common.base.Optional;
12 import com.google.common.io.BaseEncoding;
13 import java.util.Objects;
14 import org.opendaylight.yangtools.yang.data.api.codec.UnionCodec;
15 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
16 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
20 final class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition> implements UnionCodec<String> {
22 private final static Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
24 private UnionStringCodec(final Optional<UnionTypeDefinition> typeDef) {
25 super(typeDef, Object.class);
28 static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
29 return new UnionStringCodec(Optional.fromNullable(normalizedType));
33 public String serialize(final Object data) {
34 if (data instanceof byte[]) {
35 return BaseEncoding.base64().encode((byte[]) data);
37 return Objects.toString(data, "");
41 public Object deserialize(final String stringRepresentation) {
43 if (!getTypeDefinition().isPresent()) {
44 return stringRepresentation;
47 for (final TypeDefinition<?> type : getTypeDefinition().get().getTypes()) {
48 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwareCodec = from(type);
49 if (typeAwareCodec == null) {
51 * This is a type for which we have no codec (eg identity ref) so we'll say it's
54 return stringRepresentation;
58 typeAwareCodec.deserialize(stringRepresentation);
59 return stringRepresentation;
60 } catch (final Exception e) {
61 LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e);
62 // invalid - try the next union type.
66 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");