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>
21 implements UnionCodec<String> {
23 private static final Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
25 private UnionStringCodec(final Optional<UnionTypeDefinition> typeDef) {
26 super(typeDef, Object.class);
29 static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
30 return new UnionStringCodec(Optional.fromNullable(normalizedType));
34 public String serialize(final Object data) {
35 if (data instanceof byte[]) {
36 return BaseEncoding.base64().encode((byte[]) data);
38 return Objects.toString(data, "");
42 @SuppressWarnings("checkstyle:illegalCatch")
43 public Object deserialize(final String stringRepresentation) {
45 if (!getTypeDefinition().isPresent()) {
46 return stringRepresentation;
49 for (final TypeDefinition<?> type : getTypeDefinition().get().getTypes()) {
50 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwareCodec = from(type);
51 if (typeAwareCodec == null) {
53 * This is a type for which we have no codec (eg identity ref) so we'll say it's
56 return stringRepresentation;
60 return typeAwareCodec.deserialize(stringRepresentation);
61 } catch (final Exception e) {
62 LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e);
63 // invalid - try the next union type.
67 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");