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 com.google.common.collect.ImmutableList;
13 import java.util.ArrayList;
14 import java.util.Base64;
15 import java.util.List;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.yangtools.yang.data.api.codec.UnionCodec;
18 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 final class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition>
23 implements UnionCodec<String> {
24 private static final Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
26 private final ImmutableList<TypeDefinitionAwareCodec<Object, ?>> codecs;
28 private UnionStringCodec(final UnionTypeDefinition typeDef,
29 final ImmutableList<TypeDefinitionAwareCodec<Object, ?>> codecs) {
30 super(requireNonNull(typeDef), Object.class);
31 this.codecs = requireNonNull(codecs);
34 static @Nullable TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition typeDef) {
35 final var types = typeDef.getTypes();
36 final var builder = ImmutableList.<TypeDefinitionAwareCodec<Object, ?>>builderWithExpectedSize(types.size());
37 for (var type : types) {
38 final var codec = from(type);
40 LOG.debug("Cannot handle {} because of unhandled component {}", typeDef, type);
45 return new UnionStringCodec(typeDef, builder.build());
49 protected Object deserializeImpl(final String stringRepresentation) {
50 List<IllegalArgumentException> suppressed = null;
51 for (var codec : codecs) {
53 return codec.deserialize(stringRepresentation);
54 } catch (final IllegalArgumentException e) {
55 // invalid - try the next union type.
56 LOG.debug("Value {} did not match codec {}", stringRepresentation, codec, e);
57 if (suppressed == null) {
58 suppressed = new ArrayList<>();
64 final var ex = new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");
65 if (suppressed != null) {
66 suppressed.forEach(ex::addSuppressed);
72 protected String serializeImpl(final Object data) {
73 return data instanceof byte[] ? Base64.getEncoder().encodeToString((byte[]) data) : data.toString();