You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2016/10/13 13:38:52 UTC
svn commit: r1764673 [8/10] - in /sis/branches/JDK8: ./
application/sis-console/src/main/java/org/apache/sis/console/ core/
core/sis-feature/src/main/java/org/apache/sis/feature/builder/
core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/meta...
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/Measure.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/Measure.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/Measure.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/Measure.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -17,9 +17,8 @@
package org.apache.sis.internal.jaxb.gml;
import java.net.URISyntaxException;
-import javax.measure.unit.Unit;
-import javax.measure.unit.NonSI;
-import javax.measure.quantity.Quantity;
+import javax.measure.Unit;
+import javax.measure.Quantity;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.XmlAttribute;
@@ -62,7 +61,7 @@ import org.apache.sis.measure.Units;
* @author C�dric Brian�on (Geomatys)
* @author Martin Desruisseaux (Geomatys)
* @since 0.3
- * @version 0.4
+ * @version 0.8
* @module
*
* @see org.apache.sis.measure.Measure
@@ -150,12 +149,9 @@ public final class Measure {
return DefinitionURI.PREFIX + ":uom:" + Constants.EPSG + "::" + code;
}
}
- if (unit == null || unit.equals(Unit.ONE)) {
+ if (unit == null || unit.equals(Units.ONE)) {
return "";
}
- if (unit.equals(NonSI.PIXEL)) {
- return "pixel"; // TODO: maybe not the most appropriate unit.
- }
return Context.schema(Context.current(), "gmd", Schemas.METADATA_ROOT).append(Schemas.UOM_PATH)
.append("#xpointer(//*[@gml:id='").append(unit).append("'])").toString();
}
@@ -181,7 +177,7 @@ public final class Measure {
* @param type The quantity for the desired unit.
* @return A unit compatible with the given type, or {@code null} if none.
*/
- public <Q extends Quantity> Unit<Q> getUnit(final Class<Q> type) {
+ public <Q extends Quantity<Q>> Unit<Q> getUnit(final Class<Q> type) {
return (unit != null) ? unit.asType(type) : null;
}
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/MeasureList.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/MeasureList.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/MeasureList.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/gml/MeasureList.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -23,7 +23,7 @@ import java.net.URISyntaxException;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.XmlAttribute;
-import javax.measure.unit.Unit;
+import javax.measure.Unit;
import org.apache.sis.internal.jaxb.Context;
import org.apache.sis.util.ObjectConverter;
import org.apache.sis.util.ObjectConverters;
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -18,14 +18,8 @@ package org.apache.sis.internal.util;
import java.util.Map;
import java.util.HashMap;
-import java.text.Format;
-import java.text.FieldPosition;
-import java.text.ParsePosition;
-import javax.measure.unit.NonSI;
-import javax.measure.unit.SI;
-import javax.measure.unit.Unit;
-import javax.measure.unit.UnitFormat;
-import javax.measure.quantity.Quantity;
+import javax.measure.Unit;
+import javax.measure.Quantity;
import org.apache.sis.measure.Units;
import org.apache.sis.util.Workaround;
@@ -39,12 +33,7 @@ import org.apache.sis.util.Workaround;
* @module
*/
@Workaround(library="JSR-275", version="0.9.3")
-public final class PatchedUnitFormat extends Format {
- /**
- * For cross-version compatibility (even if this class is hopefully temporary).
- */
- private static final long serialVersionUID = -3064428584419360693L;
-
+public final class PatchedUnitFormat {
/**
* The symbols for some units defined by Apache SIS. We store here the symbols that we were not able
* to set in the units created by {@link org.apache.sis.measure.SexagesimalConverter} because of
@@ -77,23 +66,9 @@ public final class PatchedUnitFormat ext
}
/**
- * The {@link UnitFormat} to patch.
- */
- private final UnitFormat format;
-
- /**
- * {@code true} for formatting the unit names using US spelling.
- * Example: "meter" instead of "metre".
- */
- public boolean isLocaleUS;
-
- /**
- * Creates a new {@code PatchedUnitFormat} instance wrapping the given format.
- *
- * @param format the format to wrap.
+ * Do not allow instantiation of this class.
*/
- public PatchedUnitFormat(final UnitFormat format) {
- this.format = format;
+ private PatchedUnitFormat() {
}
/**
@@ -105,11 +80,11 @@ public final class PatchedUnitFormat ext
* @return The replacement to format, or {@code unit} if not needed.
*/
@SuppressWarnings("unchecked")
- public static <Q extends Quantity> Unit<Q> toFormattable(Unit<Q> unit) {
+ public static <Q extends Quantity<Q>> Unit<Q> toFormattable(Unit<Q> unit) {
final Map<Unit<?>,String> symbols = SYMBOLS;
if (symbols != null && symbols.containsKey(unit)) {
assert Units.isAngular(unit);
- unit = (Unit<Q>) NonSI.DEGREE_ANGLE;
+ unit = (Unit<Q>) Units.DEGREE;
}
return unit;
}
@@ -147,48 +122,14 @@ public final class PatchedUnitFormat ext
}
/**
- * Formats the given unit.
+ * Returns the "special-case" symbol of the given unit, or {@code null} if none.
*
- * @param unit The unit to format.
- * @param toAppendTo where to append to unit.
- * @param pos Ignored.
- * @return The given {@code toAppendTo} argument.
+ * @param unit the unit to format.
+ * @return the "special-case" symbol of given unit, or {@code null}.
*/
- @Override
- public StringBuffer format(final Object unit, final StringBuffer toAppendTo, final FieldPosition pos) {
+ @Workaround(library="JSR-275", version="0.9.3")
+ public static String getSymbol(final Object unit) {
final Map<Unit<?>,String> symbols = SYMBOLS;
- if (symbols != null) {
- final String symbol = symbols.get(unit);
- if (symbol != null) {
- return toAppendTo.append(symbol);
- }
- }
- /*
- * Following are specific to the WKT format, which is currently the only user of this method.
- * If we invoke this method for other purposes, then we would need to provide more control on
- * what kind of formatting is desired.
- */
- if (Unit.ONE.equals(unit)) {
- return toAppendTo.append("unity");
- } else if (NonSI.DEGREE_ANGLE.equals(unit)) {
- return toAppendTo.append("degree");
- } else if (SI.METRE.equals(unit)) {
- return toAppendTo.append(isLocaleUS ? "meter" : "metre");
- } else if (NonSI.FOOT_SURVEY_US.equals(unit)) {
- return toAppendTo.append("US survey foot");
- } else if (Units.PPM.equals(unit)) {
- return toAppendTo.append("parts per million");
- }
- return format.format(unit, toAppendTo, pos);
- }
-
- /**
- * Delegates to the wrapped {@link UnitFormat}.
- *
- * @return The parsed unit, or {@code null}.
- */
- @Override
- public Object parseObject(final String source, final ParsePosition pos) {
- return format.parseObject(source, pos);
+ return (symbols != null) ? symbols.get(unit) : null;
}
}
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/XPaths.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/XPaths.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/XPaths.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/XPaths.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -46,9 +46,9 @@ public final class XPaths extends Static
* {@code "http://schemas.opengis.net/iso/19139/20070417/resources/uom/gmxUom.xml#xpointer(//*[@gml:id='m'])"})</li>
* </ul>
*
- * @param type The object type.
- * @param url The URL to parse.
- * @return The reference, or {@code null} if none.
+ * @param type the object type.
+ * @param url the URL to parse.
+ * @return the reference, or {@code null} if none.
*/
public static String xpointer(final String type, final String url) {
if (type.equals("uom")) {
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/io/CompoundFormat.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/io/CompoundFormat.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/io/CompoundFormat.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/io/CompoundFormat.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -29,14 +29,14 @@ import java.text.ParsePosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import javax.measure.unit.Unit;
-import javax.measure.unit.UnitFormat;
+import javax.measure.Unit;
import org.opengis.referencing.IdentifiedObject;
import org.apache.sis.measure.Angle;
import org.apache.sis.measure.AngleFormat;
import org.apache.sis.measure.Range;
import org.apache.sis.measure.RangeFormat;
+import org.apache.sis.measure.UnitFormat;
import org.apache.sis.util.Localized;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.ArgumentChecks;
@@ -77,7 +77,7 @@ import static org.apache.sis.internal.ut
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.3
- * @version 0.3
+ * @version 0.8
* @module
*/
public abstract class CompoundFormat<T> extends Format implements Localized {
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/MeasurementRange.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/MeasurementRange.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/MeasurementRange.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/MeasurementRange.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -16,9 +16,9 @@
*/
package org.apache.sis.measure;
-import javax.measure.unit.Unit;
-import javax.measure.converter.UnitConverter;
-import javax.measure.converter.ConversionException;
+import javax.measure.Unit;
+import javax.measure.UnitConverter;
+import javax.measure.IncommensurableException;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.resources.Errors;
@@ -243,9 +243,9 @@ public class MeasurementRange<E extends
*
* @param targetUnit the target unit, or {@code null} for keeping the unit unchanged.
* @return the converted range, or {@code this} if no conversion is needed.
- * @throws ConversionException if the target unit are not compatible with this {@linkplain #unit() range unit}.
+ * @throws IncommensurableException if the target unit are not compatible with this {@linkplain #unit() range unit}.
*/
- public MeasurementRange<E> convertTo(final Unit<?> targetUnit) throws ConversionException {
+ public MeasurementRange<E> convertTo(final Unit<?> targetUnit) throws IncommensurableException {
return convertAndCast(elementType, targetUnit);
}
@@ -275,7 +275,7 @@ public class MeasurementRange<E extends
private <N extends E> Range<N> convert(final Range<N> range) throws IllegalArgumentException {
if (range instanceof MeasurementRange<?>) try {
return ((MeasurementRange<N>) range).convertAndCast(range.elementType, unit);
- } catch (ConversionException e) {
+ } catch (IncommensurableException e) {
throw new IllegalArgumentException(Errors.format(Errors.Keys.IncompatibleUnits_2,
((MeasurementRange<?>) range).unit, unit), e);
}
@@ -298,7 +298,7 @@ public class MeasurementRange<E extends
{
if (range instanceof MeasurementRange<?>) try {
return ((MeasurementRange<?>) range).convertAndCast(type, unit);
- } catch (ConversionException e) {
+ } catch (IncommensurableException e) {
throw new IllegalArgumentException(Errors.format(Errors.Keys.IncompatibleUnits_2,
((MeasurementRange<?>) range).unit, unit), e);
}
@@ -314,11 +314,11 @@ public class MeasurementRange<E extends
* {@link Integer}, {@link Long}, {@link Float} or {@link Double}.
* @param targetUnit the target unit, or {@code null} for no change.
* @return the casted range, or {@code this}.
- * @throws ConversionException if the given target unit is not compatible with the unit of this range.
+ * @throws IncommensurableException if the given target unit is not compatible with the unit of this range.
*/
@SuppressWarnings("unchecked")
private <N extends Number & Comparable<? super N>> MeasurementRange<N>
- convertAndCast(final Class<N> type, Unit<?> targetUnit) throws ConversionException
+ convertAndCast(final Class<N> type, Unit<?> targetUnit) throws IncommensurableException
{
if (targetUnit == null || targetUnit.equals(unit)) {
if (elementType == type) {
@@ -327,7 +327,7 @@ public class MeasurementRange<E extends
targetUnit = unit;
} else if (unit != null) {
final UnitConverter converter = unit.getConverterToAny(targetUnit);
- if (!converter.equals(UnitConverter.IDENTITY)) {
+ if (!converter.isIdentity()) {
boolean minInc = isMinIncluded;
boolean maxInc = isMaxIncluded;
double minimum = converter.convert(getMinDouble());
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/Range.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/Range.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/Range.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/Range.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -20,7 +20,7 @@ import java.util.Formatter;
import java.util.Formattable;
import java.util.FormattableFlags;
import java.io.Serializable;
-import javax.measure.unit.Unit;
+import javax.measure.Unit;
import org.apache.sis.internal.util.Utilities;
import org.apache.sis.internal.util.PatchedUnitFormat;
import org.apache.sis.util.collection.CheckedContainer;
@@ -86,7 +86,7 @@ import java.util.Objects;
* @author Martin Desruisseaux (Geomatys)
* @author Jody Garnett (for parameterized type inspiration)
* @since 0.3
- * @version 0.3
+ * @version 0.8
* @module
*
* @see RangeFormat
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/RangeFormat.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/RangeFormat.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/RangeFormat.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/RangeFormat.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -31,8 +31,7 @@ import java.text.AttributedCharacterIter
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
-import javax.measure.unit.Unit;
-import javax.measure.unit.UnitFormat;
+import javax.measure.Unit;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.UnconvertibleObjectException;
@@ -91,7 +90,7 @@ import org.apache.sis.util.resources.Err
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.3
- * @version 0.4
+ * @version 0.8
* @module
*
* @see Range#toString()
@@ -578,7 +577,7 @@ public class RangeFormat extends Format
}
field = MAX_VALUE_FIELD;
}
- toAppendTo.appendCodePoint( // Select the char for the first condition to be true below:
+ toAppendTo.appendCodePoint( // Select the char for the first condition to be true below:
isSingleton ? openSet :
range.isMinIncluded() ? openInclusive :
alternateForm ? openExclusiveAlt :
@@ -594,7 +593,7 @@ public class RangeFormat extends Format
int startPosition = toAppendTo.length();
if (value == null) {
switch (field) {
- case MIN_VALUE_FIELD: toAppendTo.append(minusSign); // Fall through
+ case MIN_VALUE_FIELD: toAppendTo.append(minusSign); // Fall through
case MAX_VALUE_FIELD: toAppendTo.append(infinity); break;
}
} else {
@@ -631,7 +630,7 @@ public class RangeFormat extends Format
toAppendTo.append(' ').append(separator).append(' ');
break;
}
- case MAX_VALUE_FIELD: { // Select the char for the first condition to be true below:
+ case MAX_VALUE_FIELD: { // Select the char for the first condition to be true below:
toAppendTo.appendCodePoint(
isSingleton ? closeSet :
range.isMaxIncluded() ? closeInclusive :
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/SexagesimalConverter.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/SexagesimalConverter.java?rev=1764673&r1=1764672&r2=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/SexagesimalConverter.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/SexagesimalConverter.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -16,12 +16,12 @@
*/
package org.apache.sis.measure;
-import java.math.BigDecimal;
-import java.math.MathContext;
-import javax.measure.unit.Unit;
-import javax.measure.unit.NonSI;
+import java.util.List;
+import java.util.Collections;
+import java.io.Serializable;
+import javax.measure.Unit;
import javax.measure.quantity.Angle;
-import javax.measure.converter.UnitConverter;
+import javax.measure.UnitConverter;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.resources.Vocabulary;
import org.apache.sis.internal.util.PatchedUnitFormat;
@@ -47,7 +47,7 @@ import static org.apache.sis.math.MathFu
* @version 0.6
* @module
*/
-class SexagesimalConverter extends UnitConverter { // Intentionally not final.
+class SexagesimalConverter implements UnitConverter, Serializable {
/**
* Serial number for compatibility with different versions.
*/
@@ -74,7 +74,7 @@ class SexagesimalConverter extends UnitC
* <p>This unit does not have an easily readable symbol because of the
* <a href="http://kenai.com/jira/browse/JSR_275-41">JSR-275 bug</a>.</p>
*/
- static final Unit<Angle> DM = NonSI.DEGREE_ANGLE.transform(
+ static final Unit<Angle> DM = Units.DEGREE.transform(
new SexagesimalConverter(false, 100).inverse()).asType(Angle.class);//.alternate("D.M");
/**
@@ -93,7 +93,7 @@ class SexagesimalConverter extends UnitC
* <p>This unit does not have an easily readable symbol because of the
* <a href="http://kenai.com/jira/browse/JSR_275-41">JSR-275 bug</a>.</p>
*/
- static final Unit<Angle> DMS = NonSI.DEGREE_ANGLE.transform(
+ static final Unit<Angle> DMS = Units.DEGREE.transform(
new SexagesimalConverter(true, 10000).inverse()).asType(Angle.class);//.alternate("D.MS");
/**
@@ -113,7 +113,7 @@ class SexagesimalConverter extends UnitC
* <p>This unit does not have an easily readable symbol because of the
* <a href="http://kenai.com/jira/browse/JSR_275-41">JSR-275 bug</a>.</p>
*/
- static final Unit<Angle> DMS_SCALED = NonSI.DEGREE_ANGLE.transform(
+ static final Unit<Angle> DMS_SCALED = Units.DEGREE.transform(
new SexagesimalConverter(true, 1).inverse()).asType(Angle.class);//.alternate("DMS");
/*
@@ -143,8 +143,8 @@ class SexagesimalConverter extends UnitC
/**
* Constructs a converter for sexagesimal units.
*
- * @param hasSeconds {@code true} if the seconds field is present.
- * @param divider The value to divide DMS unit by.
+ * @param hasSeconds {@code true} if the seconds field is present.
+ * @param divider the value to divide DMS unit by.
* For "degree minute second" (EPSG code 9107), this is 1.
* For "sexagesimal degree" (EPSG code 9110), this is 10000.
*/
@@ -165,6 +165,31 @@ class SexagesimalConverter extends UnitC
}
/**
+ * Returns {@code false} since this converter is not an identity function.
+ */
+ @Override
+ public boolean isIdentity() {
+ return false;
+ }
+
+ /**
+ * Returns {@code false} since the conversion is non-linear.
+ */
+ @Override
+ public boolean isLinear() {
+ return false;
+ }
+
+ /**
+ * Returns a collection containing only {@code this} since this conversion is not
+ * a concatenation of other converters.
+ */
+ @Override
+ public List<? extends UnitConverter> getConversionSteps() {
+ return Collections.singletonList(this);
+ }
+
+ /**
* Returns the inverse of this converter.
*/
@Override
@@ -181,7 +206,7 @@ class SexagesimalConverter extends UnitC
angle = (angle - deg) * 60;
if (hasSeconds) {
final double min = truncate(angle);
- angle = (angle - min) * 60; // Secondes
+ angle = (angle - min) * 60; // Secondes
angle += (deg*100 + min)*100;
} else {
angle += deg * 100;
@@ -192,11 +217,19 @@ class SexagesimalConverter extends UnitC
/**
* Performs a conversion from fractional degrees to sexagesimal degrees.
* This method delegates to the version working on {@code double} primitive type,
- * so it does not provide the accuracy normally required by this method contract.
+ * so it may not provide the accuracy normally required by this method contract.
+ */
+ @Override
+ public final Number convert(final Number value) {
+ return convert(value.doubleValue());
+ }
+
+ /**
+ * @todo not yet supported.
*/
@Override
- public final BigDecimal convert(final BigDecimal value, final MathContext context) {
- return new BigDecimal(convert(value.doubleValue()), context);
+ public UnitConverter concatenate(UnitConverter uc) {
+ throw new UnsupportedOperationException("Not supported yet.");
}
/**
@@ -250,7 +283,7 @@ class SexagesimalConverter extends UnitC
deg = truncate(min / 100);
min -= deg * 100;
}
- if (min <= -60 || min >= 60) { // Do not enter for NaN
+ if (min <= -60 || min >= 60) { // Do not enter for NaN
if (Math.abs(Math.abs(min) - 100) <= (EPS * 100)) {
if (min >= 0) deg++; else deg--;
min = 0;
@@ -258,7 +291,7 @@ class SexagesimalConverter extends UnitC
throw illegalField(angle, min, Vocabulary.Keys.AngularMinutes);
}
}
- if (sec <= -60 || sec >= 60) { // Do not enter for NaN
+ if (sec <= -60 || sec >= 60) { // Do not enter for NaN
if (Math.abs(Math.abs(sec) - 100) <= (EPS * 100)) {
if (sec >= 0) min++; else min--;
sec = 0;
@@ -272,10 +305,10 @@ class SexagesimalConverter extends UnitC
/**
* Creates an exception for an illegal field.
*
- * @param value The user-supplied angle value.
- * @param field The value of the illegal field.
- * @param unit The vocabulary key for the field (minutes or seconds).
- * @return The exception to throw.
+ * @param value the user-supplied angle value.
+ * @param field the value of the illegal field.
+ * @param unit the vocabulary key for the field (minutes or seconds).
+ * @return the exception to throw.
*/
private static IllegalArgumentException illegalField(final double value, final double field, final short unit) {
return new IllegalArgumentException(Errors.format(Errors.Keys.IllegalArgumentField_4,
Copied: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/UnitFormat.java (from r1764142, sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java)
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/UnitFormat.java?p2=sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/UnitFormat.java&p1=sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java&r1=1764142&r2=1764673&rev=1764673&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/internal/util/PatchedUnitFormat.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/measure/UnitFormat.java [UTF-8] Thu Oct 13 13:38:49 2016
@@ -14,181 +14,386 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.sis.internal.util;
+package org.apache.sis.measure;
-import java.util.Map;
-import java.util.HashMap;
+import java.util.Locale;
import java.text.Format;
import java.text.FieldPosition;
import java.text.ParsePosition;
-import javax.measure.unit.NonSI;
-import javax.measure.unit.SI;
-import javax.measure.unit.Unit;
-import javax.measure.unit.UnitFormat;
-import javax.measure.quantity.Quantity;
-import org.apache.sis.measure.Units;
-import org.apache.sis.util.Workaround;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import javax.measure.Unit;
+import javax.measure.format.ParserException;
+import org.apache.sis.internal.util.Constants;
+import org.apache.sis.internal.util.DefinitionURI;
+import org.apache.sis.internal.util.XPaths;
+import org.apache.sis.util.ArraysExt;
+import org.apache.sis.util.CharSequences;
+import org.apache.sis.util.Exceptions;
+import org.apache.sis.util.Localized;
+import org.apache.sis.util.resources.Errors;
/**
- * Workaround for JSR-275 issues.
+ * Parses and formats units of measurement as SI symbols, URI in OGC namespace or other symbols.
+ * This class combines in a single class the API from {@link java.text} and the API from {@link javax.measure.format}.
+ * In addition to the symbols of the <cite>Syst�me international</cite> (SI), this class is also capable to handle
+ * some symbols found in <cite>Well Known Text</cite> (WKT) definitions or in XML files.
+*
+* <div class="section">Parsing authority codes</div>
+* As a special case, if a character sequence given to the {@link #parse(CharSequence)} method is of the
+* {@code "EPSG:####"} or {@code "urn:ogc:def:uom:EPSG:####"} form (ignoring case and whitespaces),
+* then {@code "####"} is parsed as an integer and forwarded to the {@link Units#valueOfEPSG(int)} method.
+*
+* <div class="section">NetCDF unit symbols</div>
+* The attributes in NetCDF files often merge the axis direction with the angular unit,
+* as in {@code "degrees_east"} or {@code "degrees_north"}.
+* This class ignores those suffixes and unconditionally returns {@link Units#DEGREE} for all axis directions.
+* In particular, the units for {@code "degrees_west"} and {@code "degrees_east"} do <strong>not</strong> have
+* opposite sign. It is caller responsibility to handle the direction of axes associated to NetCDF units.
*
* @author Martin Desruisseaux (Geomatys)
- * @since 0.6
- * @version 0.6
+ * @since 0.8
+ * @version 0.8
* @module
+ *
+ * @see Units#valueOf(String)
*/
-@Workaround(library="JSR-275", version="0.9.3")
-public final class PatchedUnitFormat extends Format {
+public class UnitFormat extends Format implements javax.measure.format.UnitFormat, Localized {
/**
- * For cross-version compatibility (even if this class is hopefully temporary).
+ * For cross-version compatibility.
*/
private static final long serialVersionUID = -3064428584419360693L;
/**
- * The symbols for some units defined by Apache SIS. We store here the symbols that we were not able
- * to set in the units created by {@link org.apache.sis.measure.SexagesimalConverter} because of
- * <a href="http://kenai.com/jira/browse/JSR_275-41">JSR-275 bug</a>.
- *
- * <p>We do not bother making this map unmodifiable. This is okay if this map is never modified
- * after this field has been assigned a value.</p>
+ * The suffixes that NetCDF files sometime put after the "degrees" unit.
+ * Suffix at even index are for axes having the standard geometric direction,
+ * while suffix at odd index are for axes having the reverse direction.
*/
- private static volatile Map<Unit<?>,String> SYMBOLS;
+ private static final String[] CARDINAL_DIRECTIONS = {"east", "west", "north", "south"};
/**
- * Invoked by {@code SexagesimalConverter} static class initializer for declaring the SIS units
- * that JSR-275 0.9.3 can not format by itself. This method should not be invoked in any other
- * circumstance, otherwise an {@link IllegalStateException} will be thrown.
- *
- * @param entries The (unit, symbol) pairs.
+ * The default instance used by {@link Units#valueOf(String)} for parsing units of measurement.
*/
- public static void init(final Object... entries) {
- final Map<Unit<?>,String> symbols = new HashMap<>(8);
- for (int i=0; i<entries.length; i++) {
- final String uom;
- if (symbols.put((Unit<?>) entries[i], uom = (String) entries[++i]) != null) {
- throw new IllegalArgumentException(uom); // Duplicated unit.
- }
- }
- if (SYMBOLS != null) { // Check on a best-effort basis only (ignoring race conditions).
- throw new IllegalStateException();
- }
- SYMBOLS = symbols;
- }
+ static final UnitFormat INSTANCE = new UnitFormat();
+
+ /**
+ * Temporary helper class before we replace by our own implementation.
+ */
+ private final javax.measure.format.UnitFormat delegate = tec.units.ri.format.SimpleUnitFormat.getInstance();
/**
- * The {@link UnitFormat} to patch.
+ * The locale specified at construction time.
*/
- private final UnitFormat format;
+ private Locale locale;
/**
* {@code true} for formatting the unit names using US spelling.
* Example: "meter" instead of "metre".
*/
- public boolean isLocaleUS;
+ private boolean isLocaleUS;
/**
- * Creates a new {@code PatchedUnitFormat} instance wrapping the given format.
+ * Creates a new format for the given locale.
*
- * @param format the format to wrap.
+ * @param locale the locale to use for parsing and formatting units.
+ * @return a new {@code UnitFormat} instance using the given locale.
+ */
+ public static UnitFormat getInstance(final Locale locale) {
+ final UnitFormat f = new UnitFormat();
+ f.setLocale(locale);
+ return f;
+ }
+
+ /**
+ * Creates a new format initialized to the {@link Locale#ROOT} locale.
*/
- public PatchedUnitFormat(final UnitFormat format) {
- this.format = format;
+ private UnitFormat() {
+ locale = Locale.ROOT;
}
/**
- * If the given unit is one of the unit that can not be formatted without ambiguity in WKT format,
- * return a proposed replacement. Otherwise returns {@code unit} unchanged.
+ * Returns the locale used by this {@code UnitFormat}.
*
- * @param <Q> The unit dimension.
- * @param unit The unit to test.
- * @return The replacement to format, or {@code unit} if not needed.
+ * @return the locale of this {@code UnitFormat}.
*/
- @SuppressWarnings("unchecked")
- public static <Q extends Quantity> Unit<Q> toFormattable(Unit<Q> unit) {
- final Map<Unit<?>,String> symbols = SYMBOLS;
- if (symbols != null && symbols.containsKey(unit)) {
- assert Units.isAngular(unit);
- unit = (Unit<Q>) NonSI.DEGREE_ANGLE;
- }
- return unit;
+ @Override
+ public Locale getLocale() {
+ return locale;
}
/**
- * Returns the string representation of the given unit, or {@code null} if none.
- * This method is used as a workaround for a bug in JSR-275, which sometime throws
- * an exception in the {@link Unit#toString()} method.
+ * Sets the locale used by this {@code UnitFormat}.
*
- * @param unit The unit for which to get a string representation, or {@code null}.
- * @return The string representation of the given string (may be an empty string), or {@code null}.
+ * @param locale the new locale for this {@code UnitFormat}.
*/
- @Workaround(library="JSR-275", version="0.9.3")
- public static String toString(final Unit<?> unit) {
- if (unit != null) {
- final Map<Unit<?>,String> symbols = SYMBOLS;
- if (symbols != null) {
- final String symbol = symbols.get(unit);
- if (symbol != null) {
- return symbol;
- }
- }
- try {
- String text = unit.toString();
- if (text.equals("deg")) {
- text = "�";
- }
- return text;
- } catch (IllegalArgumentException e) {
- // Workaround for JSR-275 implementation bug.
- // Do nothing, we will return null below.
- }
- }
- return null;
+ public void setLocale(final Locale locale) {
+ isLocaleUS = locale.getCountry().equalsIgnoreCase("US");
+ this.locale = locale;
}
/**
- * Formats the given unit.
+ * Returns {@code true} since this {@code UnitFormat} depends on the {@link Locale}
+ * given at construction time for performing its tasks.
*
- * @param unit The unit to format.
- * @param toAppendTo where to append to unit.
- * @param pos Ignored.
- * @return The given {@code toAppendTo} argument.
+ * @return {@code true}.
*/
@Override
- public StringBuffer format(final Object unit, final StringBuffer toAppendTo, final FieldPosition pos) {
- final Map<Unit<?>,String> symbols = SYMBOLS;
- if (symbols != null) {
- final String symbol = symbols.get(unit);
- if (symbol != null) {
- return toAppendTo.append(symbol);
- }
+ public boolean isLocaleSensitive() {
+ return true;
+ }
+
+ /**
+ * Attaches a label to the specified unit.
+ * If the specified label is already associated to another unit, then this method does nothing.
+ *
+ * @param unit the unit being labeled.
+ * @param label the new label for the given unit.
+ */
+ @Override
+ public void label(final Unit<?> unit, final String label) {
+ delegate.label(unit, label);
+ }
+
+ /**
+ * Formats the specified unit.
+ *
+ * @param unit the unit to format.
+ * @param toAppendTo where to format the unit.
+ * @return the given {@code toAppendTo} argument, for method calls chaining.
+ * @throws IOException if an error occurred while writing to the destination.
+ */
+ @Override
+ public Appendable format(final Unit<?> unit, final Appendable toAppendTo) throws IOException {
+ final String symbol = org.apache.sis.internal.util.PatchedUnitFormat.getSymbol(unit);
+ if (symbol != null) {
+ return toAppendTo.append(symbol);
}
/*
* Following are specific to the WKT format, which is currently the only user of this method.
* If we invoke this method for other purposes, then we would need to provide more control on
* what kind of formatting is desired.
*/
- if (Unit.ONE.equals(unit)) {
+ if (Units.ONE.equals(unit)) {
return toAppendTo.append("unity");
- } else if (NonSI.DEGREE_ANGLE.equals(unit)) {
+ } else if (Units.DEGREE.equals(unit)) {
return toAppendTo.append("degree");
- } else if (SI.METRE.equals(unit)) {
+ } else if (Units.METRE.equals(unit)) {
return toAppendTo.append(isLocaleUS ? "meter" : "metre");
- } else if (NonSI.FOOT_SURVEY_US.equals(unit)) {
+ } else if (Units.FOOT_SURVEY_US.equals(unit)) {
return toAppendTo.append("US survey foot");
} else if (Units.PPM.equals(unit)) {
return toAppendTo.append("parts per million");
}
- return format.format(unit, toAppendTo, pos);
+ return delegate.format(unit, toAppendTo);
}
/**
- * Delegates to the wrapped {@link UnitFormat}.
+ * Formats the specified unit.
*
- * @return The parsed unit, or {@code null}.
+ * @param unit the unit to format.
+ * @param toAppendTo where to format the unit.
+ * @param pos where to store the position of a formatted field.
+ * @return the given {@code toAppendTo} argument, for method calls chaining.
*/
@Override
- public Object parseObject(final String source, final ParsePosition pos) {
- return format.parseObject(source, pos);
+ public StringBuffer format(final Object unit, final StringBuffer toAppendTo, final FieldPosition pos) {
+ try {
+ return (StringBuffer) format((Unit<?>) unit, toAppendTo);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e); // Should never happen since we are writting to a StringBuffer.
+ }
+ }
+
+ /**
+ * Formats the given unit.
+ *
+ * @param unit the unit to format.
+ * @return the formatted unit.
+ */
+ @Override
+ public String format(final Unit<?> unit) {
+ try {
+ return format(unit, new StringBuilder()).toString();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e); // Should never happen since we are writting to a StringBuilder.
+ }
+ }
+
+ /**
+ * Parses the given text as an instance of {@code Unit}.
+ * If the parse completes without reading the entire length of the text, an exception is thrown.
+ *
+ * @param symbols the unit symbols or URI to parse.
+ * @return the unit parsed from the specified symbols.
+ * @throws ParserException if a problem occurred while parsing the given symbols.
+ *
+ * @see Units#valueOf(String)
+ */
+ @Override
+ public Unit<?> parse(final CharSequence symbols) throws ParserException {
+ String uom = CharSequences.trimWhitespaces(CharSequences.toASCII(symbols)).toString();
+ final int length = uom.length();
+ /*
+ * Check for authority codes (currently only EPSG, but more could be added later).
+ * If the unit is not an authority code (which is the most common case), then we
+ * will check for hard-coded unit symbols.
+ *
+ * DefinitionURI.codeOf(\u2026) returns 'uom' directly (provided that whitespaces were already trimmed)
+ * if no ':' character were found, in which case the string is assumed to be the code directly.
+ * This is the intended behavior for AuthorityFactory, but in the particular case of this method
+ * we want to try to parse as a xpointer before to give up.
+ */
+ if (isURI(uom)) {
+ String code = DefinitionURI.codeOf("uom", Constants.EPSG, uom);
+ if (code != null && code != uom) try { // Really identity check, see above comment.
+ return Units.valueOfEPSG(Integer.parseInt(code));
+ } catch (NumberFormatException e) {
+ throw (ParserException) new ParserException(
+ Errors.format(Errors.Keys.IllegalArgumentValue_2, "symbols", symbols),
+ uom, Math.max(0, uom.indexOf(code))).initCause(e);
+ }
+ code = XPaths.xpointer("uom", uom);
+ if (code != null) {
+ uom = code;
+ }
+ }
+ /*
+ * Check for degrees units. Note that "deg" could be both angular and Celsius degrees.
+ * We try to resolve this ambiguity in the code below by looking for the "Celsius" suffix.
+ * Other suffixes commonly found in NetCDF files are "west", "east", "north" or "south".
+ * Those suffixes are ignored.
+ */
+ if (uom.regionMatches(true, 0, "deg", 0, 3)) {
+ switch (length) {
+ case 3: return Units.DEGREE; // Exactly "deg"
+ case 4: {
+ if (uom.charAt(3) == 'K') { // Exactly "degK"
+ return Units.KELVIN;
+ }
+ break;
+ }
+ }
+ String prefix = uom;
+ boolean isTemperature = false;
+ final int s = Math.max(uom.lastIndexOf(' '), uom.lastIndexOf('_'));
+ if (s >= 1) {
+ final String suffix = (String) CharSequences.trimWhitespaces(uom, s+1, length);
+ if (ArraysExt.containsIgnoreCase(CARDINAL_DIRECTIONS, suffix) || (isTemperature = isCelsius(suffix))) {
+ prefix = (String) CharSequences.trimWhitespaces(uom, 0, s); // Remove the suffix only if we recognized it.
+ }
+ }
+ if (equalsIgnorePlural(prefix, "degree")) {
+ return isTemperature ? Units.CELSIUS : Units.DEGREE;
+ }
+ } else {
+ /*
+ * Check for unit symbols that do not begin with "deg". If a symbol begins
+ * with "deg", then the check should be put in the above block instead.
+ */
+ if (uom.equals("�") || equalsIgnorePlural(uom, "decimal_degree")) return Units.DEGREE;
+ if (uom.equalsIgnoreCase("arcsec")) return Units.ARC_SECOND;
+ if (uom.equalsIgnoreCase("rad") || equalsIgnorePlural(uom, "radian")) return Units.RADIAN;
+ if (equalsIgnorePlural(uom, "meter") || equalsIgnorePlural(uom, "metre")) return Units.METRE;
+ if (equalsIgnorePlural(uom, "kilometer") || equalsIgnorePlural(uom, "kilometre")) return Units.KILOMETRE;
+ if (equalsIgnorePlural(uom, "week")) return Units.WEEK;
+ if (equalsIgnorePlural(uom, "day")) return Units.DAY;
+ if (equalsIgnorePlural(uom, "hour")) return Units.HOUR;
+ if (equalsIgnorePlural(uom, "minute")) return Units.MINUTE;
+ if (equalsIgnorePlural(uom, "second")) return Units.SECOND;
+ if (equalsIgnorePlural(uom, "grade")) return Units.GRAD;
+ if (equalsIgnorePlural(uom, "grad")) return Units.GRAD;
+ if (isCelsius(uom)) return Units.CELSIUS;
+ if (uom.isEmpty()) return Units.ONE;
+ if (uom.equalsIgnoreCase("US survey foot")) return Units.FOOT_SURVEY_US;
+ if (uom.equalsIgnoreCase("ppm")) return Units.PPM;
+ if (uom.equalsIgnoreCase("psu")) return Units.PSU;
+ if (uom.equalsIgnoreCase("sigma")) return Units.SIGMA;
+ if (equalsIgnorePlural(uom, "pixel")) return Units.PIXEL;
+ }
+ final Unit<?> unit;
+ try {
+ unit = delegate.parse(symbols);
+ } catch (ParserException e) {
+ // Provides a better error message than the default JSR-275 0.9.4 implementation.
+ throw Exceptions.setMessage(e, Errors.format(Errors.Keys.IllegalArgumentValue_2, "uom", uom), true);
+ }
+ /*
+ * Special case: JSR-275 version 0.6.1 parses "1/s" and "s-1" as "Baud", which is not what
+ * we use in geoscience. Replace "Baud" by "Hertz" if the symbol was not explicitely "Bd".
+ */
+ if (unit.isCompatible(Units.HERTZ) && !uom.equals("Bd")) {
+ return Units.HERTZ;
+ }
+ return UnitsMap.canonicalize(unit);
+ }
+
+ /**
+ * Returns {@code true} if the given {@code uom} is equals to the given expected string,
+ * ignoring trailing {@code 's'} character (if any).
+ */
+ @SuppressWarnings("fallthrough")
+ private static boolean equalsIgnorePlural(final String uom, final String expected) {
+ final int length = expected.length();
+ switch (uom.length() - length) {
+ case 0: break; // uom has exactly the expected length.
+ case 1: if (Character.toLowerCase(uom.charAt(length)) == 's') break; // else fallthrough.
+ default: return false;
+ }
+ return uom.regionMatches(true, 0, expected, 0, length);
+ }
+
+ /**
+ * Returns {@code true} if the given {@code uom} is equals to {@code "Celsius"} or {@code "Celcius"}.
+ * The later is a common misspelling.
+ */
+ private static boolean isCelsius(final String uom) {
+ return uom.equalsIgnoreCase("Celsius") || uom.equalsIgnoreCase("Celcius");
+ }
+
+ /**
+ * Returns {@code true} if the given unit seems to be an URI.
+ * Examples:
+ * <ul>
+ * <li>{@code "urn:ogc:def:uom:EPSG::9001"}</li>
+ * <li>{@code "http://schemas.opengis.net/iso/19139/20070417/resources/uom/gmxUom.xml#xpointer(//*[@gml:id='m'])"}</li>
+ * </ul>
+ */
+ private static boolean isURI(final CharSequence uom) {
+ for (int i=uom.length(); --i>=0;) {
+ final char c = uom.charAt(i);
+ if (c == ':' || c == '#') {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Parses the given text as an instance of {@code Unit}.
+ *
+ * @param symbols the unit symbols to parse.
+ * @param pos on input, index of the first character to parse.
+ * On output, index after the last parsed character.
+ * @return the unit parsed from the specified symbols.
+ * @throws ParserException if a problem occurred while parsing the given symbols.
+ */
+ @Override
+ public Object parseObject(final String symbols, final ParsePosition pos) {
+ final int start = pos.getIndex();
+ int stop = start;
+ while (stop < symbols.length()) {
+ final int c = symbols.codePointAt(stop);
+ if (Character.isWhitespace(c) || c == ']') break; // Temporary hack before we implement our own parser.
+ stop += Character.charCount(c);
+ }
+ try {
+ final Unit<?> unit = parse(symbols.substring(start, stop));
+ pos.setIndex(stop);
+ return unit;
+ } catch (ParserException e) {
+ pos.setErrorIndex(start);
+ return null;
+ }
}
}