Examples of UnitConverter


Examples of javax.measure.converter.UnitConverter

    @Override
    public Date[] numberToDate(final String symbol, final Number... values) throws IOException {
        final Date[] dates = new Date[values.length];
        final String[] parts = TIME_UNIT_PATTERN.split(symbol);
        if (parts.length == 2) try {
            final UnitConverter converter = Units.valueOf(parts[0]).getConverterToAny(Units.MILLISECOND);
            final long epoch = JDK8.parseDateTime(parts[1], DEFAULT_TIMEZONE_IS_UTC).getTime();
            for (int i=0; i<values.length; i++) {
                final Number value = values[i];
                if (value != null) {
                    dates[i] = new Date(epoch + Math.round(converter.convert(value.doubleValue())));
                }
            }
        } catch (ConversionException e) {
            listeners.warning(null, e);
        } catch (IllegalArgumentException e) {
View Full Code Here

Examples of javax.measure.converter.UnitConverter

     */
    private static <Q extends Quantity> void checkConversion(
            final double expected, final Unit<Q> unitExpected,
            final double actual,   final Unit<Q> unitActual)
    {
        final UnitConverter converter = unitActual.getConverterTo(unitExpected);
        final UnitConverter inverse   = converter.inverse();
        assertEquals( expected, converter.convert( actual), TOLERANCE);
        assertEquals( actual,   inverse.convert( expected), TOLERANCE);
        assertEquals(-expected, converter.convert(-actual), TOLERANCE);
        assertEquals(-actual,   inverse.convert(-expected), TOLERANCE);
    }
View Full Code Here

Examples of javax.measure.converter.UnitConverter

            properties.put(NAME_KEY, DefaultCoordinateSystemAxis.UNNAMED);
        }
        /*
         * Converts the axis range and build the new axis.
         */
        final UnitConverter c;
        try {
            c = unit.getConverterToAny(newUnit);
        } catch (ConversionException e) {
            // Use IllegalStateException because the public API is an AbstractCS member method.
            throw new IllegalStateException(Errors.format(Errors.Keys.IllegalUnitFor_2, "axis", unit), e);
        }
        properties.put(DefaultCoordinateSystemAxis.MINIMUM_VALUE_KEY, c.convert(axis.getMinimumValue()));
        properties.put(DefaultCoordinateSystemAxis.MAXIMUM_VALUE_KEY, c.convert(axis.getMaximumValue()));
        properties.put(DefaultCoordinateSystemAxis.RANGE_MEANING_KEY, axis.getRangeMeaning());
        return new DefaultCoordinateSystemAxis(properties, newAbbr, newDir, newUnit);
    }
View Full Code Here

Examples of javax.measure.converter.UnitConverter

        /*
         * Before to verify if the given value is inside the bounds, we need to convert the value
         * to the units used by the parameter descriptor. The first part of this block verifies
         * the validity of the unit argument, so we execute it even if 'value' is null.
         */
        UnitConverter converter = null;
        Object convertedValue = value;
        if (unit != null) {
            final Unit<?> def = descriptor.getUnit();
            if (def == null) {
                final String name = getName(descriptor);
                throw new InvalidParameterValueException(Errors.format(Errors.Keys.UnitlessParameter_1, name), name, unit);
            }
            if (!unit.equals(def)) {
                final short expectedID = getUnitMessageID(def);
                if (getUnitMessageID(unit) != expectedID) {
                    throw new IllegalArgumentException(Errors.format(expectedID, unit));
                }
                /*
                 * Verify the type of the user's value before to perform the unit conversion,
                 * because the conversion will create a new object not necessarily of the same type.
                 */
                if (value != null) {
                    if (!valueClass.isInstance(value)) {
                        final String name = getName(descriptor);
                        throw new InvalidParameterValueException(
                                Errors.format(Errors.Keys.IllegalParameterValueClass_3,
                                name, valueClass, value.getClass()), name, value);
                    }
                    /*
                     * From this point we will perform the actual unit conversion. The value may be either
                     * a Number instance, or an array of numbers (typically an array of type double[]). In
                     * the array case, we will store the converted values in a new array of the same type.
                     */
                    try {
                        converter = unit.getConverterToAny(def);
                    } catch (ConversionException e) {
                        throw new IllegalArgumentException(Errors.format(Errors.Keys.IncompatibleUnits_2, unit, def), e);
                    }
                    Class<?> componentType = valueClass.getComponentType();
                    if (componentType == null) {
                        /*
                         * Usual case where the value is not an array. Convert the value directly.
                         * Note that the value can only be a number because the unit is associated
                         * to MeasurementRange, which accepts only numbers.
                         */
                        Number n = converter.convert(((Number) value).doubleValue());
                        try {
                            convertedValue = Numbers.cast(n, (Class<? extends Number>) valueClass);
                        } catch (IllegalArgumentException e) {
                            throw new InvalidParameterValueException(e.getLocalizedMessage(), getName(descriptor), value);
                        }
                    } else {
                        /*
                         * The value is an array. Creates a new array and store the converted values
                         * using Array reflection.
                         */
                        final int length = Array.getLength(value);
                        convertedValue = Array.newInstance(componentType, length);
                        componentType = Numbers.primitiveToWrapper(componentType);
                        for (int i=0; i<length; i++) {
                            Number n = (Number) Array.get(value, i);
                            n = converter.convert(n.doubleValue()); // Value in units that we can compare.
                            try {
                                n = Numbers.cast(n, (Class<? extends Number>) componentType);
                            } catch (IllegalArgumentException e) {
                                throw new InvalidParameterValueException(e.getLocalizedMessage(),
                                        getName(descriptor) + '[' + i + ']', value);
View Full Code Here

Examples of javax.measure.converter.UnitConverter

     * @see #setValue(double[],Unit)
     * @see #doubleValue(Unit)
     */
    @Override
    public double[] doubleValueList(final Unit<?> unit) throws IllegalArgumentException, IllegalStateException {
        final UnitConverter converter = getConverterTo(unit);
        final double[] values = doubleValueList();
        for (int i=0; i<values.length; i++) {
            values[i] = converter.convert(values[i]);
        }
        return values;
    }
View Full Code Here

Examples of javax.measure.converter.UnitConverter

        final Number zmax = decoder.numericValue(VERTICAL .MAXIMUM);
        /*
         * If at least one geographic ordinates above is available, add a GeographicBoundingBox.
         */
        if (xmin != null || xmax != null || ymin != null || ymax != null) {
            final UnitConverter xConv = getConverterTo(decoder.unitValue(LONGITUDE.UNITS), NonSI.DEGREE_ANGLE);
            final UnitConverter yConv = getConverterTo(decoder.unitValue(LATITUDE .UNITS), NonSI.DEGREE_ANGLE);
            extent = new DefaultExtent(null, new DefaultGeographicBoundingBox(
                    valueOf(xmin, xConv), valueOf(xmax, xConv),
                    valueOf(ymin, yConv), valueOf(ymax, yConv)), null, null);
        }
        /*
         * If at least one vertical ordinates above is available, add a VerticalExtent.
         */
        if (zmin != null || zmax != null) {
            final UnitConverter c = getConverterTo(decoder.unitValue(VERTICAL.UNITS), SI.METRE);
            double min = valueOf(zmin, c);
            double max = valueOf(zmax, c);
            if (CF.POSITIVE_DOWN.equals(decoder.stringValue(VERTICAL.POSITIVE))) {
                final double tmp = min;
                min = -max;
View Full Code Here

Examples of javax.measure.converter.UnitConverter

  protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path,
      TimeLapse time) {
    final long startTimeConsumed = time.getTimeConsumed();
    Point loc = objLocs.get(object);

    final UnitConverter toInternalTimeConv = time.getTimeUnit().getConverterTo(
        INTERNAL_TIME_UNIT);
    final UnitConverter toExternalTimeConv = INTERNAL_TIME_UNIT
        .getConverterTo(time.getTimeUnit());

    double traveled = 0;
    final double speed = min(toInternalSpeedConv.convert(object.getSpeed()),
        maxSpeed);
    if (speed == 0d) {
      // FIXME add test for this case, also check GraphRoadModel
      final Measure<Double, Length> dist = Measure.valueOf(0d,
          externalDistanceUnit);
      final Measure<Long, Duration> dur = Measure.valueOf(0L,
          time.getTimeUnit());
      return new MoveProgress(dist, dur, new ArrayList<Point>());
    }

    final List<Point> travelledNodes = new ArrayList<Point>();
    while (time.hasTimeLeft() && path.size() > 0) {
      checkArgument(isPointInBoundary(path.peek()),
          "points in the path must be within the predefined boundary of the plane");

      // distance in internal time unit that can be traveled with timeleft
      final double travelDistance = speed
          * toInternalTimeConv.convert(time.getTimeLeft());
      final double stepLength = toInternalDistConv.convert(Point.distance(loc,
          path.peek()));

      if (travelDistance >= stepLength) {
        loc = path.remove();
        travelledNodes.add(loc);

        final long timeSpent = DoubleMath.roundToLong(
            toExternalTimeConv.convert(stepLength / speed),
            RoundingMode.HALF_DOWN);
        time.consume(timeSpent);
        traveled += stepLength;
      } else {
        final Point diff = Point.diff(path.peek(), loc);
View Full Code Here

Examples of javax.measure.converter.UnitConverter

    final long startTimeConsumed = time.getTimeConsumed();
    final Loc objLoc = objLocs.get(object);
    checkLocation(objLoc);
    double traveled = 0;

    final UnitConverter toInternalTimeConv = time.getTimeUnit().getConverterTo(
        INTERNAL_TIME_UNIT);
    final UnitConverter toExternalTimeConv = INTERNAL_TIME_UNIT
        .getConverterTo(time.getTimeUnit());

    Loc tempLoc = objLoc;
    Point tempPos = objLoc;

    double newDis = Double.NaN;

    final List<Point> travelledNodes = new ArrayList<Point>();
    while (time.hasTimeLeft() && path.size() > 0) {
      checkIsValidMove(tempLoc, path.peek());

      // speed in internal speed unit
      final double speed = getMaxSpeed(object, tempPos, path.peek());

      // distance that can be traveled in current edge with timeleft
      final double travelDistance = speed
          * toInternalTimeConv.convert(time.getTimeLeft());
      final double connLength = toInternalDistConv
          .convert(computeConnectionLength(tempPos, path.peek()));

      if (travelDistance >= connLength) {
        // jump to next vertex
        tempPos = path.remove();
        if (!(tempPos instanceof Loc)) {
          travelledNodes.add(tempPos);
        }
        final long timeSpent = DoubleMath.roundToLong(
            toExternalTimeConv.convert(connLength / speed),
            RoundingMode.HALF_DOWN);
        time.consume(timeSpent);
        traveled += connLength;

        if (tempPos instanceof Loc) {
View Full Code Here

Examples of javax.measure.converter.UnitConverter

  }

  @Test
  public void maxSpeedTest() {
    final UnitConverter speedConverter = NonSI.KILOMETERS_PER_HOUR
        .getConverterTo(AbstractRoadModel.INTERNAL_SPEED_UNIT);

    final double s = speedConverter.convert(speed);

    final SpeedyRoadUser agent = new SpeedyRoadUser(speed);
    assertEquals(s, model.getMaxSpeed(agent, A, B), DELTA);
    assertEquals(speed > 2.5 ? speedConverter.convert(2.5) : s,
        model.getMaxSpeed(agent, B, C), DELTA);
    assertEquals(s, model.getMaxSpeed(agent, C, B), DELTA);
    assertEquals(s, model.getMaxSpeed(agent, B, D), DELTA);
    assertEquals(s, model.getMaxSpeed(agent, C, D), DELTA);
    assertEquals(speedConverter.convert(1), model.getMaxSpeed(agent, D, C),
        DELTA);
    assertEquals(s, model.getMaxSpeed(agent, D, E), DELTA);
  }
View Full Code Here

Examples of javax.measure.converter.UnitConverter

    final Graph<LengthData> g = new MultimapGraph<LengthData>();
    final GraphRoadModel rm = new GraphRoadModel(g, SI.KILOMETER,
        NonSI.KILOMETERS_PER_HOUR);
    g.addConnection(A, B, new LengthData(3));

    final UnitConverter conv = NonSI.KILOMETERS_PER_HOUR
        .getConverterTo(AbstractRoadModel.INTERNAL_SPEED_UNIT);

    assertEquals(conv.convert(10),
        rm.getMaxSpeed(new SpeedyRoadUser(10), A, B), EPSILON);

    ((Graph<MultiAttributeData>) graph).addConnection(SE, SW,
        new MultiAttributeData(3, 5d));
    assertEquals(conv.convert(5),
        model.getMaxSpeed(new SpeedyRoadUser(10), SE, SW), EPSILON);

    ((Graph<MultiAttributeData>) graph).addConnection(NE, SE,
        new MultiAttributeData(3, Double.NaN));
    assertEquals(conv.convert(10),
        model.getMaxSpeed(new SpeedyRoadUser(10), NE, SE), EPSILON);
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.