2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.codec;
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;
16 final class BooleanStringCodec extends TypeDefinitionAwareCodec<Boolean, BooleanTypeDefinition>
17 implements BooleanCodec<String> {
19 BooleanStringCodec(final Optional<BooleanTypeDefinition> typeDef) {
20 super(typeDef, Boolean.class);
24 public String serialize(final Boolean data) {
25 return Objects.toString(data, "");
29 public Boolean deserialize(final String stringRepresentation) {
30 if (stringRepresentation == null) {
33 validate(stringRepresentation);
34 return Boolean.valueOf(stringRepresentation);
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);
42 static TypeDefinitionAwareCodec<?,BooleanTypeDefinition> from(final BooleanTypeDefinition normalizedType) {
43 return new BooleanStringCodec(Optional.fromNullable(normalizedType));