2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the terms of the Eclipse
5 * Public License v1.0 which accompanies this distribution, and is available at
6 * 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 org.opendaylight.yangtools.yang.data.api.codec.UnionCodec;
12 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
13 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
17 class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition> implements UnionCodec<String> {
19 private final static Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
21 protected UnionStringCodec(final Optional<UnionTypeDefinition> typeDef) {
22 super(typeDef, Object.class);
25 static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
26 return new UnionStringCodec(Optional.fromNullable(normalizedType));
30 public final String serialize(final Object data) {
31 return data == null ? "" : data.toString();
35 public final Object deserialize(final String stringRepresentation) {
37 if (!getTypeDefinition().isPresent()) {
38 return stringRepresentation;
41 for (final TypeDefinition<?> type : getTypeDefinition().get().getTypes()) {
42 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwareCodec = from(type);
43 if (typeAwareCodec == null) {
45 * This is a type for which we have no codec (eg identity ref) so we'll say it's
48 return stringRepresentation;
52 typeAwareCodec.deserialize(stringRepresentation);
53 return stringRepresentation;
54 } catch (final Exception e) {
55 LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e);
56 // invalid - try the next union type.
60 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");