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