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

se.wfh.libs.common.web.converter.FileSizeConverter Maven / Gradle / Ivy

package se.wfh.libs.common.web.converter;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

@FacesConverter(forClass = Double.class, value = "wfh.FileSizeConverter")
public class FileSizeConverter implements Converter {
	private static final NumberFormat DOUBLE_FMT = new DecimalFormat();

	private static final String[] SUFFIXE = { " b", " KiB", " MiB", " GiB",
			" TiB", };

	public FileSizeConverter() {
		DOUBLE_FMT.setMinimumFractionDigits(2);
		DOUBLE_FMT.setMaximumFractionDigits(2);
	}

	@Override
	public Object getAsObject(final FacesContext context,
			final UIComponent component, final String value)
			throws ConverterException {
		String[] parts = value.split(" ");

		String tempVal = parts[0];
		String tempSuffix = " " + parts[1];
		int suffix = 0;

		for (int i = 0; i < SUFFIXE.length; i++) {
			if (tempSuffix.equals(SUFFIXE[i])) {
				suffix = i;
			}
		}

		Object obj;
		try {
			obj = DOUBLE_FMT.parseObject(tempVal);
		} catch (ParseException pex) {
			throw new ConverterException(pex);
		}

		double result = ((Number) obj).doubleValue();

		while (suffix > 0) {
			result *= 1024;
			suffix--;
		}

		return Double.valueOf(result);
	}

	@Override
	public String getAsString(final FacesContext context,
			final UIComponent component, final Object value) {
		short suffix = 0;
		double temp = 0;

		if (value != null) {
			if (value instanceof Double) {
				temp = (Double) value;
			} else {
				temp = ((Number) value).doubleValue();
			}
		}

		while (temp > 1050) {
			temp /= 1024;
			suffix++;
		}

		if (suffix > 0) {
			return DOUBLE_FMT.format(temp) + SUFFIXE[suffix];
		} else {
			return (long) temp + SUFFIXE[suffix];
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy