3053b1af96bf99d0b718692a873252501df0a455
[yangtools.git] / data / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / UnionStringCodec.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec;
9
10 import static java.util.Objects.requireNonNull;
11
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;
18
19 final class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition>
20         implements UnionCodec<String> {
21     private static final Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
22
23     UnionStringCodec(final UnionTypeDefinition typeDef) {
24         super(requireNonNull(typeDef), Object.class);
25     }
26
27     static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
28         return new UnionStringCodec(normalizedType);
29     }
30
31     @Override
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) {
37                 /*
38                  * This is a type for which we have no codec (eg identity ref) so we'll say it's
39                  * valid
40                  */
41                 return stringRepresentation;
42             }
43
44             try {
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.
49             }
50         }
51
52         throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");
53     }
54
55     @Override
56     protected String serializeImpl(final Object data) {
57         return data instanceof byte[] ? Base64.getEncoder().encodeToString((byte[]) data) : data.toString();
58     }
59 }