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 static java.util.Objects.requireNonNull;
13 import org.opendaylight.yangtools.concepts.Codec;
14 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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 public abstract class AbstractStringUnionCodec implements Codec<String, Object> {
21 private static final Logger LOG = LoggerFactory.getLogger(AbstractStringUnionCodec.class);
23 protected final DataSchemaNode schema;
24 protected final UnionTypeDefinition typeDefinition;
26 protected AbstractStringUnionCodec(final DataSchemaNode schema, final UnionTypeDefinition typeDefinition) {
27 this.schema = requireNonNull(schema);
28 this.typeDefinition = requireNonNull(typeDefinition);
31 protected abstract Codec<String, Object> codecFor(TypeDefinition<?> type);
34 @SuppressWarnings("checkstyle:illegalCatch")
35 public final String serialize(final Object data) {
36 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
37 Codec<String, Object> codec = codecFor(type);
39 LOG.debug("no codec found for {}", type);
43 return codec.serialize(data);
44 } catch (final Exception e) {
45 LOG.debug("Data {} did not match for {}", data, type, e);
46 // invalid - try the next union type.
49 throw new IllegalArgumentException("Invalid data \"" + data + "\" for union type.");
53 @SuppressWarnings("checkstyle:illegalCatch")
54 public Object deserialize(final String stringRepresentation) {
55 if (stringRepresentation == null) {
59 Object returnValue = null;
60 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
61 Codec<String, Object> codec = codecFor(type);
64 * This is a type for which we have no codec (eg identity ref) so we'll say it's
67 returnValue = stringRepresentation;
71 final Object deserialized = codec.deserialize(stringRepresentation);
72 if (deserialized != null) {
75 returnValue = stringRepresentation;
76 } catch (final Exception e) {
77 LOG.debug("Value {} did not matched representation for {}", stringRepresentation, type, e);
78 // invalid - try the next union type.
81 if (returnValue != null) {
84 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");