2 * Copyright (c) 2015 Cisco Systems, Inc. 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.impl.codec;
10 import static java.util.Objects.requireNonNull;
12 import java.util.Base64;
13 import org.opendaylight.yangtools.yang.data.api.codec.UnionCodec;
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 final class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition>
20 implements UnionCodec<String> {
21 private static final Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
23 UnionStringCodec(final UnionTypeDefinition typeDef) {
24 super(requireNonNull(typeDef), Object.class);
27 static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
28 return new UnionStringCodec(normalizedType);
32 @SuppressWarnings("checkstyle:illegalCatch")
33 protected Object deserializeImpl(final String stringRepresentation) {
34 for (final TypeDefinition<?> type : getTypeDefinition().get().getTypes()) {
35 final TypeDefinitionAwareCodec<Object, ?> typeAwareCodec = from(type);
36 if (typeAwareCodec == null) {
38 * This is a type for which we have no codec (eg identity ref) so we'll say it's
41 return stringRepresentation;
45 return typeAwareCodec.deserialize(stringRepresentation);
46 } catch (final Exception e) {
47 LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e);
48 // invalid - try the next union type.
52 throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");
56 protected String serializeImpl(final Object data) {
57 return data instanceof byte[] ? Base64.getEncoder().encodeToString((byte[]) data) : data.toString();