001 // Copyright 2004, 2005 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.hivemind.schema.rules;
016
017 import java.util.Map;
018
019 import org.apache.hivemind.ApplicationRuntimeException;
020 import org.apache.hivemind.HiveMind;
021 import org.apache.hivemind.Location;
022 import org.apache.hivemind.internal.Module;
023 import org.apache.hivemind.schema.Translator;
024
025 /**
026 * Translates a string value to a boolean value. "true" and "false" are acceptible values.
027 * Other values are logged as errors and treated as false. Null is simply considered false.
028 *
029 * @author Howard Lewis Ship
030 */
031 public class BooleanTranslator implements Translator
032 {
033 private Boolean _defaultValue = Boolean.FALSE;
034
035 public BooleanTranslator()
036 {
037 }
038
039 /**
040 * Initializes the translator, recognizing key "default" as the
041 * default value for the translator when the input is blank.
042 */
043
044 public BooleanTranslator(String initializer)
045 {
046 Map m = RuleUtils.convertInitializer(initializer);
047
048 String defaultInit = (String) m.get("default");
049
050 if (defaultInit != null)
051 _defaultValue = Boolean.valueOf(defaultInit);
052 }
053
054 public Object translate(
055 Module contributingModule,
056 Class propertyType,
057 String inputValue,
058 Location location)
059 {
060 if (HiveMind.isBlank(inputValue))
061 return _defaultValue;
062
063 if (inputValue.equals("true"))
064 return Boolean.TRUE;
065
066 if (inputValue.equals("false"))
067 return Boolean.FALSE;
068
069 throw new ApplicationRuntimeException(
070 RulesMessages.invalidBooleanValue(inputValue),
071 location,
072 null);
073 }
074
075 }