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