Search in sources :

Example 36 with Unit

use of javax.measure.Unit in project sis by apache.

the class Proj4 method definition.

/**
 * Infers a {@literal Proj.4} definition from the given projected, geographic or geocentric coordinate reference system.
 * This method does not need the Proj.4 native library; it can be used in a pure Java application.
 * However the returned definition string may differ depending on whether the Proj.4 library is available or not.
 *
 * @param  crs  the coordinate reference system for which to create a Proj.4 definition.
 * @return the definition of the given CRS in a Proj.4 format.
 * @throws FactoryException if the Proj.4 definition string can not be created from the given CRS.
 */
public static String definition(final CoordinateReferenceSystem crs) throws FactoryException {
    ArgumentChecks.ensureNonNull("crs", crs);
    /*
         * If the given CRS object is associated to a Proj.4 structure, let Proj.4 formats itself
         * the definition string. Note that this operation may fail if there is no Proj.4 library
         * in the current system, or no JNI bindings to that library.
         */
    try {
        for (final Identifier id : crs.getIdentifiers()) {
            if (id instanceof PJ) {
                return ((PJ) id).getCode();
            }
        }
    } catch (UnsatisfiedLinkError e) {
        // Thrown the first time that we try to use the library.
        Logging.unexpectedException(Logging.getLogger(Modules.GDAL), Proj4.class, "definition", e);
    } catch (NoClassDefFoundError e) {
        // Thrown on all attempts after the first one.
        Logging.recoverableException(Logging.getLogger(Modules.GDAL), Proj4.class, "definition", e);
    }
    /*
         * If we found no Proj.4 structure, formats the definition string ourself. The string may differ from
         * what Proj.4 would have given. In particular, we do not provide "+init=" or "+datum=" parameter.
         * But the definition should still be semantically equivalent.
         */
    final String method;
    final GeodeticDatum datum;
    final ParameterValueGroup parameters;
    final CoordinateSystem cs = crs.getCoordinateSystem();
    if (crs instanceof GeodeticCRS) {
        if (cs instanceof EllipsoidalCS) {
            method = "latlon";
        } else if (cs instanceof CartesianCS) {
            method = "geocent";
        } else {
            throw new FactoryException(Errors.format(Errors.Keys.UnsupportedCoordinateSystem_1, cs.getClass()));
        }
        datum = ((GeodeticCRS) crs).getDatum();
        parameters = null;
    } else if (crs instanceof ProjectedCRS) {
        Projection c = ((ProjectedCRS) crs).getConversionFromBase();
        datum = ((ProjectedCRS) crs).getDatum();
        method = name(c.getMethod());
        parameters = c.getParameterValues();
    } else {
        throw new FactoryException(Errors.format(Errors.Keys.UnsupportedType_1, crs.getClass()));
    }
    /*
         * Append the map projection parameters. Those parameters may include axis lengths (a and b),
         * but not necessarily. If axis lengths are specified, then we will ignore the Ellipsoid instance
         * associated to the CRS.
         */
    final StringBuilder definition = new StringBuilder(100);
    definition.append(Proj4Factory.PROJ_PARAM).append(method);
    boolean hasSemiMajor = false;
    boolean hasSemiMinor = false;
    if (parameters != null) {
        definition.append(Proj4Factory.STANDARD_OPTIONS);
        for (final GeneralParameterValue parameter : parameters.values()) {
            if (parameter instanceof ParameterValue<?>) {
                final ParameterValue<?> pv = (ParameterValue<?>) parameter;
                final Object value;
                Unit<?> unit = pv.getUnit();
                if (unit != null) {
                    unit = Units.isAngular(unit) ? Units.DEGREE : unit.getSystemUnit();
                    // Always in metres or degrees.
                    value = pv.doubleValue(unit);
                } else {
                    value = pv.getValue();
                    if (value == null) {
                        continue;
                    }
                }
                final String pn = name(parameter.getDescriptor());
                hasSemiMajor |= pn.equals("a");
                hasSemiMinor |= pn.equals("b");
                definition.append(" +").append(pn).append('=').append(value);
            }
        }
    }
    /*
         * Append datum information: axis lengths if they were not part of the parameters, then prime meridian.
         */
    final Ellipsoid ellipsoid = datum.getEllipsoid();
    if (!hasSemiMajor)
        definition.append(" +a=").append(ellipsoid.getSemiMajorAxis());
    if (!hasSemiMinor)
        definition.append(" +b=").append(ellipsoid.getSemiMinorAxis());
    final PrimeMeridian pm = datum.getPrimeMeridian();
    if (pm != null) {
        double lon = pm.getGreenwichLongitude();
        final Unit<Angle> unit = pm.getAngularUnit();
        if (unit != null) {
            lon = unit.getConverterTo(Units.DEGREE).convert(lon);
        }
        definition.append(" +pm=").append(lon);
    }
    /*
         * Appends axis directions. This method always format a vertical direction (up or down)
         * even if the coordinate system is two-dimensional, because Proj.4 seems to require it.
         * Also extract axis units in the process.
         */
    // Horizontal at index 0, vertical at index 1.
    final Unit<?>[] units = new Unit<?>[2];
    boolean validCS = true;
    definition.append(' ').append(Proj4Factory.AXIS_ORDER_PARAM);
    final int dimension = Math.min(cs.getDimension(), 3);
    boolean hasVertical = false;
    for (int i = 0; i < dimension; i++) {
        final CoordinateSystemAxis axis = cs.getAxis(i);
        final AxisDirection dir = axis.getDirection();
        int unitIndex = 0;
        if (!AxisDirections.isCardinal(dir)) {
            if (!AxisDirections.isVertical(dir)) {
                throw new FactoryException(Errors.format(Errors.Keys.UnsupportedAxisDirection_1, dir));
            }
            hasVertical = true;
            unitIndex = 1;
        }
        final Unit<?> old = units[unitIndex];
        units[unitIndex] = axis.getUnit();
        validCS &= (old == null || old.equals(units[unitIndex]));
        definition.appendCodePoint(Character.toLowerCase(dir.name().codePointAt(0)));
    }
    if (!hasVertical && dimension < 3) {
        // Add a UP direction if not already present.
        definition.append('u');
    }
    /*
         * Append units of measurement, then verify the coordinate system validity.
         */
    for (int i = 0; i < units.length; i++) {
        final Unit<?> unit = units[i];
        if (unit != null && !unit.equals(Units.DEGREE) && !unit.equals(Units.METRE)) {
            validCS &= Units.isLinear(unit);
            definition.append(" +");
            // "+vto_meter" parameter.
            if (i == 1)
                definition.append('v');
            definition.append("to_meter=").append(Units.toStandardUnit(unit));
        }
    }
    /*
         * Append the "+towgs84" element if any. This is the last piece of information.
         * Note that the use of a "+towgs84" parameter is an "early binding" approach,
         * which is usually not recommended. But Proj4 works that way.
         */
    if (validCS) {
        if (datum instanceof DefaultGeodeticDatum) {
            for (final BursaWolfParameters bwp : ((DefaultGeodeticDatum) datum).getBursaWolfParameters()) {
                if (Utilities.equalsIgnoreMetadata(CommonCRS.WGS84.datum(), bwp.getTargetDatum())) {
                    definition.append(" +towgs84=").append(bwp.tX).append(',').append(bwp.tY).append(',').append(bwp.tZ);
                    if (!bwp.isTranslation()) {
                        definition.append(',').append(bwp.rX).append(',').append(bwp.rY).append(',').append(bwp.rZ).append(',').append(bwp.dS);
                    }
                    break;
                }
            }
        }
        return definition.toString();
    }
    /*
         * If we reach this point, we detected a coordinate system that we can not format as a
         * Proj.4 definition string. Format an error message with axis directions and units.
         */
    definition.setLength(0);
    definition.append('(');
    for (int i = 0; i < units.length; i++) {
        final CoordinateSystemAxis axis = cs.getAxis(i);
        if (i != 0)
            definition.append(", ");
        definition.append(axis.getUnit()).append(' ').append(Types.getCodeName(axis.getDirection()));
    }
    throw new FactoryException(Errors.format(Errors.Keys.IllegalCoordinateSystem_1, definition.append(')')));
}
Also used : ParameterValueGroup(org.opengis.parameter.ParameterValueGroup) UnavailableFactoryException(org.apache.sis.referencing.factory.UnavailableFactoryException) FactoryException(org.opengis.util.FactoryException) CoordinateSystem(org.opengis.referencing.cs.CoordinateSystem) Projection(org.opengis.referencing.operation.Projection) CoordinateSystemAxis(org.opengis.referencing.cs.CoordinateSystemAxis) Unit(javax.measure.Unit) Identifier(org.opengis.metadata.Identifier) AxisDirection(org.opengis.referencing.cs.AxisDirection) EllipsoidalCS(org.opengis.referencing.cs.EllipsoidalCS) CartesianCS(org.opengis.referencing.cs.CartesianCS) GeneralParameterValue(org.opengis.parameter.GeneralParameterValue) ParameterValue(org.opengis.parameter.ParameterValue) GeneralParameterValue(org.opengis.parameter.GeneralParameterValue) GeodeticDatum(org.opengis.referencing.datum.GeodeticDatum) DefaultGeodeticDatum(org.apache.sis.referencing.datum.DefaultGeodeticDatum) GeodeticCRS(org.opengis.referencing.crs.GeodeticCRS) PrimeMeridian(org.opengis.referencing.datum.PrimeMeridian) ProjectedCRS(org.opengis.referencing.crs.ProjectedCRS) Angle(javax.measure.quantity.Angle) DefaultGeodeticDatum(org.apache.sis.referencing.datum.DefaultGeodeticDatum) IdentifiedObject(org.opengis.referencing.IdentifiedObject) BursaWolfParameters(org.apache.sis.referencing.datum.BursaWolfParameters) Ellipsoid(org.opengis.referencing.datum.Ellipsoid)

Example 37 with Unit

use of javax.measure.Unit in project com.revolsys.open by revolsys.

the class MapRulerBorder method paintBorder.

@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
    final Graphics2D graphics = (Graphics2D) g;
    graphics.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 10));
    final FontMetrics fontMetrics = graphics.getFontMetrics();
    this.labelHeight = fontMetrics.getHeight();
    paintBackground(graphics, x, y, width, height);
    final BoundingBox boundingBox = this.viewport.getBoundingBox();
    if (this.rulerCoordinateSystem instanceof GeographicCoordinateSystem) {
        final Unit<Angle> displayUnit = NonSI.DEGREE_ANGLE;
        paintRuler(graphics, boundingBox, displayUnit, METRIC_GEOGRAPHICS_STEPS, true, x, y, width, height);
    } else if (this.rulerCoordinateSystem instanceof ProjectedCoordinateSystem) {
        if (this.baseUnit.equals(USCustomary.FOOT)) {
            final Unit<Length> displayUnit = USCustomary.FOOT;
            paintRuler(graphics, boundingBox, displayUnit, IMPERIAL_FOOT_STEPS, true, x, y, width, height);
        } else {
            final Unit<Length> displayUnit = Units.METRE;
            paintRuler(graphics, boundingBox, displayUnit, METRIC_PROJECTED_STEPS, true, x, y, width, height);
        }
    }
    graphics.setColor(Color.BLACK);
    graphics.drawRect(this.rulerSize - 1, this.rulerSize - 1, width - 2 * this.rulerSize + 1, height - 2 * this.rulerSize + 1);
}
Also used : Angle(javax.measure.quantity.Angle) FontMetrics(java.awt.FontMetrics) BoundingBox(com.revolsys.geometry.model.BoundingBox) ProjectedCoordinateSystem(com.revolsys.geometry.cs.ProjectedCoordinateSystem) GeographicCoordinateSystem(com.revolsys.geometry.cs.GeographicCoordinateSystem) Unit(javax.measure.Unit) Font(java.awt.Font) Graphics2D(java.awt.Graphics2D)

Example 38 with Unit

use of javax.measure.Unit in project com.revolsys.open by revolsys.

the class BoundingBoxTest method assertBoundingBox.

@SuppressWarnings({ "rawtypes", "unchecked" })
private void assertBoundingBox(final Geometry geometry, final BoundingBox boundingBox, final GeometryFactory geometryFactory, final boolean empty, final int axisCount, final double... bounds) {
    Assert.assertEquals("Geometry Factory", geometryFactory, boundingBox.getGeometryFactory());
    Assert.assertEquals("Empty", empty, boundingBox.isEmpty());
    Assert.assertEquals("Axis Count", axisCount, boundingBox.getAxisCount());
    Assert.assertEquals("Bounds", Lists.newArray(bounds), Lists.newArray(boundingBox.getMinMaxValues()));
    Unit unit = Units.METRE;
    Unit lengthUnit = Units.METRE;
    final StringBuilder wkt = new StringBuilder();
    final int srid = boundingBox.getCoordinateSystemId();
    if (geometryFactory == GeometryFactory.DEFAULT_3D) {
        Assert.assertEquals("coordinateSystem", null, boundingBox.getCoordinateSystem());
        Assert.assertEquals("srid", 0, srid);
    } else {
        if (srid > 0) {
            wkt.append("SRID=");
            wkt.append(srid);
            wkt.append(";");
        }
        Assert.assertEquals("srid", geometryFactory.getCoordinateSystemId(), srid);
        final CoordinateSystem coordinateSystem = geometryFactory.getCoordinateSystem();
        Assert.assertEquals("coordinateSystem", coordinateSystem, boundingBox.getCoordinateSystem());
        if (coordinateSystem != null) {
            unit = coordinateSystem.getUnit();
            lengthUnit = coordinateSystem.getLengthUnit();
        }
    }
    wkt.append("BBOX");
    assertMinMax(boundingBox, -1, Double.NaN, Double.NaN);
    assertMinMax(boundingBox, axisCount + 1, Double.NaN, Double.NaN);
    double width = 0;
    double height = 0;
    double minX = Double.NaN;
    double maxX = Double.NaN;
    double minY = Double.NaN;
    double maxY = Double.NaN;
    double area = 0;
    if (bounds == null) {
        wkt.append(" EMPTY");
    } else {
        minX = bounds[0];
        maxX = bounds[axisCount];
        if (axisCount > 1) {
            minY = bounds[1];
            maxY = bounds[axisCount + 1];
            width = Math.abs(maxX - minX);
            height = Math.abs(maxY - minY);
            area = width * height;
        } else {
            area = 0;
        }
        if (axisCount == 3) {
            wkt.append(" Z");
        } else if (axisCount == 4) {
            wkt.append(" ZM");
        } else if (axisCount != 2) {
            wkt.append(" ");
            wkt.append(axisCount);
        }
        wkt.append("(");
        for (int axisIndex = 0; axisIndex < axisCount; axisIndex++) {
            if (axisIndex > 0) {
                wkt.append(',');
            }
            wkt.append(Doubles.toString(bounds[axisIndex]));
        }
        wkt.append(' ');
        for (int axisIndex = 0; axisIndex < axisCount; axisIndex++) {
            if (axisIndex > 0) {
                wkt.append(',');
            }
            wkt.append(Doubles.toString(bounds[axisCount + axisIndex]));
        }
        wkt.append(')');
        for (int i = 0; i < axisCount; i++) {
            assertMinMax(boundingBox, i, bounds[i], bounds[axisCount + i]);
            Assert.assertEquals("Minimum " + i, Quantities.getQuantity(bounds[i], unit), boundingBox.getMinimum(i));
            Assert.assertEquals("Maximum" + i, Quantities.getQuantity(bounds[axisCount + i], unit), boundingBox.getMaximum(i));
            Assert.assertEquals("Minimum " + i, bounds[i], boundingBox.getMinimum(i, unit), 0);
            Assert.assertEquals("Maximum " + i, bounds[axisCount + i], boundingBox.getMaximum(i, unit), 0);
        }
    }
    Assert.assertEquals("MinX", minX, boundingBox.getMinX(), 0);
    Assert.assertEquals("MaxX", maxX, boundingBox.getMaxX(), 0);
    if (!boundingBox.isEmpty()) {
        Assert.assertEquals("MinimumX", Quantities.getQuantity(minX, unit), boundingBox.getMinimum(0));
        Assert.assertEquals("MaximumX", Quantities.getQuantity(maxX, unit), boundingBox.getMaximum(0));
        Assert.assertEquals("MinimumX", minX, boundingBox.getMinimum(0, unit), 0);
        Assert.assertEquals("MaximumX", maxX, boundingBox.getMaximum(0, unit), 0);
        Assert.assertEquals("MinimumY", Quantities.getQuantity(minY, unit), boundingBox.getMinimum(1));
        Assert.assertEquals("MaximumY", Quantities.getQuantity(maxY, unit), boundingBox.getMaximum(1));
        Assert.assertEquals("MinimumY", minY, boundingBox.getMinimum(1, unit), 0);
        Assert.assertEquals("MaximumY", maxY, boundingBox.getMaximum(1, unit), 0);
    }
    Assert.assertEquals("MinY", minY, boundingBox.getMinY(), 0);
    Assert.assertEquals("MaxY", maxY, boundingBox.getMaxY(), 0);
    Assert.assertEquals("WKT", wkt.toString(), boundingBox.toString());
    Assert.assertEquals("Area", area, boundingBox.getArea(), 0);
    Assert.assertEquals("Width", width, boundingBox.getWidth(), 0);
    Assert.assertEquals("Width", width, QuantityType.doubleValue(boundingBox.getWidthLength(), lengthUnit), 0);
    Assert.assertEquals("Width", Quantities.getQuantity(width, lengthUnit), boundingBox.getWidthLength());
    Assert.assertEquals("Height", height, boundingBox.getHeight(), 0);
    Assert.assertEquals("Height", height, QuantityType.doubleValue(boundingBox.getHeightLength(), lengthUnit), 0);
    Assert.assertEquals("Height", Quantities.getQuantity(height, lengthUnit), boundingBox.getHeightLength());
    Assert.assertEquals("Aspect Ratio", width / height, boundingBox.getAspectRatio(), 0);
    if (geometry != null) {
        if (geometry.isEmpty()) {
            final boolean intersects = geometry.intersects(boundingBox);
            Assert.assertFalse("Bounding Box Intersects Empty", intersects);
        } else {
            final boolean intersects = geometry.intersects(boundingBox);
            Assert.assertTrue("Bounding Box Intersects", intersects);
            // Test outside
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(-100, -100)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(-100, 0)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(-100, 100)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(0, -100)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(0, 100)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(100, -100)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(100, 0)));
            Assert.assertFalse("Bounding Box Intersects", geometry.intersects(boundingBox.move(100, 100)));
        }
    }
}
Also used : CoordinateSystem(com.revolsys.geometry.cs.CoordinateSystem) Unit(javax.measure.Unit) Point(com.revolsys.geometry.model.Point)

Example 39 with Unit

use of javax.measure.Unit in project smarthome by eclipse.

the class ItemUIRegistryImpl method getLabel.

@Override
public String getLabel(Widget w) {
    String label = getLabelFromWidget(w);
    String itemName = w.getItem();
    if (StringUtils.isBlank(itemName)) {
        return transform(label, null);
    }
    String labelMappedOption = null;
    State state = null;
    StateDescription stateDescription = null;
    String formatPattern = getFormatPattern(label);
    // (i.e. it contains at least a %)
    try {
        final Item item = getItem(itemName);
        // There is a known issue in the implementation of the method getStateDescription() of class Item
        // in the following case:
        // - the item provider returns as expected a state description without pattern but with for
        // example a min value because a min value is set in the item definition but no label with
        // pattern is set.
        // - the channel state description provider returns as expected a state description with a pattern
        // In this case, the result is no display of value by UIs because no pattern is set in the
        // returned StateDescription. What is expected is the display of a value using the pattern
        // provided by the channel state description provider.
        stateDescription = item.getStateDescription();
        if (formatPattern == null && stateDescription != null && stateDescription.getPattern() != null) {
            label = label + " [" + stateDescription.getPattern() + "]";
        }
        String updatedPattern = getFormatPattern(label);
        if (updatedPattern != null) {
            formatPattern = updatedPattern;
            // a number is requested, PercentType must not be converted to DecimalType:
            if (formatPattern.contains("%d") && !(item.getState() instanceof PercentType)) {
                state = item.getStateAs(DecimalType.class);
            } else {
                state = item.getState();
            }
        }
    } catch (ItemNotFoundException e) {
        logger.error("Cannot retrieve item for widget {}", w.eClass().getInstanceTypeName());
    }
    if (formatPattern != null) {
        if (formatPattern.isEmpty()) {
            label = label.substring(0, label.indexOf("[")).trim();
        } else {
            if (state == null || state instanceof UnDefType) {
                formatPattern = formatUndefined(formatPattern);
            } else if (state instanceof Type) {
                // if the channel contains options, we build a label with the mapped option value
                if (stateDescription != null && stateDescription.getOptions() != null) {
                    for (StateOption option : stateDescription.getOptions()) {
                        if (option.getValue().equals(state.toString()) && option.getLabel() != null) {
                            State stateOption = new StringType(option.getLabel());
                            try {
                                String formatPatternOption = stateOption.format(formatPattern);
                                labelMappedOption = label.trim();
                                labelMappedOption = labelMappedOption.substring(0, labelMappedOption.indexOf("[") + 1) + formatPatternOption + "]";
                            } catch (IllegalArgumentException e) {
                                logger.debug("Mapping option value '{}' for item {} using format '{}' failed ({}); mapping is ignored", stateOption, itemName, formatPattern, e.getMessage());
                                labelMappedOption = null;
                            }
                            break;
                        }
                    }
                }
                if (state instanceof QuantityType) {
                    QuantityType<?> quantityState = (QuantityType<?>) state;
                    // sanity convert current state to the item state description unit in case it was updated in the
                    // meantime. The item state is still in the "original" unit while the state description will
                    // display the new unit:
                    Unit<?> patternUnit = UnitUtils.parseUnit(formatPattern);
                    if (patternUnit != null && !quantityState.getUnit().equals(patternUnit)) {
                        quantityState = quantityState.toUnit(patternUnit);
                    }
                    // The widget may define its own unit in the widget label. Convert to this unit:
                    quantityState = convertStateToWidgetUnit(quantityState, w);
                    state = quantityState;
                }
                // This also handles IllegalFormatConversionException, which is a subclass of IllegalArgument.
                try {
                    formatPattern = fillFormatPattern(formatPattern, state);
                } catch (IllegalArgumentException e) {
                    logger.warn("Exception while formatting value '{}' of item {} with format '{}': {}", state, itemName, formatPattern, e.getMessage());
                    formatPattern = new String("Err");
                }
            }
            label = label.trim();
            label = label.substring(0, label.indexOf("[") + 1) + formatPattern + "]";
        }
    }
    return transform(label, labelMappedOption);
}
Also used : StringType(org.eclipse.smarthome.core.library.types.StringType) UnDefType(org.eclipse.smarthome.core.types.UnDefType) PercentType(org.eclipse.smarthome.core.library.types.PercentType) Unit(javax.measure.Unit) ChronoUnit(java.time.temporal.ChronoUnit) StateOption(org.eclipse.smarthome.core.types.StateOption) NumberItem(org.eclipse.smarthome.core.library.items.NumberItem) CallItem(org.eclipse.smarthome.core.library.items.CallItem) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) DateTimeItem(org.eclipse.smarthome.core.library.items.DateTimeItem) RollershutterItem(org.eclipse.smarthome.core.library.items.RollershutterItem) GroupItem(org.eclipse.smarthome.core.items.GroupItem) ColorItem(org.eclipse.smarthome.core.library.items.ColorItem) LocationItem(org.eclipse.smarthome.core.library.items.LocationItem) ContactItem(org.eclipse.smarthome.core.library.items.ContactItem) GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) StringItem(org.eclipse.smarthome.core.library.items.StringItem) PlayerItem(org.eclipse.smarthome.core.library.items.PlayerItem) ImageItem(org.eclipse.smarthome.core.library.items.ImageItem) DimmerItem(org.eclipse.smarthome.core.library.items.DimmerItem) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) UnDefType(org.eclipse.smarthome.core.types.UnDefType) PlayPauseType(org.eclipse.smarthome.core.library.types.PlayPauseType) StringType(org.eclipse.smarthome.core.library.types.StringType) NextPreviousType(org.eclipse.smarthome.core.library.types.NextPreviousType) PercentType(org.eclipse.smarthome.core.library.types.PercentType) Type(org.eclipse.smarthome.core.types.Type) QuantityType(org.eclipse.smarthome.core.library.types.QuantityType) DateTimeType(org.eclipse.smarthome.core.library.types.DateTimeType) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) QuantityType(org.eclipse.smarthome.core.library.types.QuantityType) State(org.eclipse.smarthome.core.types.State) DecimalType(org.eclipse.smarthome.core.library.types.DecimalType) StateDescription(org.eclipse.smarthome.core.types.StateDescription) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 40 with Unit

use of javax.measure.Unit in project uom-se by unitsofmeasurement.

the class DefaultQuantityFormat method parse.

@SuppressWarnings("unchecked")
@Override
AbstractQuantity<?> parse(CharSequence csq, int index) throws ParserException {
    // cursor.getIndex();
    int startDecimal = index;
    while ((startDecimal < csq.length()) && Character.isWhitespace(csq.charAt(startDecimal))) {
        startDecimal++;
    }
    int endDecimal = startDecimal + 1;
    while ((endDecimal < csq.length()) && !Character.isWhitespace(csq.charAt(endDecimal))) {
        endDecimal++;
    }
    Double decimal = new Double(csq.subSequence(startDecimal, endDecimal).toString());
    // cursor.setIndex(endDecimal + 1);
    // Unit unit = EBNFUnitFormat.getInstance().parse(csq, index);
    Unit unit = SimpleUnitFormat.getInstance().parse(csq, index);
    return NumberQuantity.of(decimal, unit);
}
Also used : Unit(javax.measure.Unit) AbstractUnit(tec.uom.se.AbstractUnit)

Aggregations

Unit (javax.measure.Unit)52 AbstractUnit (tech.units.indriya.AbstractUnit)12 AbstractUnit (tec.uom.se.AbstractUnit)11 UnitConverter (javax.measure.UnitConverter)5 Test (org.junit.Test)5 CoordinateSystem (com.revolsys.geometry.cs.CoordinateSystem)4 ProjectedCoordinateSystem (com.revolsys.geometry.cs.ProjectedCoordinateSystem)4 BigDecimal (java.math.BigDecimal)4 Length (javax.measure.quantity.Length)4 CoordinateSystemAxis (org.opengis.referencing.cs.CoordinateSystemAxis)4 GeographicCoordinateSystem (com.revolsys.geometry.cs.GeographicCoordinateSystem)3 Format (java.text.Format)3 NumberFormat (java.text.NumberFormat)3 IncommensurableException (javax.measure.IncommensurableException)3 Angle (javax.measure.quantity.Angle)3 TestUnit (javax.measure.test.TestUnit)3 Test (org.junit.jupiter.api.Test)3 IdentifiedObject (org.opengis.referencing.IdentifiedObject)3 CoordinateSystem (org.opengis.referencing.cs.CoordinateSystem)3 ChainedCoordinatesOperation (com.revolsys.geometry.cs.projection.ChainedCoordinatesOperation)2