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 @SuppressWarnings("checkstyle:illegalCatch")
34 public final String serialize(final Object data) {
35 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
36 Codec<String, Object> codec = codecFor(type);
38 LOG.debug("no codec found for {}", type);
42 return codec.serialize(data);
43 } catch (final Exception e) {
44 LOG.debug("Data {} did not match for {}", data, type, e);
45 // invalid - try the next union type.
48 throw new IllegalArgumentException("Invalid data \"" + data + "\" for union type.");
52 @SuppressWarnings("checkstyle:illegalCatch")
53 public Object deserialize(final String stringRepresentation) {
54 if (stringRepresentation == null) {
58 Object returnValue = null;
59 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
60 Codec<String, Object> codec = codecFor(type);
63 * This is a type for which we have no codec (eg identity ref) so we'll say it's
66 returnValue = stringRepresentation;
70 final Object deserialized = codec.deserialize(stringRepresentation);
71 if (deserialized != null) {
74 returnValue = stringRepresentation;
75 } catch (final Exception e) {
76 LOG.debug("Value {} did not matched representation for {}", stringRepresentation, type, e);
77 // invalid - try the next union type.
80 if (returnValue != null) {
83 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");