2 * Copyright (c) 2016 Intel Corporation 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.util;
11 import com.google.common.base.Preconditions;
12 import org.opendaylight.yangtools.concepts.Codec;
13 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
14 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
15 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 public abstract class AbstractStringUnionCodec implements Codec<String, Object> {
20 private static final Logger LOG = LoggerFactory.getLogger(AbstractStringUnionCodec.class);
22 protected final DataSchemaNode schema;
23 protected final UnionTypeDefinition typeDefinition;
25 protected AbstractStringUnionCodec(final DataSchemaNode schema, final UnionTypeDefinition typeDefinition) {
26 this.schema = Preconditions.checkNotNull(schema);
27 this.typeDefinition = Preconditions.checkNotNull(typeDefinition);
30 protected abstract Codec<String, Object> codecFor(final TypeDefinition<?> type);
33 public final String serialize(final Object data) {
34 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
35 Codec<String, Object> codec = codecFor(type);
37 LOG.debug("no codec found for {}", type);
41 return codec.serialize(data);
42 } catch (final Exception e) {
43 LOG.debug("Data {} did not match for {}", data, type, e);
44 // invalid - try the next union type.
47 throw new IllegalArgumentException("Invalid data \"" + data + "\" for union type.");
51 public Object deserialize(final String stringRepresentation) {
52 if (stringRepresentation == null) {
56 Object returnValue = null;
57 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
58 Codec<String, Object> codec = codecFor(type);
61 * This is a type for which we have no codec (eg identity ref) so we'll say it's
64 returnValue = stringRepresentation;
68 final Object deserialized = codec.deserialize(stringRepresentation);
69 if (deserialized != null) {
72 returnValue = stringRepresentation;
73 } catch (final Exception e) {
74 LOG.debug("Value {} did not matched representation for {}", stringRepresentation, type, e);
75 // invalid - try the next union type.
78 if (returnValue != null) {
81 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");