Search in sources :

Example 11 with DefaultGeometryProperty

use of eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty in project hale by halestudio.

the class MsSqlGeometries method convertToInstanceGeometry.

/**
 * @see eu.esdihumboldt.hale.io.jdbc.GeometryAdvisor#convertToInstanceGeometry(java.lang.Object,
 *      eu.esdihumboldt.hale.common.schema.model.TypeDefinition,
 *      java.lang.Object, java.util.function.Supplier)
 */
@Override
public GeometryProperty<?> convertToInstanceGeometry(Object geom, TypeDefinition columnType, SQLServerConnection connection, Supplier<CRSDefinition> crsProvider) throws Exception {
    Statement stmt = null;
    ResultSet rs = null;
    try {
        // We need Column Data type
        String columnDataType = columnType.getName().getLocalPart();
        String geomAsHex = BaseEncoding.base16().lowerCase().encode((byte[]) geom);
        String sqlGeom = // 
        "SELECT top 1 GeomConvert.geom.STSrid srid, GeomConvert.geom.STAsText() as geomAsText, GeomConvert.geom.STGeometryType() as geomType " + // 
        "FROM " + "(SELECT cast(cast(temp.wkb as varbinary(max)) as " + columnDataType + // 
        ") as geom " + // 
        "FROM " + "( select " + "0x" + geomAsHex + // 
        " as wkb) as temp" + // 
        ") " + // 
        "as GeomConvert";
        stmt = connection.createStatement();
        rs = stmt.executeQuery(sqlGeom);
        Geometry jtsGeom = null;
        int srId = 0;
        if (rs.next()) {
            srId = rs.getInt(1);
            String geomAsText = rs.getString(2);
            String geomType = rs.getString(3);
            // WKTReader does not support CircularString, CurvePolygon,
            // CompoundCurve
            WKTReader wktReader = getSpecificWktReader(geomType);
            try {
                // conversion to JTS via WKT
                jtsGeom = wktReader.read(geomAsText);
            } catch (ParseException e) {
                log.error("Could not load geometry from database", e);
            }
        }
        CRSDefinition crsDef = null;
        String authName = SRSUtil.getAuthorityName(srId, connection);
        if (authName != null && authName.equals("EPSG")) {
            // For geography/geometry data type, SQL server assumes lon/lat
            // axis order, if we read using SQL function
            String epsgCode = authName + ":" + SRSUtil.getSRS(srId, connection);
            if (columnDataType.equals("geography"))
                crsDef = new CodeDefinition(epsgCode, true);
            else
                crsDef = new CodeDefinition(epsgCode, null);
        } else {
            String wkt = SRSUtil.getSRSText(srId, connection);
            if (wkt != null) {
                crsDef = new WKTDefinition(wkt, null);
            }
        }
        if (crsDef == null) {
            log.warn("Could not find spatial reference system id " + srId + " in MS sql server");
            crsDef = crsProvider.get();
            if (crsDef == null) {
                log.warn("Could not retrieve default spatial reference for " + srId + " in MS sql server");
            }
            // saving in cache
            if (crsDef != null) {
                String srsName = CRS.toSRS(crsDef.getCRS());
                if (srsName != null) {
                    final int index = srsName.lastIndexOf(':');
                    String authorityName = null;
                    String authorizedId = null;
                    if (index > 0) {
                        authorityName = srsName.substring(0, index);
                        authorizedId = srsName.substring(index + 1).trim();
                    }
                    // we don't need wkt.
                    SRSUtil.addSRSinCache(srId, authorityName, authorizedId, null);
                }
            }
        }
        return new DefaultGeometryProperty<Geometry>(crsDef, jtsGeom);
    } finally {
        if (rs != null)
            try {
                rs.close();
            } catch (Exception e) {
            // 
            }
        if (stmt != null)
            try {
                stmt.close();
            } catch (Exception e) {
            // 
            }
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) DefaultGeometryProperty(eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty) CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition) CodeDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.CodeDefinition) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) ParseException(com.vividsolutions.jts.io.ParseException) WKTDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.WKTDefinition) WKTReader(com.vividsolutions.jts.io.WKTReader) ParseException(com.vividsolutions.jts.io.ParseException)

Example 12 with DefaultGeometryProperty

use of eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty in project hale by halestudio.

the class PostGISGeometries method convertToInstanceGeometry.

/**
 * @see eu.esdihumboldt.hale.io.jdbc.GeometryAdvisor#convertToInstanceGeometry(java.lang.Object,
 *      eu.esdihumboldt.hale.common.schema.model.TypeDefinition,
 *      java.lang.Object, java.util.function.Supplier)
 */
@Override
public GeometryProperty<?> convertToInstanceGeometry(Object geom, TypeDefinition columnType, PGConnection connection, Supplier<CRSDefinition> crsProvider) throws Exception {
    if (geom instanceof PGgeometry) {
        PGgeometry pgeom = (PGgeometry) geom;
        // conversion to JTS via WKT
        // TODO use better conversion (p4b?)
        WKTReader2 reader = new WKTReader2();
        String value = pgeom.getGeometry().toString();
        if (value.startsWith(PGgeometry.SRIDPREFIX) && value.indexOf(';') >= 0) {
            value = value.substring(value.indexOf(';') + 1);
        }
        Geometry jtsGeom = reader.read(value);
        // determine CRS
        GeometryMetadata columnTypeMetadata = columnType.getConstraint(GeometryMetadata.class);
        CRSDefinition crsDef = null;
        String authName = columnTypeMetadata.getAuthName();
        if (authName != null && authName.equals("EPSG")) {
            // PostGIS assumes lon/lat order
            crsDef = new CodeDefinition(authName + ":" + columnTypeMetadata.getSrs(), true);
        } else {
            String wkt = columnTypeMetadata.getSrsText();
            if (wkt != null) {
                crsDef = new WKTDefinition(wkt, null);
            }
        }
        return new DefaultGeometryProperty<Geometry>(crsDef, jtsGeom);
    }
    throw new IllegalArgumentException("Only conversion of PGgeometry supported");
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) GeometryMetadata(eu.esdihumboldt.hale.common.schema.model.constraint.type.GeometryMetadata) DefaultGeometryProperty(eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty) CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition) CodeDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.CodeDefinition) MultiLineString(com.vividsolutions.jts.geom.MultiLineString) WKTDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.WKTDefinition) WKTReader2(org.geotools.geometry.jts.WKTReader2) PGgeometry(org.postgis.PGgeometry)

Example 13 with DefaultGeometryProperty

use of eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty in project hale by halestudio.

the class StreamGmlHelper method parseInstance.

/**
 * Parses an instance with the given type from the given XML stream reader.
 *
 * @param reader the XML stream reader, the current event must be the start
 *            element of the instance
 * @param type the definition of the instance type
 * @param indexInStream the index of the instance in the stream or
 *            <code>null</code>
 * @param strict if associating elements with properties should be done
 *            strictly according to the schema, otherwise a fall-back is
 *            used trying to populate values also on invalid property paths
 * @param srsDimension the dimension of the instance or <code>null</code>
 * @param crsProvider CRS provider in case no CRS is specified, may be
 *            <code>null</code>
 * @param parentType the type of the topmost instance
 * @param propertyPath the property path down from the topmost instance, may
 *            be <code>null</code>
 * @param allowNull if a <code>null</code> result is allowed
 * @param ignoreNamespaces if parsing of the XML instances should allow
 *            types and properties with namespaces that differ from those
 *            defined in the schema
 * @param ioProvider the I/O Provider to get value
 * @param crs The <code>CRSDefinition</code> to use for geometries
 * @return the parsed instance, may be <code>null</code> if allowNull is
 *         <code>true</code>
 * @throws XMLStreamException if parsing the instance failed
 */
public static Instance parseInstance(XMLStreamReader reader, TypeDefinition type, Integer indexInStream, boolean strict, Integer srsDimension, CRSProvider crsProvider, TypeDefinition parentType, List<QName> propertyPath, boolean allowNull, boolean ignoreNamespaces, IOProvider ioProvider, CRSDefinition crs) throws XMLStreamException {
    checkState(reader.getEventType() == XMLStreamConstants.START_ELEMENT);
    if (propertyPath == null) {
        propertyPath = Collections.emptyList();
    }
    if (srsDimension == null) {
        String dim = reader.getAttributeValue(null, "srsDimension");
        if (dim != null)
            srsDimension = Integer.parseInt(dim);
    }
    // extract additional settings from I/O provider
    boolean suppressParsingGeometry = ioProvider.getParameter(StreamGmlReader.PARAM_SUPPRESS_PARSE_GEOMETRY).as(Boolean.class, false);
    MutableInstance instance;
    if (indexInStream == null) {
        // not necessary to associate data set
        instance = new DefaultInstance(type, null);
    } else {
        instance = new StreamGmlInstance(type, indexInStream);
    }
    // If the current instance has an srsName attribute, try to resolve the
    // corresponding CRS and pass it down the hierarchy and use it for
    // nested geometries that don't have their own srsName.
    CRSDefinition lastCrs = crs;
    String srsName = reader.getAttributeValue(null, "srsName");
    if (srsName != null) {
        lastCrs = CodeDefinition.tryResolve(srsName);
        if (lastCrs == null && crsProvider != null) {
            // In case the srsName value could not be resolved to a CRS, try
            // to resolve the CRS via the crsProvider.
            CRSDefinition unresolvedCrs = new CodeDefinition(srsName);
            CRSDefinition resolvedCrs = crsProvider.getCRS(parentType, propertyPath, unresolvedCrs);
            // unresolvedCrs unchanged
            if (resolvedCrs != null && !resolvedCrs.equals(unresolvedCrs)) {
                lastCrs = resolvedCrs;
            }
        }
    // If the provided CRS could not be resolved, it will be ignored
    // here silently, so that use cases that don't need the CRS will not
    // fail.
    }
    boolean mixed = type.getConstraint(XmlMixedFlag.class).isEnabled();
    if (!mixed) {
        // mixed types are treated special (see else)
        // check if xsi:nil attribute is there and set to true
        String nilString = reader.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil");
        boolean isNil = nilString != null && "true".equalsIgnoreCase(nilString);
        // instance properties
        parseProperties(reader, instance, strict, srsDimension, crsProvider, lastCrs, parentType, propertyPath, false, ignoreNamespaces, ioProvider);
        // nil instance w/o properties
        if (allowNull && isNil && Iterables.isEmpty(instance.getPropertyNames())) {
        // no value should be created
        /*
				 * XXX returning null here then results in problems during
				 * adding other properties to the parent group, as mandatory
				 * elements are expected to appear, and it will warn about
				 * possible invalid data loaded
				 */
        // return null;
        }
        // instance value
        if (!hasElements(type)) {
            /*
				 * Value can only be determined if there are no documents,
				 * because otherwise elements have already been processed in
				 * parseProperties and we are already past END_ELEMENT.
				 */
            if (type.getConstraint(HasValueFlag.class).isEnabled()) {
                // try to get text value
                String value = reader.getElementText();
                if (!isNil && value != null) {
                    instance.setValue(convertSimple(type, value));
                }
            }
        }
    } else {
        /*
			 * XXX For a mixed type currently ignore elements and parse only
			 * attributes and text.
			 */
        // instance properties (attributes only)
        parseProperties(reader, instance, strict, srsDimension, crsProvider, lastCrs, parentType, propertyPath, true, ignoreNamespaces, ioProvider);
        // combined text
        String value = readText(reader);
        if (value != null) {
            instance.setValue(convertSimple(type, value));
        }
    }
    // augmented value XXX should this be an else if?
    if (!suppressParsingGeometry && type.getConstraint(AugmentedValueFlag.class).isEnabled()) {
        // add geometry as a GeometryProperty value where applicable
        GeometryFactory geomFactory = type.getConstraint(GeometryFactory.class);
        Object geomValue = null;
        // the default value for the srsDimension
        int defaultValue = 2;
        try {
            if (srsDimension != null) {
                geomValue = geomFactory.createGeometry(instance, srsDimension, ioProvider);
            } else {
                // srsDimension is not set
                geomValue = geomFactory.createGeometry(instance, defaultValue, ioProvider);
            }
        } catch (Exception e) {
            /*
				 * Catch IllegalArgumentException that e.g. occurs if a linear
				 * ring has to few points. NullPointerExceptions may occur
				 * because an internal geometry could not be created.
				 * 
				 * XXX a problem is that these messages will not appear in the
				 * report
				 */
            log.error("Error creating geometry", e);
        }
        if (geomValue != null && crsProvider != null && propertyPath != null) {
            // check if CRS are set, and if not, try determining them using
            // the CRS provider
            Collection<?> values;
            if (geomValue instanceof Collection) {
                values = (Collection<?>) geomValue;
            } else {
                values = Collections.singleton(geomValue);
            }
            List<Object> resultVals = new ArrayList<Object>();
            for (Object value : values) {
                if (value instanceof Geometry || (value instanceof GeometryProperty<?> && ((GeometryProperty<?>) value).getCRSDefinition() == null)) {
                    // try to resolve value of srsName attribute
                    CRSDefinition geometryCrs = crsProvider.getCRS(parentType, propertyPath, lastCrs);
                    if (geometryCrs != null) {
                        Geometry geom = (value instanceof Geometry) ? ((Geometry) value) : (((GeometryProperty<?>) value).getGeometry());
                        resultVals.add(new DefaultGeometryProperty<Geometry>(geometryCrs, geom));
                        continue;
                    }
                }
                resultVals.add(value);
            }
            if (resultVals.size() == 1) {
                geomValue = resultVals.get(0);
            } else {
                geomValue = resultVals;
            }
        }
        if (geomValue != null) {
            instance.setValue(geomValue);
        }
    }
    return instance;
}
Also used : DefaultGeometryProperty(eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty) GeometryProperty(eu.esdihumboldt.hale.common.schema.geometry.GeometryProperty) GeometryFactory(eu.esdihumboldt.hale.io.gml.geometry.constraint.GeometryFactory) CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition) HasValueFlag(eu.esdihumboldt.hale.common.schema.model.constraint.type.HasValueFlag) ArrayList(java.util.ArrayList) XMLStreamException(javax.xml.stream.XMLStreamException) Geometry(com.vividsolutions.jts.geom.Geometry) CodeDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.CodeDefinition) XmlMixedFlag(eu.esdihumboldt.hale.io.xsd.constraint.XmlMixedFlag) DefaultInstance(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance) MutableInstance(eu.esdihumboldt.hale.common.instance.model.MutableInstance) Collection(java.util.Collection)

Example 14 with DefaultGeometryProperty

use of eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty in project hale by halestudio.

the class ReprojectGeometryTest method testReproject.

@SuppressWarnings("javadoc")
@Test
public void testReproject() throws Exception {
    TestData tr = new TestData(TestDataConfiguration.REPROJECT);
    List<Instance> result = transformData(tr);
    assertTrue(result.size() > 0);
    Geometry aspectedGeometry = null;
    InstanceCollection sourceInstances = tr.getSourceInstances();
    Iterator<Instance> sit = sourceInstances.iterator();
    if (sit.hasNext()) {
        Instance i = sit.next();
        DefaultInstance di = (DefaultInstance) (i.getProperty(new QName("eu:esdihumboldt:hale:test", "geometry"))[0]);
        DefaultGroup dg = (DefaultGroup) (di.getProperty(new QName("http://www.opengis.net/gml/_Geometry", "choice"))[0]);
        DefaultInstance dig = (DefaultInstance) (dg.getProperty(new QName("http://www.opengis.net/gml", "Point"))[0]);
        DefaultGeometryProperty<?> value = (DefaultGeometryProperty<?>) dig.getValue();
        DefaultGeometryProperty<?> geom = value;
        MathTransform transform = CRS.findMathTransform(geom.getCRSDefinition().getCRS(), CRS.decode("EPSG:4326"), false);
        aspectedGeometry = JTS.transform(geom.getGeometry(), transform);
    }
    assertNotNull(aspectedGeometry);
    Instance resultInstance = result.get(0);
    DefaultGeometryProperty<?> geom = (DefaultGeometryProperty<?>) ((DefaultInstance) resultInstance.getProperty(new QName("eu:esdihumboldt:hale:test", "geometry"))[0]).getValue();
    String code = CRS.lookupIdentifier(geom.getCRSDefinition().getCRS(), true);
    assertEquals("EPSG:4326", code);
    assertEquals(aspectedGeometry.getCoordinate().x, geom.getGeometry().getCoordinate().x, 0);
    assertEquals(aspectedGeometry.getCoordinate().y, geom.getGeometry().getCoordinate().y, 0);
}
Also used : MathTransform(org.opengis.referencing.operation.MathTransform) Instance(eu.esdihumboldt.hale.common.instance.model.Instance) DefaultInstance(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance) QName(javax.xml.namespace.QName) InstanceCollection(eu.esdihumboldt.hale.common.instance.model.InstanceCollection) DefaultGroup(eu.esdihumboldt.hale.common.instance.model.impl.DefaultGroup) Geometry(com.vividsolutions.jts.geom.Geometry) DefaultGeometryProperty(eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty) DefaultInstance(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance) AbstractTransformationTest(eu.esdihumboldt.cst.test.AbstractTransformationTest) Test(org.junit.Test)

Example 15 with DefaultGeometryProperty

use of eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty in project hale by halestudio.

the class OrdinatesToPoint method evaluate.

/**
 * @see eu.esdihumboldt.hale.common.align.transformation.function.impl.AbstractPropertyTransformation#evaluate(java.lang.String,
 *      eu.esdihumboldt.hale.common.align.transformation.engine.TransformationEngine,
 *      com.google.common.collect.ListMultimap,
 *      com.google.common.collect.ListMultimap, java.util.Map,
 *      eu.esdihumboldt.hale.common.align.transformation.report.TransformationLog)
 */
@Override
protected Object evaluate(String transformationIdentifier, TransformationEngine engine, ListMultimap<String, PropertyValue> variables, String resultName, PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log) throws TransformationException {
    // get x, y and z properties
    PropertyValue x = variables.get("x").get(0);
    PropertyValue y = variables.get("y").get(0);
    PropertyValue z = null;
    if (!variables.get("z").isEmpty())
        z = variables.get("z").get(0);
    // get crs definition if srs is specified
    CRSDefinition crsDef = null;
    String srs = getOptionalParameter(PARAMETER_REFERENCE_SYSTEM, null).as(String.class);
    if (srs != null)
        crsDef = new CodeDefinition(srs, null);
    // convert values to double and create a point
    double xValue = x.getValueAs(Double.class);
    double yValue = y.getValueAs(Double.class);
    Point resultPoint;
    GeometryFactory geomFactory = new GeometryFactory();
    if (z == null)
        resultPoint = geomFactory.createPoint(new Coordinate(xValue, yValue));
    else
        resultPoint = geomFactory.createPoint(new Coordinate(xValue, yValue, z.getValueAs(Double.class)));
    // pack result into geometry property and return it
    GeometryProperty<Point> result = new DefaultGeometryProperty<Point>(crsDef, resultPoint);
    return result;
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) DefaultGeometryProperty(eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty) CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition) CodeDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.CodeDefinition) Coordinate(com.vividsolutions.jts.geom.Coordinate) PropertyValue(eu.esdihumboldt.hale.common.align.transformation.function.PropertyValue) Point(com.vividsolutions.jts.geom.Point)

Aggregations

DefaultGeometryProperty (eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty)25 CRSDefinition (eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition)20 Geometry (com.vividsolutions.jts.geom.Geometry)13 GeometryNotSupportedException (eu.esdihumboldt.hale.io.gml.geometry.GeometryNotSupportedException)11 Coordinate (com.vividsolutions.jts.geom.Coordinate)9 Point (com.vividsolutions.jts.geom.Point)9 GeometryProperty (eu.esdihumboldt.hale.common.schema.geometry.GeometryProperty)9 ArrayList (java.util.ArrayList)9 LineString (com.vividsolutions.jts.geom.LineString)8 Instance (eu.esdihumboldt.hale.common.instance.model.Instance)7 GeometryFinder (eu.esdihumboldt.hale.common.instance.geometry.GeometryFinder)6 CodeDefinition (eu.esdihumboldt.hale.common.instance.geometry.impl.CodeDefinition)6 DepthFirstInstanceTraverser (eu.esdihumboldt.hale.common.instance.helper.DepthFirstInstanceTraverser)6 InstanceTraverser (eu.esdihumboldt.hale.common.instance.helper.InstanceTraverser)6 TransformationException (eu.esdihumboldt.hale.common.align.transformation.function.TransformationException)5 InterpolationAlgorithm (eu.esdihumboldt.util.geometry.interpolation.InterpolationAlgorithm)5 Arc (eu.esdihumboldt.util.geometry.interpolation.model.Arc)5 ParseException (java.text.ParseException)5 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)3 LinearRing (com.vividsolutions.jts.geom.LinearRing)3