Cleanup use of Guava library
[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 static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import java.util.Objects;
14 import java.util.Optional;
15 import org.opendaylight.yangtools.yang.data.api.codec.BooleanCodec;
16 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
17
18 /**
19  * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
20  */
21 @Beta
22 public final class BooleanStringCodec extends TypeDefinitionAwareCodec<Boolean, BooleanTypeDefinition>
23         implements BooleanCodec<String> {
24
25     private BooleanStringCodec(final Optional<BooleanTypeDefinition> typeDef) {
26         super(typeDef, Boolean.class);
27     }
28
29     @Override
30     public String serialize(final Boolean data) {
31         return Objects.toString(data, "");
32     }
33
34     @Override
35     public Boolean deserialize(final String stringRepresentation) {
36         if (stringRepresentation == null) {
37             return null;
38         }
39         checkArgument("true".equalsIgnoreCase(stringRepresentation) || "false".equalsIgnoreCase(stringRepresentation),
40             "Invalid value '%s' for boolean type. Allowed values are true and false", stringRepresentation);
41         return Boolean.valueOf(stringRepresentation);
42     }
43
44     public static BooleanStringCodec from(final BooleanTypeDefinition normalizedType) {
45         return new BooleanStringCodec(Optional.of(normalizedType));
46     }
47 }