javax.measure.Quantity Java Examples

The following examples show how to use javax.measure.Quantity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommunicationManager.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private @Nullable QuantityType<?> convertToQuantityType(DecimalType originalType, Item item,
        @Nullable String acceptedItemType) {
    NumberItem numberItem = (NumberItem) item;

    // DecimalType command sent via a NumberItem with dimension:
    Class<? extends Quantity<?>> dimension = numberItem.getDimension();

    if (dimension == null) {
        // DecimalType command sent via a plain NumberItem w/o dimension.
        // We try to guess the correct unit from the channel-type's expected item dimension
        // or from the item's state description.
        dimension = getDimension(acceptedItemType);
    }

    if (dimension != null) {
        return numberItem.toQuantityType(originalType, dimension);
    }

    return null;
}
 
Example #2
Source File: ScalarTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link Scalar#multiply(Quantity)}, {@link Scalar#divide(Quantity)} and {@link Quantity#inverse()}.
 * Those tests depend on proper working of {@link Quantities#create(double, Unit)}, which depends in turn on
 * proper declarations of {@link ScalarFactory} in {@link Units} initialization.
 */
@Test
public void testMultiplyDivideQuantity() {
    final Quantity<Length> q1 = new Scalar.Length(24, Units.METRE);
    final Quantity<Time>   q2 = new Scalar.Time  ( 4, Units.SECOND);
    final Quantity<Speed>  q3 = q1.divide(q2).asType(Speed.class);
    assertSame  ("unit", Units.METRES_PER_SECOND, q3.getUnit());
    assertEquals("value", 6, q3.getValue().doubleValue(), STRICT);
    assertInstanceOf("Length/Time", Scalar.Speed.class, q3);

    final Quantity<Area> q4 = q1.multiply(q1).asType(Area.class);
    assertSame  ("unit", Units.SQUARE_METRE, q4.getUnit());
    assertEquals("value", 576, q4.getValue().doubleValue(), STRICT);
    assertInstanceOf("Length⋅Length", Scalar.Area.class, q4);

    final Quantity<Frequency> q5 = q2.inverse().asType(Frequency.class);
    assertSame  ("unit", Units.HERTZ, q5.getUnit());
    assertEquals("value", 0.25, q5.getValue().doubleValue(), STRICT);
    assertInstanceOf("1/Time", Scalar.Frequency.class, q5);
}
 
Example #3
Source File: UnitUtils.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Parses a String denoting a dimension (e.g. Length, Temperature, Mass,..) into a {@link Class} instance of an
 * interface from {@link javax.measure.Quantity}. The interfaces reside in {@code javax.measure.quantity} and
 * framework specific interfaces in {@code org.eclipse.smarthome.core.library.dimension}.
 *
 * @param dimension the simple name of an interface from the package {@code javax.measure.quantity} or
 *            {@code org.eclipse.smarthome.core.library.dimension}.
 * @return the {@link Class} instance of the interface or {@code null} if the given dimension is blank.
 * @throws IllegalArgumentException in case no class instance could be parsed from the given dimension.
 */
public static @Nullable Class<? extends Quantity<?>> parseDimension(String dimension) {
    if (StringUtils.isBlank(dimension)) {
        return null;
    }

    try {
        return dimensionClass(FRAMEWORK_DIMENSION_PREFIX, dimension);
    } catch (ClassNotFoundException e1) {
        try {
            return dimensionClass(JAVAX_MEASURE_QUANTITY_PREFIX, dimension);
        } catch (ClassNotFoundException e2) {
            throw new IllegalArgumentException(
                    "Error creating a dimension Class instance for name '" + dimension + "'.");
        }
    }
}
 
Example #4
Source File: UnitRegistry.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked by {@link Units} static class initializer for registering SI base and derived units.
 * This method shall be invoked in a single thread by the {@code Units} class initializer only.
 */
static <Q extends Quantity<Q>> SystemUnit<Q> init(final SystemUnit<Q> unit) {
    assert !Units.initialized : unit;        // This assertion happens during Units initialization, but it is okay.
    final String symbol = unit.getSymbol();
    int existed;
    /* Unconditional */ existed  = (HARD_CODED.put(unit.dimension, unit) == null) ? 0 : 1;
    /* Unconditional */ existed |= (HARD_CODED.put(unit.quantity,  unit) == null) ? 0 : 2;
    if (symbol != null) existed |= (HARD_CODED.put(symbol,         unit) == null) ? 0 : 4;
    if (unit.epsg != 0) existed |= (HARD_CODED.put(unit.epsg,      unit) == null) ? 0 : 8;
    /*
     * Key collision on dimension and quantity tolerated for dimensionless units only, with an
     * an exception for "candela" because "lumen" is candela divided by a dimensionless unit.
     * Another exception is "Hz" because it come after rad/s, which has the same dimension.
     */
    assert filter(existed, unit, symbol) == 0 : unit;
    return unit;
}
 
Example #5
Source File: GroupItemTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private NumberItem createNumberItem(String name, Class<? extends Quantity<?>> dimension, State state) {
    NumberItem item = new NumberItem(CoreItemFactory.NUMBER + ":" + dimension.getSimpleName(), name);
    item.setUnitProvider(unitProvider);
    item.setState(state);

    return item;
}
 
Example #6
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testKmh2Knot() {
    Quantity<Speed> kmh = Quantities.getQuantity(new BigDecimal("1.852"), SIUnits.KILOMETRE_PER_HOUR);

    Quantity<Speed> knot = kmh.to(SmartHomeUnits.KNOT);
    assertThat(knot.getUnit(), is(SmartHomeUnits.KNOT));
    assertThat(knot.getValue().doubleValue(), is(closeTo(1.000, DEFAULT_ERROR)));
}
 
Example #7
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testKmh2Mih() {
    Quantity<Speed> kmh = Quantities.getQuantity(BigDecimal.TEN, SIUnits.KILOMETRE_PER_HOUR);

    Quantity<Speed> mph = kmh.to(ImperialUnits.MILES_PER_HOUR);
    assertThat(mph.getUnit(), is(ImperialUnits.MILES_PER_HOUR));
    assertThat(mph.getValue().doubleValue(), is(closeTo(6.21371192237333935d, DEFAULT_ERROR)));
}
 
Example #8
Source File: UnitUtils.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * A utility method to parse a unit symbol either directly or from a given pattern (like stateDescription or widget
 * label). In the latter case, the unit is expected to be the last part of the pattern separated by " " (e.g. "%.2f
 * °C" for °C).
 *
 * @param stringWithUnit the string to extract the unit symbol from
 * @return the unit symbol extracted from the string or {@code null} if no unit could be parsed
 *
 */
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) {
            // we expect this exception in case the extracted string does not match any known unit
            LOGGER.debug("Unknown unit from pattern: {}", unitSymbol);
        }
    }

    return null;
}
 
Example #9
Source File: AbstractUnit.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * If the {@code result} unit is a {@link ConventionalUnit} with no symbol, tries to infer a symbol for it.
 * Otherwise returns {@code result} unchanged.
 *
 * @param  result     the result of an arithmetic operation.
 * @param  operation  {@link #MULTIPLY}, {@link #DIVIDE} or an exponent.
 * @param  other      the left operand used in the operation, or {@code null} if {@code operation} is an exponent.
 * @return {@code result} or an equivalent unit augmented with a symbol.
 */
final <R extends Quantity<R>> Unit<R> inferSymbol(Unit<R> result, final char operation, final Unit<?> other) {
    if (result instanceof ConventionalUnit<?> && result.getSymbol() == null) {
        final String symbol = inferSymbol(operation, other);
        if (symbol != null) {
            result = ((ConventionalUnit<R>) result).forSymbol(symbol);
        }
    }
    return result;
}
 
Example #10
Source File: QuantitiesTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Scalar#equals(Object)} and {@link Scalar#hashCode()}.
 * This test uses a unit without specific {@link Scalar} subclass, in order to
 * verify that tested methods work even though the {@link ScalarFallback} proxy.
 */
@Test
public void testEqualsAndHashcode() {
    Quantity<?> q1 = Quantities.create(2, Units.VOLT);
    Quantity<?> q2 = Quantities.create(2, Units.VOLT);
    Quantity<?> q3 = Quantities.create(3, Units.VOLT);
    assertTrue (q1.hashCode() == q2.hashCode());
    assertFalse(q1.hashCode() == q3.hashCode());
    assertTrue (q1.hashCode() != 0);
    assertTrue (q1.equals(q2));
    assertFalse(q1.equals(q3));
}
 
Example #11
Source File: CommunicationManager.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable Class<? extends Quantity<?>> getDimension(@Nullable String acceptedItemType) {
    if (acceptedItemType == null || acceptedItemType.isEmpty()) {
        return null;
    }
    String itemTypeExtension = ItemUtil.getItemTypeExtension(acceptedItemType);
    if (itemTypeExtension == null) {
        return null;
    }

    return UnitUtils.parseDimension(itemTypeExtension);
}
 
Example #12
Source File: ConverterTest.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testKelvinToCelsius() {
  Quantity<Temperature> sut = Quantities.getQuantity(273.15d, KELVIN).to(CELSIUS);
  assertNotNull(sut);
  assertEquals(CELSIUS, sut.getUnit());
  assertEquals(0, sut.getValue());
}
 
Example #13
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Ml() {
    Quantity<Length> km = Quantities.getQuantity(BigDecimal.TEN, MetricPrefix.KILO(SIUnits.METRE));

    Quantity<Length> mile = km.to(ImperialUnits.MILE);
    assertThat(mile.getUnit(), is(ImperialUnits.MILE));
    assertThat(mile.getValue().doubleValue(), is(closeTo(6.2137119223733395d, DEFAULT_ERROR)));
}
 
Example #14
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testFahrenheit2Kelvin() {
    Quantity<Temperature> fahrenheit = Quantities.getQuantity(new BigDecimal("100"), ImperialUnits.FAHRENHEIT);

    Quantity<Temperature> kelvin = fahrenheit.to(SmartHomeUnits.KELVIN);
    assertThat(kelvin.getUnit(), is(SmartHomeUnits.KELVIN));
    assertThat(kelvin.getValue().doubleValue(), is(closeTo(310.92777777777777778d, DEFAULT_ERROR)));
}
 
Example #15
Source File: NumberItem.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Try to convert a {@link DecimalType} into a new {@link QuantityType}. The unit for the new
 * type is derived either from the state description (which might also give a hint on items w/o dimension) or from
 * the system default unit of the given dimension.
 *
 * @param originalType the source {@link DecimalType}.
 * @param dimension the dimension to which the new {@link QuantityType} should adhere.
 * @return the new {@link QuantityType} from the given originalType, {@code null} if a unit could not be calculated.
 */
public @Nullable QuantityType<?> toQuantityType(DecimalType originalType,
        @Nullable Class<? extends Quantity<?>> dimension) {
    Unit<? extends Quantity<?>> itemUnit = getUnit(dimension);
    if (itemUnit != null) {
        return new QuantityType<>(originalType.toBigDecimal(), itemUnit);
    }

    return null;
}
 
Example #16
Source File: ArithmeticTest.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSubtract() {
	Quantity<Length> km = Quantities.getQuantity(2000, Units.METRE);
	Quantity<Length> mile = Quantities.getQuantity(1, USCustomary.MILE);
	Quantity<Length> result = km.subtract(mile);
	assertEquals(390.656d, result.getValue().doubleValue(), 0d);
	assertEquals(Units.METRE, result.getUnit());
}
 
Example #17
Source File: ConverterTest.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testKelvinToReaumur() {
  Quantity<Temperature> sut = Quantities.getQuantity(1d, KELVIN).to(REAUMUR);
  assertNotNull(sut);
  assertEquals(REAUMUR, sut.getUnit());
  assertEquals(RationalNumber.of(-217.27d), sut.getValue());
}
 
Example #18
Source File: I18nProviderImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Quantity<T>> @Nullable Unit<T> getUnit(@Nullable Class<T> dimension) {
    Map<SystemOfUnits, Unit<? extends Quantity<?>>> map = dimensionMap.get(dimension);
    if (map == null) {
        return null;
    }
    return (Unit<T>) map.get(getMeasurementSystem());
}
 
Example #19
Source File: SmartHomeUnitsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testmmHg2PascalConversion() {
    Quantity<Pressure> mmHg = Quantities.getQuantity(BigDecimal.ONE, SmartHomeUnits.MILLIMETRE_OF_MERCURY);

    assertThat(mmHg.to(SIUnits.PASCAL), is(Quantities.getQuantity(new BigDecimal("133.322368"), SIUnits.PASCAL)));
    assertThat(mmHg.to(MetricPrefix.HECTO(SIUnits.PASCAL)),
            is(Quantities.getQuantity(new BigDecimal("1.33322368"), MetricPrefix.HECTO(SIUnits.PASCAL))));
}
 
Example #20
Source File: SmartHomeUnitsTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCm2In() {
    Quantity<Length> cm = Quantities.getQuantity(BigDecimal.TEN, MetricPrefix.CENTI(SIUnits.METRE));

    Quantity<Length> in = cm.to(ImperialUnits.INCH);
    assertThat(in.getUnit(), is(ImperialUnits.INCH));
    assertThat(in.getValue().doubleValue(), is(closeTo(3.93700787401574803d, DEFAULT_ERROR)));
}
 
Example #21
Source File: SmartHomeUnitsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testHectoPascal2Pascal() {
    Quantity<Pressure> pascal = Quantities.getQuantity(BigDecimal.valueOf(100), SIUnits.PASCAL);

    assertThat(pascal.to(MetricPrefix.HECTO(SIUnits.PASCAL)),
            is(Quantities.getQuantity(BigDecimal.ONE, MetricPrefix.HECTO(SIUnits.PASCAL))));
}
 
Example #22
Source File: ConventionalUnit.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Casts this unit to a parameterized unit of specified nature or throw a {@code ClassCastException}
 * if the dimension of the specified quantity and this unit's dimension do not match.
 *
 * @param  <T>   the type of the quantity measured by the unit.
 * @param  type  the quantity class identifying the nature of the unit.
 * @return this unit parameterized with the specified type.
 * @throws ClassCastException if the dimension of this unit is different from the specified quantity dimension.
 */
@Override
@SuppressWarnings("unchecked")
public <T extends Quantity<T>> Unit<T> asType(final Class<T> type) throws ClassCastException {
    final Unit<T> alternate = target.asType(type);
    if (target.equals(alternate)) {
        return (Unit<T>) this;
    }
    return alternate.transform(toTarget);
}
 
Example #23
Source File: ArithmeticTest.java    From uom-systems with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testAdd() {
	Quantity<Length> km = Quantities.getQuantity(1000, Units.METRE);
	Quantity<Length> mile = Quantities.getQuantity(1, USCustomary.MILE);
	Quantity<Length> result = km.add(mile);
	assertEquals(2609.344d, result.getValue().doubleValue(), 0d);
	assertEquals(Units.METRE, result.getUnit());
}
 
Example #24
Source File: SmartHomeUnitsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Ft() {
    Quantity<Length> cm = Quantities.getQuantity(new BigDecimal("30"), MetricPrefix.CENTI(SIUnits.METRE));

    Quantity<Length> foot = cm.to(ImperialUnits.FOOT);
    assertThat(foot.getUnit(), is(ImperialUnits.FOOT));
    assertThat(foot.getValue().doubleValue(), is(closeTo(0.9842519685039369d, DEFAULT_ERROR)));
}
 
Example #25
Source File: SmartHomeUnitsTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testM2Yd() {
    Quantity<Length> m = Quantities.getQuantity(BigDecimal.ONE, SIUnits.METRE);

    Quantity<Length> yard = m.to(ImperialUnits.YARD);
    assertThat(yard.getUnit(), is(ImperialUnits.YARD));
    assertThat(yard.getValue().doubleValue(), is(closeTo(1.0936132983377076d, DEFAULT_ERROR)));
}
 
Example #26
Source File: ItemDTOMapper.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private static @Nullable Class<? extends Quantity<?>> getDimension(@Nullable Item baseItem) {
    if (baseItem instanceof NumberItem) {
        return ((NumberItem) baseItem).getDimension();
    }

    return null;
}
 
Example #27
Source File: SystemUnit.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a quantity for the given value and unit of measurement.
 */
@Override
public Quantity<Q> create(final Number value, final Unit<Q> unit) {
    final double v = AbstractConverter.doubleValue(value);
    if (factory != null) {
        return factory.create(v, unit);
    } else {
        return ScalarFallback.factory(v, unit, quantity);
    }
}
 
Example #28
Source File: Scalar.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a quantity with the same units than this quantity. If the new value is the same
 * than current value, then {@code this} instance is returned. Positive and negative zeros
 * are considered two different values.
 */
private Quantity<Q> of(final double newValue) {
    if (Double.doubleToRawLongBits(value) != Double.doubleToRawLongBits(newValue)) {
        return create(newValue, unit);
    }
    return this;
}
 
Example #29
Source File: DerivedScalar.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link Fallback} instance implementing the given quantity type.
 *
 * @see ScalarFallback#factory(double, Unit, Class)
 */
@SuppressWarnings("unchecked")
static <Q extends Quantity<Q>> Q factory(final double value, final Unit<Q> unit,
        final Unit<Q> systemUnit, final UnitConverter toSystem, final Class<Q> type)
{
    final Fallback<Q> quantity = new Fallback<>(value, unit, systemUnit, toSystem, type);
    return (Q) Proxy.newProxyInstance(Scalar.class.getClassLoader(), new Class<?>[] {type}, quantity);
}
 
Example #30
Source File: PersistentQuantityAndUnit.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
protected Quantity<?> fromConvertedColumns(Object[] convertedColumns) {

    String stringPart = (String) convertedColumns[0];
    Unit<?> unit = (Unit<?>) convertedColumns[1];

    return Quantities.getQuantity(stringPart + " " + unit.getSymbol());
}