UnitUtils { public static @Nullable Unit<?> parseUnit(@Nullable String pattern) { if (pattern == null || pattern.isBlank()) { return null; } String unitSymbol = pattern; int lastBlankIndex = pattern.lastIndexOf(" "); if (lastBlankIndex >= 0) { unitSymbol = pattern.substring(lastBlankIndex).trim(); } if (!UNIT_PLACEHOLDER.equals(unitSymbol)) { if (UNIT_PERCENT_FORMAT_STRING.equals(unitSymbol)) { return SmartHomeUnits.PERCENT; } try { Quantity<?> quantity = Quantities.getQuantity("1 " + unitSymbol); return quantity.getUnit(); } catch (IllegalArgumentException e) { LOGGER.debug("Unknown unit from pattern: {}", unitSymbol); } } return null; }  static @Nullable Class<? extends Quantity<?>> parseDimension(String dimension); static @Nullable String getDimensionName(Unit<?> unit); static @Nullable Unit<?> parseUnit(@Nullable String pattern); static boolean isDifferentMeasurementSystem(Unit<? extends Quantity<?>> thisUnit, Unit<?> thatUnit); static final String UNIT_PLACEHOLDER; static final String UNIT_PERCENT_FORMAT_STRING; }
@Test public void shouldParseUnitFromPattern() { assertThat(UnitUtils.parseUnit("%.2f °F"), is(ImperialUnits.FAHRENHEIT)); assertThat(UnitUtils.parseUnit("%.2f °C"), is(SIUnits.CELSIUS)); assertThat(UnitUtils.parseUnit("myLabel km"), is(KILO(SIUnits.METRE))); assertThat(UnitUtils.parseUnit("%.2f %%"), is(SmartHomeUnits.PERCENT)); assertThat(UnitUtils.parseUnit("myLabel %unit%"), is(nullValue())); assertThat(UnitUtils.parseUnit("%.2f kvarh"), is(SmartHomeUnits.KILOVAR_HOUR)); }
@Test public void testParsePureUnit() { assertThat(UnitUtils.parseUnit("DU"), is(SmartHomeUnits.DOBSON_UNIT)); assertThat(UnitUtils.parseUnit("°F"), is(ImperialUnits.FAHRENHEIT)); assertThat(UnitUtils.parseUnit("m"), is(SIUnits.METRE)); assertThat(UnitUtils.parseUnit("%"), is(SmartHomeUnits.PERCENT)); }