BUG-865: remove TypeDefinitionAwareCodec nested classes
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / BooleanStringCodec.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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import org.opendaylight.yangtools.yang.data.api.codec.BooleanCodec;
13 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
14
15 final class BooleanStringCodec extends TypeDefinitionAwareCodec<Boolean, BooleanTypeDefinition>
16         implements BooleanCodec<String> {
17
18     BooleanStringCodec(final Optional<BooleanTypeDefinition> typeDef) {
19         super(typeDef, Boolean.class);
20     }
21
22     @Override
23     public final String serialize(final Boolean data) {
24         return data == null ? "" : data.toString();
25     }
26
27     @Override
28     public final Boolean deserialize(final String stringRepresentation) {
29         if (stringRepresentation == null) {
30             return null;
31         }
32         validate(stringRepresentation);
33         return Boolean.valueOf(stringRepresentation);
34     }
35
36     private static void validate(final String string) {
37         Preconditions.checkArgument("true".equalsIgnoreCase(string) || "false".equalsIgnoreCase(string),
38                 "Invalid value '%s' for boolean type. Allowed values are true and false", string);
39     }
40
41     static TypeDefinitionAwareCodec<?,BooleanTypeDefinition> from(final BooleanTypeDefinition normalizedType) {
42         return new BooleanStringCodec(Optional.fromNullable(normalizedType));
43     }
44 }