From Null-pointer
package gamesys.cognos.camel;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.EnumSet;
public enum ByteSize {
BYTE("b"),
KILO("kb"),
MEGA("mb"),
GIGA("gb");
private final String symbol;
private static final int MULTIPLIER = 1024;
ByteSize(String symbol) {
this.symbol = symbol;
}
static double multiply(double d) {
return d * MULTIPLIER;
}
static double divide(double d) {
return d / MULTIPLIER;
}
public static double convert(String source, ByteSize target) {
double d = 0;
EnumSet<ByteSize> allSizes = EnumSet.allOf(ByteSize.class);
ByteSize sourceSize = ByteSize.BYTE;
String lower = source.toLowerCase();
for (ByteSize size : allSizes) {
if (lower.contains(size.symbol)) {
sourceSize = size;
}
}
int range = target.ordinal() - sourceSize.ordinal();
NumberFormat nf = NumberFormat.getNumberInstance();
try {
Number number = nf.parse(source);
d = number.doubleValue();
if (range > 0) {
for (int i = 0; i < range; i++) {
d = ByteSize.divide(d);
}
} else if (range < 0) {
for (int i = 0; i > range; i--) {
d = ByteSize.multiply(d);
}
}
} catch (ParseException ignore) {
}
return d;
}
}
Unit test
package gamesys.cognos.camel.route;
import gamesys.cognos.camel.ByteSize;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class ByteSizeUTest {
@Test
public void testConvert() throws Exception {
assertEquals(1d, ByteSize.convert("1024", ByteSize.KILO));
assertEquals(1d, ByteSize.convert("1024b", ByteSize.KILO));
assertEquals(1d, ByteSize.convert("1048576b", ByteSize.MEGA));
assertEquals(1d, ByteSize.convert("1,048,576b", ByteSize.MEGA));
assertEquals(1048576d, ByteSize.convert("1mb", ByteSize.BYTE));
assertEquals(10240d, ByteSize.convert("10kb", ByteSize.BYTE));
assertEquals(1024d, ByteSize.convert("1GB", ByteSize.MEGA));
assertEquals(1d, ByteSize.convert("1,024MB", ByteSize.GIGA));
assertEquals(1024d, ByteSize.convert("1024kb", ByteSize.KILO));
}
}