Search in sources :

Example 11 with CRSDefinition

use of eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition in project hale by halestudio.

the class OSerializationHelper method deserialize.

/**
 * Deserialize a serialized value wrapped in the given document.
 *
 * @param doc the document
 * @param parent the parent group
 * @param childName the name of the child the value is associated to
 * @return the deserialized value
 */
public static Object deserialize(ODocument doc, OGroup parent, QName childName) {
    int serType = doc.field(FIELD_SERIALIZATION_TYPE);
    switch(serType) {
        case SERIALIZATION_TYPE_STRING:
            {
                // convert a string value back to its original form
                Object val = doc.field(FIELD_STRING_VALUE);
                String stringVal = (val == null) ? (null) : (val.toString());
                ConvertProxy cp = CONVERTER_IDS.getObject((String) doc.field(FIELD_CONVERT_ID));
                if (cp != null) {
                    return cp.convert(stringVal);
                }
                return stringVal;
            }
        case SERIALIZATION_TYPE_COLLECTION:
            {
                // recreate collection
                Object val = doc.field(FIELD_VALUES);
                Object typeVal = doc.field(FIELD_COLLECTION_TYPE);
                CollectionType type = (typeVal != null) ? (CollectionType.valueOf(typeVal.toString())) : (CollectionType.LIST);
                if (val instanceof Collection<?>) {
                    Collection<?> values = (Collection<?>) val;
                    Collection<Object> target = createCollection(type);
                    for (Object element : values) {
                        Object convElement = convertFromDB(element, parent, childName);
                        target.add(convElement);
                    }
                    return target;
                }
            }
            break;
    }
    ORecordBytes record = (ORecordBytes) doc.field(BINARY_WRAPPER_FIELD);
    Object result;
    switch(serType) {
        case SERIALIZATION_TYPE_BYTEARRAY:
            result = record.toStream();
            break;
        case SERIALIZATION_TYPE_GEOM:
        case SERIALIZATION_TYPE_GEOM_PROP:
            ExtendedWKBReader reader = new ExtendedWKBReader();
            try {
                result = reader.read(record.toStream());
            } catch (ParseException e1) {
                throw new IllegalStateException("Unable to parse WKB to restore geometry", e1);
            }
            break;
        case SERIALIZATION_TYPE_JAVA:
        default:
            ByteArrayInputStream bytes = new ByteArrayInputStream(record.toStream());
            try {
                ObjectInputStream in = new ObjectInputStream(bytes) {

                    @Override
                    protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                        Class<?> result = resolved.get(desc.getName());
                        if (result == null) {
                            result = OsgiUtils.loadClass(desc.getName(), null);
                            if (resolved.size() > 200) {
                                resolved.entrySet().iterator().remove();
                            }
                            resolved.put(desc.getName(), result);
                        }
                        if (result == null) {
                            throw new IllegalStateException("Class " + desc.getName() + " not found");
                        }
                        return result;
                    }
                };
                result = in.readObject();
            } catch (Exception e) {
                throw new IllegalStateException("Could not deserialize field value.", e);
            }
            break;
    }
    if (serType == SERIALIZATION_TYPE_GEOM_PROP) {
        // wrap geometry in geometry property
        // determine CRS
        CRSDefinition crs = null;
        Object crsId = doc.field(FIELD_CRS_ID);
        if (crsId != null) {
            crs = CRS_IDS.getObject(crsId.toString());
        }
        // create geometry property
        GeometryProperty<Geometry> prop = new DefaultGeometryProperty<Geometry>(crs, (Geometry) result);
        return prop;
    }
    return result;
}
Also used : CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition) ORecordBytes(com.orientechnologies.orient.core.record.impl.ORecordBytes) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) Geometry(com.vividsolutions.jts.geom.Geometry) DefaultGeometryProperty(eu.esdihumboldt.hale.common.instance.geometry.DefaultGeometryProperty) ByteArrayInputStream(java.io.ByteArrayInputStream) Collection(java.util.Collection) ParseException(com.vividsolutions.jts.io.ParseException) ObjectStreamClass(java.io.ObjectStreamClass) ObjectInputStream(java.io.ObjectInputStream)

Example 12 with CRSDefinition

use of eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition in project hale by halestudio.

the class AbstractCRSManager method getCRS.

@Override
public CRSDefinition getCRS(TypeDefinition parentType, List<QName> propertyPath, CRSDefinition defaultCrs) {
    CRSDefinition result = null;
    String resourceId = reader.getResourceIdentifier();
    if (resourceId == null) {
        // TODO warn about no resource Id?
        // setting for any resource
        resourceId = "";
    } else {
        resourceId = "resource-" + resourceId + ":";
    }
    // first, try configuration
    // configuration for property
    StringBuffer keybuilder = new StringBuffer();
    keybuilder.append(resourceId);
    keybuilder.append(PREFIX_PARAM_CRS);
    keybuilder.append(parentType.getName());
    for (QName property : propertyPath) {
        keybuilder.append('/');
        keybuilder.append(property);
    }
    final String propertyKey = keybuilder.toString();
    result = CRSDefinitionManager.getInstance().parse(loadValue(propertyKey));
    // overall configuration for resource
    if (result == null && !resourceId.isEmpty()) {
        result = CRSDefinitionManager.getInstance().parse(loadValue(resourceId + PARAM_DEFAULT_CRS));
    }
    // overall configuration
    if (result == null) {
        result = CRSDefinitionManager.getInstance().parse(loadValue(PARAM_DEFAULT_CRS));
    }
    if (result == null && provider != null) {
        // consult default CRS provider
        result = provider.getCRS(parentType, propertyPath, defaultCrs);
        if (result != null) {
            // store in configuration
            storeValue(propertyKey, CRSDefinitionManager.getInstance().asString(result));
        }
    }
    return result;
}
Also used : CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition) QName(javax.xml.namespace.QName)

Example 13 with CRSDefinition

use of eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition in project hale by halestudio.

the class EPSGResolveCache method resolveCRS.

@Override
public CRSDefinition resolveCRS(final CoordinateReferenceSystem crs) {
    CRSDefinition result = cached.get(crs);
    if (result == null) {
        result = CRSDefinitionUtil.lookupCrs(crs);
        cached.put(crs, result);
    }
    return result;
}
Also used : CRSDefinition(eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition)

Example 14 with CRSDefinition

use of eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition 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 15 with CRSDefinition

use of eu.esdihumboldt.hale.common.schema.geometry.CRSDefinition 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)

Aggregations

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