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