ConfigHelper { public static long parseByteSize(String sizeString) throws InvalidConfigException { if (null == sizeString) return 0; long unit = 1L; Matcher m = BYTE_SIZE_PATTERN.matcher(sizeString); if (!m.matches()) throw new InvalidConfigException("invalid byte-size string: " + sizeString); if (1 < m.groupCount() && null != m.group(2) && 0 < m.group(2).length()) { char unitChar1 = m.group(2).charAt(0); switch (unitChar1) { case 'k': unit = 1000L; break; case 'K': unit = 1024L; break; case 'm': unit = 1000L * 1000L; break; case 'M': unit = 1024L * 1024L; break; case 'g': unit = 1000L * 1000L * 1000L; break; case 'G': unit = 1024L * 1024L * 1024L; break; case 't': unit = 1000L * 1000L * 1000L * 1000L; break; case 'T': unit = 1024L * 1024L * 1024L * 1024L; break; case 'p': unit = 1000L * 1000L * 1000L * 1000L * 1000L; break; case 'P': unit = 1024L * 1024L * 1024L * 1024L * 1024L; break; case 'e': unit = 1000L * 1000L * 1000L * 1000L * 1000L * 1000L; break; case 'E': unit = 1024L * 1024L * 1024L * 1024L * 1024L * 1024L; break; } } long value = Long.parseLong(m.group(1)); return unit * value; }  static long parseDuration(String durationStr, TimeUnit defaultUnit); static long parseByteSize(String sizeString); static final Pattern DURATION_PATTERN; static final Pattern BYTE_SIZE_PATTERN; }
@Test public void testParseByteSize() throws Exception { Assert.assertEquals(ConfigHelper.parseByteSize("999"), 999L); Assert.assertEquals(ConfigHelper.parseByteSize("123k"), 123000L); Assert.assertEquals(ConfigHelper.parseByteSize("345K"), 345L * 1024); Assert.assertEquals(ConfigHelper.parseByteSize("666m"), 666000000L); Assert.assertEquals(ConfigHelper.parseByteSize(" 1000 M "), 1024L * 1024000L); Assert.assertEquals(ConfigHelper.parseByteSize("4g"), 4000000000L); Assert.assertEquals(ConfigHelper.parseByteSize("8G"), 8L * 1024L * 1024L * 1024L); Assert.assertEquals(ConfigHelper.parseByteSize("1t"), 1000000000000L); Assert.assertEquals(ConfigHelper.parseByteSize("10 T"), 10L * 1024L * 1024L * 1024L * 1024L); Assert.assertEquals(ConfigHelper.parseByteSize("10p"), 10000000000000000L); Assert.assertEquals(ConfigHelper.parseByteSize("9P"), 9L * 1024L * 1024L * 1024L * 1024L * 1024); Assert.assertEquals(ConfigHelper.parseByteSize(" 1e "), 1000000000000000000L); Assert.assertEquals(ConfigHelper.parseByteSize(" 1E"), 1L * 1024L * 1024L * 1024L * 1024L * 1024L * 1024L); }
@Test public void testParseByteSizeInvalid() { try { ConfigHelper.parseByteSize(""); Assert.fail(); } catch (InvalidConfigException e) {} try { ConfigHelper.parseByteSize("1mega"); Assert.fail(); } catch (InvalidConfigException e) {} try { ConfigHelper.parseByteSize("100MB"); Assert.fail(); } catch (InvalidConfigException e) {} try { ConfigHelper.parseByteSize("1.5g"); Assert.fail(); } catch (InvalidConfigException e) {} try { ConfigHelper.parseByteSize("-12k"); Assert.fail(); } catch (InvalidConfigException e) {} }