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
015package org.apache.hivemind.schema.rules;
016
017import org.apache.commons.logging.Log;
018import org.apache.commons.logging.LogFactory;
019import org.apache.hivemind.Element;
020import org.apache.hivemind.ErrorHandler;
021import org.apache.hivemind.schema.SchemaProcessor;
022import org.apache.hivemind.schema.Translator;
023import org.apache.hivemind.util.PropertyUtils;
024
025/**
026 * Used to set a property of an object to a literal value.
027 *
028 * @author Howard Lewis Ship
029 */
030public class SetPropertyRule extends BaseRule
031{
032    private static final Log LOG = LogFactory.getLog(SetPropertyRule.class);
033
034    private String _propertyName;
035    private String _value;
036    private Translator _smartTranslator;
037
038    public void begin(SchemaProcessor processor, Element element)
039    {
040        String value = RuleUtils.processText(processor, element, _value);
041
042        Object target = processor.peek();
043
044        try
045        {
046            if (_smartTranslator == null)
047                _smartTranslator = RuleUtils.getTranslator(processor, "smart");
048
049            Class propertyType = PropertyUtils.getPropertyType(target, _propertyName);
050
051            Object finalValue =
052                _smartTranslator.translate(
053                    processor.getContributingModule(),
054                    propertyType,
055                    value,
056                    element.getLocation());
057
058            PropertyUtils.write(target, _propertyName, finalValue);
059        }
060        catch (Exception ex)
061        {
062            ErrorHandler eh = processor.getContributingModule().getErrorHandler();
063
064            String message = RulesMessages.unableToSetProperty(_propertyName, target, ex);
065
066            eh.error(LOG, message, element.getLocation(), ex);
067        }
068
069    }
070
071    public void setPropertyName(String string)
072    {
073        _propertyName = string;
074    }
075
076    public void setValue(String string)
077    {
078        _value = string;
079    }
080
081    public String getPropertyName()
082    {
083        return _propertyName;
084    }
085
086    public String getValue()
087    {
088        return _value;
089    }
090
091}