001/*
002 * #%L
003 * GwtBootstrap3
004 * %%
005 * Copyright (C) 2015 GwtBootstrap3
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 * 
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 * 
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package gwt.material.design.client.base.validator;
021
022import com.google.gwt.text.shared.Parser;
023
024import java.text.ParseException;
025
026/**
027 * Parses boolean values from a {@link CharSequence}.
028 *
029 * @author Steven Jardine
030 */
031public class BooleanParser implements Parser<Boolean> {
032
033    private static BooleanParser instance;
034
035    /**
036     * @return the instance of the {@link BooleanParser}.
037     */
038    public static Parser<Boolean> instance() {
039        if (instance == null) {
040            instance = new BooleanParser();
041        }
042        return instance;
043    }
044
045    /**
046     * Constructor.
047     */
048    protected BooleanParser() {
049        super();
050    }
051
052    @Override
053    public Boolean parse(final CharSequence text) throws ParseException {
054        if (text != null) {
055            String value = text.toString();
056            if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("Yes")) {
057                return true;
058            }
059            try {
060                Integer i = Integer.valueOf(value);
061                return i != 0;
062            } catch (Exception e) {
063            }
064        }
065        return false;
066    }
067}