DataAdjustment.java [src/usda/weru/util/table] Revision: default  Date:
/*
 * DataAdjustment.java
 *
 * Created on June 21, 2006, 4:30 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package usda.weru.util.table;

import org.jdom.Element;

/**
 * Wrapper class for handling data adjustments.
 * @author Joseph Levin
 */
public class DataAdjustment implements XmlObject{
    private int c_operation = WepsTableEnum.NOT_FOUND;
    private double c_adjustment;

    
    /**
     * Attempt to apply this adjustment to the supplied Object.
     * @param o The Object to be adjusted.
     * @return The adjusted Object.
     */
    public Object adjust(Object o){
        if (o == null){
            return o;
        }
        //Get a double we can work with, strings are icky for numbers.
        double d;
        if (o instanceof Number){
            d = ((Number) o).doubleValue();
        }
        else{
            try{
                d = Double.parseDouble(o.toString());
            }
            catch(NumberFormatException nfe){
                return o;
            }
        }
        switch(c_operation){
            case WepsTableEnum.OPERATION_add:
                d = d + c_adjustment;
                break;
            case WepsTableEnum.OPERATION_subtract:    
                d = d - c_adjustment;
                break;
            case WepsTableEnum.OPERATION_multiply:
                d = d * c_adjustment;
                break;
            case WepsTableEnum.OPERATION_divide:                    
                if (c_adjustment == 0){
                    d = 0;
                    break;
                }
                d = d / c_adjustment;
                break;
            case WepsTableEnum.OPERATION_abs:
                d = Math.abs(d);
                break;
            case WepsTableEnum.NOT_FOUND:
                return o;
        }
        if (d == -0) d = 0;
        return d;
    }
    
    /**
     * Load the adjustment from a jdom Element.
     * @param node An org.jdom.Element containing adjustment information.
     */
    public void fromXml(Element node){
        if(node == null) return;
        
        String adjustmentText = node.getTextTrim();
        try{
            c_adjustment = Double.parseDouble(adjustmentText);
        }
        catch(NumberFormatException nfe){
            return;
        }
        String operationText = node.getAttributeValue(WepsTableEnum.XML_operation);
        c_operation = WepsTableEnum.getEnumFromTag(operationText);
        
    }
    
}