Extracted remaining codecs to protected classes.
[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 terms of the Eclipse
5  * Public License v1.0 which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec;
9
10 import com.google.common.base.Optional;
11 import org.opendaylight.yangtools.yang.data.api.codec.UnionCodec;
12 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
13 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 class UnionStringCodec extends TypeDefinitionAwareCodec<Object, UnionTypeDefinition> implements UnionCodec<String> {
18
19     private final static Logger LOG = LoggerFactory.getLogger(UnionStringCodec.class);
20
21     protected UnionStringCodec(final Optional<UnionTypeDefinition> typeDef) {
22         super(typeDef, Object.class);
23     }
24
25     static TypeDefinitionAwareCodec<?, UnionTypeDefinition> from(final UnionTypeDefinition normalizedType) {
26         return new UnionStringCodec(Optional.fromNullable(normalizedType));
27     }
28
29     @Override
30     public final String serialize(final Object data) {
31         return data == null ? "" : data.toString();
32     }
33
34     @Override
35     public final Object deserialize(final String stringRepresentation) {
36
37         if (!getTypeDefinition().isPresent()) {
38             return stringRepresentation;
39         }
40
41         for (final TypeDefinition<?> type : getTypeDefinition().get().getTypes()) {
42             final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwareCodec = from(type);
43             if (typeAwareCodec == null) {
44                 /*
45                  * This is a type for which we have no codec (eg identity ref) so we'll say it's
46                  * valid
47                  */
48                 return stringRepresentation;
49             }
50
51             try {
52                 typeAwareCodec.deserialize(stringRepresentation);
53                 return stringRepresentation;
54             } catch (final Exception e) {
55                 LOG.debug("Value {} did not matched representation for {}",stringRepresentation,type,e);
56                 // invalid - try the next union type.
57             }
58         }
59
60         throw new IllegalArgumentException("Invalid value \"" + stringRepresentation + "\" for union type.");
61     }
62 }