/* * 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.opendaylight.yangtools.yang.data.impl.codec; import com.google.common.base.Optional; import org.opendaylight.yangtools.yang.data.api.codec.UnionCodec; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class UnionStringCodec extends TypeDefinitionAwareCodec implements UnionCodec { private final static Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class); protected UnionStringCodec(final Optional typeDef) { super(typeDef, Object.class); } static TypeDefinitionAwareCodec from(final UnionTypeDefinition normalizedType) { return new UnionStringCodec(Optional.fromNullable(normalizedType)); } @Override public final String serialize(final Object data) { return data == null ? "" : data.toString(); } @Override public final Object deserialize(final String stringRepresentation) { if (!getTypeDefinition().isPresent()) { return stringRepresentation; } for (final TypeDefinition type : getTypeDefinition().get().getTypes()) { final TypeDefinitionAwareCodec> typeAwareCodec = from(type); if (typeAwareCodec == null) { /* * This is a type for which we have no codec (eg identity ref) so we'll say it's * valid */ return stringRepresentation; } try { typeAwareCodec.deserialize(stringRepresentation); return stringRepresentation; } catch (final Exception e) { LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e); // invalid - try the next union type. } } throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type."); } }