Merge branch 'master' of ../controller
[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 java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import org.eclipse.jdt.annotation.NonNull;
14 import org.opendaylight.yangtools.yang.data.api.codec.BooleanCodec;
15 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
16
17 /**
18  * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
19  */
20 @Beta
21 public final class BooleanStringCodec extends TypeDefinitionAwareCodec<Boolean, BooleanTypeDefinition>
22         implements BooleanCodec<String> {
23     private BooleanStringCodec(final @NonNull BooleanTypeDefinition typeDef) {
24         super(typeDef, Boolean.class);
25     }
26
27     public static @NonNull BooleanStringCodec from(final BooleanTypeDefinition normalizedType) {
28         return new BooleanStringCodec(requireNonNull(normalizedType));
29     }
30
31     @Override
32     protected Boolean deserializeImpl(final String product) {
33         // FIXME: should forbid "TRUE" ?
34         if ("true".equalsIgnoreCase(product)) {
35             return Boolean.TRUE;
36         } else if ("false".equalsIgnoreCase(product)) {
37             return Boolean.FALSE;
38         } else {
39             throw new IllegalArgumentException("Invalid value '" + product + "' for boolean type. Allowed values are "
40                     + "'true' and 'false'");
41         }
42     }
43
44     @Override
45     protected String serializeImpl(final Boolean input) {
46         return input.toString();
47     }
48 }