javax.measure.quantity.Time Java Examples

The following examples show how to use javax.measure.quantity.Time. 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: 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 #2
Source File: UnitsTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests getting a unit for a given quantity type.
 */
@Test
public void testGetForQuantity() {
    assertSame("Length",            Units.METRE,             Units.get(Length.class));
    assertSame("Mass",              Units.KILOGRAM,          Units.get(Mass.class));
    assertSame("Time",              Units.SECOND,            Units.get(Time.class));
    assertSame("Temperature",       Units.KELVIN,            Units.get(Temperature.class));
    assertSame("Area",              Units.SQUARE_METRE,      Units.get(Area.class));
    assertSame("Volume",            Units.CUBIC_METRE,       Units.get(Volume.class));
    assertSame("Speed",             Units.METRES_PER_SECOND, Units.get(Speed.class));
    assertSame("LuminousIntensity", Units.CANDELA,           Units.get(LuminousIntensity.class));
    assertSame("LuminousFlux",      Units.LUMEN,             Units.get(LuminousFlux.class));
    assertSame("SolidAngle",        Units.STERADIAN,         Units.get(SolidAngle.class));
    assertSame("Angle",             Units.RADIAN,            Units.get(Angle.class));
    assertSame("Dimensionless",     Units.UNITY,             Units.get(Dimensionless.class));
}
 
Example #3
Source File: SystemUnitTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link SystemUnit#asType(Class)} for a quantity unknown to Apache SIS.
 */
@Test
@DependsOnMethod({"testAsType", "testAlternate"})
public void testAsTypeForNewQuantity() {
    /*
     * Tests with a new quantity type unknown to Apache SIS.
     * SIS can not proof that the type is wrong, so it should accept it.
     */
    final Unit<Strange> strange = Units.METRE.asType(Strange.class);
    final Unit<Strange> named   = strange.alternate("strange");
    assertNull  ("Should not have symbol since this is a unit for a new quantity.", strange.getSymbol());
    assertEquals("Should have a name since we invoked 'alternate'.", "strange", named.getSymbol());
    assertSame  ("Should prefer the named instance.", named, Units.METRE.asType(Strange.class));
    assertSame  ("Go back to the fundamental unit.",  Units.METRE, named.asType(Length.class));
    for (final Unit<Strange> unit : Arrays.asList(strange, named)) {
        try {
            unit.asType(Time.class);
            fail("Expected an exception for incompatible quantity types.");
        } catch (ClassCastException e) {
            final String message = e.getMessage();
            assertTrue(message, message.contains("Strange"));
            assertTrue(message, message.contains("Time"));
        }
    }
}
 
Example #4
Source File: SystemUnitTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link SystemUnit#asType(Class)}.
 */
@Test
public void testAsType() {
    assertSame(Units.METRE,  Units.METRE .asType(Length.class));
    assertSame(Units.SECOND, Units.SECOND.asType(Time.class));
    /*
     * Test with units outside the pre-defined constants in the Units class.
     */
    final Unit<Length> anonymous = new SystemUnit<>(Length.class, (UnitDimension) Units.METRE.getDimension(), null,  UnitRegistry.OTHER, (short) 0, null);
    final Unit<Length> otherName = new SystemUnit<>(Length.class, (UnitDimension) Units.METRE.getDimension(), "Foo", UnitRegistry.OTHER, (short) 0, null);
    assertSame(Units.METRE, anonymous.asType(Length.class));
    assertSame(otherName,   otherName.asType(Length.class));
    /*
     * Verify that the unit can not be casted to an incompatible units.
     */
    for (final Unit<Length> unit : Arrays.asList(Units.METRE, anonymous, otherName)) {
        try {
            unit.asType(Time.class);
            fail("Expected an exception for incompatible quantity types.");
        } catch (ClassCastException e) {
            final String message = e.getMessage();
            assertTrue(message, message.contains("Length"));
            assertTrue(message, message.contains("Time"));
        }
    }
}
 
Example #5
Source File: QuantityTypeTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testFormats() {
    QuantityType<Time> seconds = new QuantityType<>(80, SmartHomeUnits.SECOND);
    QuantityType<Time> millis = seconds.toUnit(MetricPrefix.MILLI(SmartHomeUnits.SECOND));
    QuantityType<Time> minutes = seconds.toUnit(SmartHomeUnits.MINUTE);

    assertThat(seconds.format("%.1f " + UnitUtils.UNIT_PLACEHOLDER), is("80" + SEP + "0 s"));
    assertThat(millis.format("%.1f " + UnitUtils.UNIT_PLACEHOLDER), is("80000" + SEP + "0 ms"));
    assertThat(minutes.format("%.1f " + UnitUtils.UNIT_PLACEHOLDER), is("1" + SEP + "3 min"));

    assertThat(seconds.format("%.1f"), is("80" + SEP + "0"));
    assertThat(minutes.format("%.1f"), is("1" + SEP + "3"));

    assertThat(seconds.format("%1$tH:%1$tM:%1$tS"), is("00:01:20"));
    assertThat(millis.format("%1$tHh %1$tMm %1$tSs"), is("00h 01m 20s"));
}
 
Example #6
Source File: ScalarTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Scalar#toString()}.
 */
@Test
public void testToString() {
    assertEquals("toString()", "24 km",   new Scalar.Length       (24.00, Units.KILOMETRE).toString());
    assertEquals("toString()", "10.25 h", new Scalar.Time         (10.25, Units.HOUR)     .toString());
    assertEquals("toString()", "0.25",    new Scalar.Dimensionless( 0.25, Units.UNITY)    .toString());
}
 
Example #7
Source File: Range.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the duration in minutes.
 */
public QuantityType<Time> getDuration() {
    if (start == null || end == null) {
        return null;
    }
    if (start.after(end)) {
        return new QuantityType<Time>(0, SmartHomeUnits.MINUTE);
    }
    return new QuantityType<Time>(end.getTimeInMillis() - start.getTimeInMillis(), MILLI(SmartHomeUnits.SECOND))
            .toUnit(SmartHomeUnits.MINUTE);
}
 
Example #8
Source File: CoordinateOperationFinder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an operation between two temporal coordinate reference systems.
 * The default implementation checks if both CRS use the same datum, then
 * adjusts for axis direction, units and epoch.
 *
 * <p>This method returns only <em>one</em> step for a chain of concatenated operations (to be built by the caller).
 * But a list is returned because the same step may be implemented by different operation methods. Only one element
 * in the returned list should be selected (usually the first one).</p>
 *
 * @param  sourceCRS  input coordinate reference system.
 * @param  targetCRS  output coordinate reference system.
 * @return a coordinate operation from {@code sourceCRS} to {@code targetCRS}.
 * @throws FactoryException if the operation can not be constructed.
 */
protected List<CoordinateOperation> createOperationStep(final TemporalCRS sourceCRS,
                                                        final TemporalCRS targetCRS)
        throws FactoryException
{
    final TemporalDatum sourceDatum = sourceCRS.getDatum();
    final TemporalDatum targetDatum = targetCRS.getDatum();
    final TimeCS sourceCS = sourceCRS.getCoordinateSystem();
    final TimeCS targetCS = targetCRS.getCoordinateSystem();
    /*
     * Compute the epoch shift.  The epoch is the time "0" in a particular coordinate reference system.
     * For example, the epoch for java.util.Date object is january 1, 1970 at 00:00 UTC. We compute how
     * much to add to a time in 'sourceCRS' in order to get a time in 'targetCRS'. This "epoch shift" is
     * in units of 'targetCRS'.
     */
    final Unit<Time> targetUnit = targetCS.getAxis(0).getUnit().asType(Time.class);
    double epochShift = sourceDatum.getOrigin().getTime() -
                        targetDatum.getOrigin().getTime();
    epochShift = Units.MILLISECOND.getConverterTo(targetUnit).convert(epochShift);
    /*
     * Check axis directions. The method 'swapAndScaleAxes' should returns a matrix of size 2×2.
     * The element at index (0,0) may be +1 if source and target axes are in the same direction,
     * or -1 if there are in opposite direction ("PAST" vs "FUTURE"). The value may be something
     * else than ±1 if a unit conversion is applied too.  For example the value is 60 if time in
     * sourceCRS is in hours while time in targetCRS is in minutes.
     *
     * The "epoch shift" previously computed is a translation. Consequently, it is added to element (0,1).
     */
    final Matrix matrix;
    try {
        matrix = CoordinateSystems.swapAndScaleAxes(sourceCS, targetCS);
    } catch (IllegalArgumentException | IncommensurableException exception) {
        throw new OperationNotFoundException(notFoundMessage(sourceCRS, targetCRS), exception);
    }
    final int translationColumn = matrix.getNumCol() - 1;           // Paranoiac check: should always be 1.
    final double translation = matrix.getElement(0, translationColumn);
    matrix.setElement(0, translationColumn, translation + epochShift);
    return asList(createFromAffineTransform(AXIS_CHANGES, sourceCRS, targetCRS, matrix));
}
 
Example #9
Source File: MoonPhase.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns the age in days.
 */
public QuantityType<Time> getAge() {
    return new QuantityType<Time>(age, SmartHomeUnits.DAY);
}
 
Example #10
Source File: GeodeticObjectParser.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Parses {@code "TimeCRS"} element.
 *
 * @param  mode       {@link #FIRST}, {@link #OPTIONAL} or {@link #MANDATORY}.
 * @param  parent     the parent element.
 * @param  isBaseCRS  {@code true} if parsing the CRS inside a {@code DerivedCRS}.
 * @return the {@code "TimeCRS"} element as a {@link TemporalCRS} object.
 * @throws ParseException if the {@code "TimeCRS"} element can not be parsed.
 */
private SingleCRS parseTimeCRS(final int mode, final Element parent, final boolean isBaseCRS)
        throws ParseException
{
    final Element element = parent.pullElement(mode, isBaseCRS ? WKTKeywords.BaseTimeCRS : WKTKeywords.TimeCRS);
    if (element == null) {
        return null;
    }
    final String     name = element.pullString("name");
    final Unit<Time> unit = parseScaledUnit(element, WKTKeywords.TimeUnit, Units.SECOND);
    /*
     * A TemporalCRS can be either a "normal" one (with a non-null datum), or a DerivedCRS of kind TemporalCRS.
     * In the later case, the datum is null and we have instead DerivingConversion element from a BaseTimeCRS.
     */
    TemporalDatum datum    = null;
    SingleCRS     baseCRS  = null;
    Conversion    fromBase = null;
    if (!isBaseCRS) {
        /*
         * UNIT[…] in DerivedCRS parameters are mandatory according ISO 19162 and the specification does not said
         * what to do if they are missing.  In this code, we default to the contextual units in the same way than
         * what we do for ProjectedCRS parameters, in the hope to be consistent.
         *
         * An alternative would be to specify null units, in which case MathTransformParser.parseParameters(…)
         * defaults to the units specified in the parameter descriptor. But this would make the CRS parser more
         * implementation-dependent, because the parameter descriptors are provided by the MathTransformFactory
         * instead than inferred from the WKT.
         */
        fromBase = parseDerivingConversion(OPTIONAL, element, WKTKeywords.DerivingConversion, unit, null);
        if (fromBase != null) {
            baseCRS = parseTimeCRS(MANDATORY, element, true);
        }
    }
    if (baseCRS == null) {                                                  // The most usual case.
        datum = parseTimeDatum(MANDATORY, element);
    }
    final CoordinateSystem cs;
    try {
        cs = parseCoordinateSystem(element, WKTKeywords.temporal, 1, false, unit, datum);
        final Map<String,?> properties = parseMetadataAndClose(element, name, datum);
        if (cs instanceof TimeCS) {
            final CRSFactory crsFactory = factories.getCRSFactory();
            if (baseCRS != null) {
                return crsFactory.createDerivedCRS(properties, baseCRS, fromBase, cs);
            }
            return crsFactory.createTemporalCRS(properties, datum, (TimeCS) cs);
        }
    } catch (FactoryException exception) {
        throw element.parseFailed(exception);
    }
    throw element.illegalCS(cs);
}
 
Example #11
Source File: TimeEncoding.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new time encoding.
 */
TimeEncoding(final TemporalDatum datum, final Unit<Time> unit) {
    this.origin   = datum.getOrigin().getTime();
    this.interval = unit.getConverterTo(Units.MILLISECOND).convert(1);
}
 
Example #12
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Unit<Time> getSystemUnit() {
	return null;
}
 
Example #13
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Unit<Time> transform(UnitConverter operation) {
	return null;
}
 
Example #14
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Unit<Time> divide(double divisor) {
	return null;
}
 
Example #15
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Unit<Time> multiply(double multiplier) {
	return null;
}
 
Example #16
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Unit<Time> shift(double offset) {
	return null;
}
 
Example #17
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Unit<Time> alternate(String symbol) {
	return null;
}
 
Example #18
Source File: MetadataFactoryTest.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public UnitConverter getConverterTo(Unit<Time> that) throws UnconvertibleException {
	return null;
}
 
Example #19
Source File: DefaultTemporalCRS.java    From sis with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the unit of measurement of temporal measurement in the coordinate reference system.
 * This is a convenience method for {@link org.opengis.referencing.cs.CoordinateSystemAxis#getUnit()}
 * on the unique axis of this coordinate reference system. The unit of measurement returned by this method
 * is the unit of the value expected in argument by {@link #toInstant(double)} and {@link #toDate(double)},
 * and the unit of the value returned by {@code toValue(…)} methods.
 *
 * <div class="note"><b>Implementation note:</b>
 * this method is declared final and does not invoke overridden {@link #getCoordinateSystem()} method
 * because this {@code getUnit()} method is invoked indirectly by constructors. Another reason is that
 * the overriding point is the {@code CoordinateSystemAxis.getUnit()} method and we want to avoid
 * introducing another overriding point that could be inconsistent with above method.</div>
 *
 * @return the temporal unit of measurement of coordinates in this CRS.
 *
 * @since 1.0
 */
public final Unit<Time> getUnit() {
    return super.getCoordinateSystem().getAxis(0).getUnit().asType(Time.class);
}