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
8 package org.opendaylight.yangtools.yang.data.util;
10 import static java.util.Objects.requireNonNull;
12 import org.opendaylight.yangtools.concepts.AbstractIllegalArgumentCodec;
13 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
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 extends AbstractIllegalArgumentCodec<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 IllegalArgumentCodec<String, Object> codecFor(TypeDefinition<?> type);
34 @SuppressWarnings("checkstyle:illegalCatch")
35 protected Object deserializeImpl(final String stringRepresentation) {
36 Object returnValue = null;
37 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
38 IllegalArgumentCodec<String, Object> codec = codecFor(type);
41 * This is a type for which we have no codec (eg identity ref) so we'll say it's valid
43 returnValue = stringRepresentation;
47 // FIXME: this hunting is a bit inefficient: we probably want to use Optional or something
48 return codec.deserialize(stringRepresentation);
49 } catch (final IllegalArgumentException e) {
50 LOG.debug("Value {} did not match representation for {}", stringRepresentation, type, e);
51 // invalid - try the next union type.
54 if (returnValue == null) {
55 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");
61 @SuppressWarnings("checkstyle:illegalCatch")
62 protected final String serializeImpl(final Object data) {
63 for (final TypeDefinition<?> type : typeDefinition.getTypes()) {
64 IllegalArgumentCodec<String, Object> codec = codecFor(type);
66 LOG.debug("no codec found for {}", type);
70 return codec.serialize(data);
71 } catch (final IllegalArgumentException e) {
72 LOG.debug("Data {} did not match for {}", data, type, e);
73 // invalid - try the next union type.
76 throw new IllegalArgumentException("Invalid data \"" + data + "\" for union type.");