All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.limetri.api.measure.format.AbstractPresenter Maven / Gradle / Ivy

/**
 * Copyright (C) 2008-2013 LimeTri. All rights reserved.
 *
 * AgroSense is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * There are special exceptions to the terms and conditions of the GPLv3 as it
 * is applied to this software, see the FLOSS License Exception
 * .
 *
 * AgroSense is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * AgroSense. If not, see .
 */

package eu.limetri.api.measure.format;

import eu.limetri.api.measure.MeasurementPresenter;
import static eu.limetri.api.measure.MeasurementPresenter.NO_DATA_PRESENTATION;
import java.text.NumberFormat;
import javax.measure.unit.Unit;
import javax.measure.unit.UnitFormat;

/**
 *
 * @author johan
 */
public abstract class AbstractPresenter implements MeasurementPresenter {
    
    @Override
    public String present(Number n, String unit) {
        return isNoData(n) ? NO_DATA_PRESENTATION : formatMeasure(n, unit);
    }
    
    // FIXME: decouple source attributes from presentation.
    protected boolean isNoData(Number n) {
        return n == null;
    }
    
    protected boolean canFormatUnit(String unit) {
        return unit != null && !unit.isEmpty();
    }
    
    protected String formatMeasure(Number n, String unit) {
        StringBuilder sb = new StringBuilder(formatValue(convertValue(n)));
        if (canFormatUnit(unit)) {
            sb.append(" ").append(formatUnit(unit));
        }
        return sb.toString();
    }
    
    protected String formatValue(Number n) {
        return NumberFormat.getInstance().format(n);
    }
    
    protected String formatUnit(String unit) {   
        //e.g. "m^+1*s^-2" to "m/s²"
        try {
            Unit u = Unit.valueOf(unit);
            return UnitFormat.getInstance().format(u);
        } catch (IllegalArgumentException e) {
            return unit;
        }
    }
    
    protected Number convertValue(Number n) {
        return n;
    }
    
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy