a811428146f5e8102c52b6b310f0a78403795615
[yangtools.git] / yang / 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
9 package org.opendaylight.yangtools.yang.data.impl.codec;
10
11 import com.google.common.base.Optional;
12 import com.google.common.io.BaseEncoding;
13 import java.util.Objects;
14 import org.opendaylight.yangtools.yang.data.api.codec.UnionCodec;
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;
19
20 final class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition>
21         implements UnionCodec<String> {
22
23     private static final Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
24
25     private UnionStringCodec(final Optional<UnionTypeDefinition> typeDef) {
26         super(typeDef, Object.class);
27     }
28
29     static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
30         return new UnionStringCodec(Optional.fromNullable(normalizedType));
31     }
32
33     @Override
34     public String serialize(final Object data) {
35         if (data instanceof byte[]) {
36             return BaseEncoding.base64().encode((byte[]) data);
37         }
38         return Objects.toString(data, "");
39     }
40
41     @Override
42     @SuppressWarnings("checkstyle:illegalCatch")
43     public Object deserialize(final String stringRepresentation) {
44
45         if (!getTypeDefinition().isPresent()) {
46             return stringRepresentation;
47         }
48
49         for (final TypeDefinition<?> type : getTypeDefinition().get().getTypes()) {
50             final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwareCodec = from(type);
51             if (typeAwareCodec == null) {
52                 /*
53                  * This is a type for which we have no codec (eg identity ref) so we'll say it's
54                  * valid
55                  */
56                 return stringRepresentation;
57             }
58
59             try {
60                 return typeAwareCodec.deserialize(stringRepresentation);
61             } catch (final Exception e) {
62                 LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e);
63                 // invalid - try the next union type.
64             }
65         }
66
67         throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");
68     }
69 }