Search in sources :

Example 16 with FactoryException

use of org.opengis.referencing.FactoryException in project hale by halestudio.

the class StreamGmlWriter method partitionByExtent.

private void partitionByExtent(ProgressIndicator progress, IOReporter reporter) throws IOException {
    int maxNodes = getParameter(PARAM_PARTITION_BY_EXTENT_MAX_NODES).as(Integer.class, 1000);
    String mode = getParameter(PARAM_PARTITION_BY_EXTENT_MODE).as(String.class, PARTITION_BY_EXTENT_MODE_DATASET);
    final SubtaskProgressIndicator qtProgress = new SubtaskProgressIndicator(progress) {

        @Override
        protected String getCombinedTaskName(String taskName, String subtaskName) {
            return taskName + " (" + subtaskName + ")";
        }
    };
    // Map for instances that either contain no or multiple geometries
    Map<String, InstanceReference> unhandledInstances = new HashMap<>();
    QuadtreeBuilder<Point, InstanceReference> builder = new QuadtreeBuilder<>();
    try (ResourceIterator<Instance> it = getInstances().iterator()) {
        qtProgress.begin("Collecting geometries", getInstances().size());
        final XMLInspector gadget = new XMLInspector();
        int i = 0;
        while (it.hasNext()) {
            Instance inst = it.next();
            InstanceReference instRef = getInstances().getReference(inst);
            InstanceTraverser traverser = new DepthFirstInstanceTraverser();
            GeometryFinder finder = new GeometryFinder(getTargetCRS());
            traverser.traverse(inst, finder);
            List<GeometryProperty<?>> geoms = finder.getGeometries();
            if (geoms.isEmpty() || geoms.size() > 1) {
                unhandledInstances.put(gadget.getIdentity(inst), instRef);
            } else {
                GeometryProperty<?> geomProperty = geoms.get(0);
                Geometry geom = geomProperty.getGeometry();
                Point centroid;
                switch(mode) {
                    case PARTITION_BY_EXTENT_MODE_WORLD:
                        CoordinateReferenceSystem sourceCrs = geomProperty.getCRSDefinition().getCRS();
                        CodeDefinition wgs84 = new CodeDefinition("EPSG:4326");
                        try {
                            MathTransform toWgs84 = CRS.findMathTransform(sourceCrs, wgs84.getCRS());
                            Geometry geomWgs84 = JTS.transform(geom, toWgs84);
                            centroid = geomWgs84.getCentroid();
                        } catch (FactoryException | MismatchedDimensionException | TransformException e) {
                            log.error("Unable to transform geometry to WGS 84", e);
                            throw new IllegalStateException(e.getMessage(), e);
                        }
                        break;
                    case PARTITION_BY_EXTENT_MODE_DATASET:
                    // fall through to default
                    default:
                        centroid = geom.getCentroid();
                }
                builder.add(centroid, new IdentifiableInstanceReference(instRef, gadget.getIdentity(inst)));
            }
            qtProgress.advance(1);
            if (++i % 100 == 0) {
                qtProgress.setCurrentTask(MessageFormat.format("{0} instances processed", i));
            }
        }
        qtProgress.setCurrentTask("Building quadtree");
        FixedBoundaryQuadtree<InstanceReference> qt;
        switch(mode) {
            case PARTITION_BY_EXTENT_MODE_DATASET:
                qt = builder.build(maxNodes);
                break;
            case PARTITION_BY_EXTENT_MODE_WORLD:
                Envelope world = new Envelope(-180, 180, -90, 90);
                qt = builder.build(maxNodes, world);
                break;
            default:
                log.error(MessageFormat.format("Unrecognized extent partitioning mode \"{0}\", using dataset boundaries", mode));
                qt = builder.build(maxNodes);
        }
        qtProgress.setCurrentTask("Performing spatial partitioning");
        final Map<String, String> idToKeyMapping = new HashMap<>();
        final Map<String, Collection<InstanceReference>> keyToRefsMapping = new HashMap<>();
        // Instances without geometry or with multiple geometries
        keyToRefsMapping.put(ExtentPartsHandler.KEY_NO_GEOMETRY, unhandledInstances.values());
        unhandledInstances.keySet().stream().forEach(id -> idToKeyMapping.put(id, ExtentPartsHandler.KEY_NO_GEOMETRY));
        buildMappings(qt, idToKeyMapping, keyToRefsMapping);
        // Partition source instances based on quadtree tiles
        Iterator<InstanceCollection> collIt = new Iterator<InstanceCollection>() {

            private final Queue<String> keySet = new LinkedList<>(keyToRefsMapping.keySet());

            @Override
            public boolean hasNext() {
                return !keySet.isEmpty();
            }

            @Override
            public InstanceCollection next() {
                String key = keySet.poll();
                Collection<InstanceReference> refs = keyToRefsMapping.get(key);
                InstanceCollection instColl = new DefaultInstanceCollection(refs.stream().map(ref -> getInstances().getInstance(IdentifiableInstanceReference.getRootReference(ref))).collect(Collectors.toList()));
                return new ExtentPartsHandler.TreeKeyDecorator(instColl, key);
            }
        };
        final Map<String, URI> keyToTargetMapping = new HashMap<>();
        keyToRefsMapping.keySet().stream().forEach(k -> keyToTargetMapping.put(k, new File(ExtentPartsHandler.getTargetFilename(k, getTarget().getLocation())).toURI()));
        final ExtentPartsHandler handler = new ExtentPartsHandler(keyToTargetMapping, idToKeyMapping);
        qtProgress.end();
        try {
            writeParts(collIt, handler, progress, reporter);
        } catch (XMLStreamException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
}
Also used : MathTransform(org.opengis.referencing.operation.MathTransform) HashMap(java.util.HashMap) Instance(eu.esdihumboldt.hale.common.instance.model.Instance) GeometryFinder(eu.esdihumboldt.hale.common.instance.geometry.GeometryFinder) FactoryException(org.opengis.referencing.FactoryException) IdentifiableInstanceReference(eu.esdihumboldt.hale.common.instance.model.IdentifiableInstanceReference) Envelope(org.locationtech.jts.geom.Envelope) DefaultInstanceCollection(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstanceCollection) MismatchedDimensionException(org.opengis.geometry.MismatchedDimensionException) URI(java.net.URI) CodeDefinition(eu.esdihumboldt.hale.common.instance.geometry.impl.CodeDefinition) ResourceIterator(eu.esdihumboldt.hale.common.instance.model.ResourceIterator) Iterator(java.util.Iterator) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Queue(java.util.Queue) DepthFirstInstanceTraverser(eu.esdihumboldt.hale.common.instance.helper.DepthFirstInstanceTraverser) InstanceTraverser(eu.esdihumboldt.hale.common.instance.helper.InstanceTraverser) GeometryProperty(eu.esdihumboldt.hale.common.schema.geometry.GeometryProperty) PerTypeInstanceCollection(eu.esdihumboldt.hale.common.instance.model.ext.impl.PerTypeInstanceCollection) DefaultInstanceCollection(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstanceCollection) InstanceCollection(eu.esdihumboldt.hale.common.instance.model.InstanceCollection) TransformException(org.opengis.referencing.operation.TransformException) SubtaskProgressIndicator(eu.esdihumboldt.hale.common.core.io.impl.SubtaskProgressIndicator) QuadtreeBuilder(eu.esdihumboldt.util.geometry.quadtree.QuadtreeBuilder) Point(org.locationtech.jts.geom.Point) IOException(java.io.IOException) Point(org.locationtech.jts.geom.Point) DepthFirstInstanceTraverser(eu.esdihumboldt.hale.common.instance.helper.DepthFirstInstanceTraverser) Geometry(org.locationtech.jts.geom.Geometry) XMLStreamException(javax.xml.stream.XMLStreamException) InstanceReference(eu.esdihumboldt.hale.common.instance.model.InstanceReference) IdentifiableInstanceReference(eu.esdihumboldt.hale.common.instance.model.IdentifiableInstanceReference) XMLInspector(eu.esdihumboldt.hale.common.instance.graph.reference.impl.XMLInspector) PerTypeInstanceCollection(eu.esdihumboldt.hale.common.instance.model.ext.impl.PerTypeInstanceCollection) DefaultInstanceCollection(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstanceCollection) Collection(java.util.Collection) InstanceCollection(eu.esdihumboldt.hale.common.instance.model.InstanceCollection) File(java.io.File)

Example 17 with FactoryException

use of org.opengis.referencing.FactoryException in project series-rest-api by 52North.

the class IoParameters method transformToInnerCrs.

/**
     * @param point
     *        a GeoJSON point to be transformed to internally used CRS:84.
     * @param crsUtils
     *        a reference helper.
     * @return a transformed GeoJSON instance.
     * @throws IoParseException
     *         if point could not be transformed, or if requested CRS object could not be created.
     */
private GeojsonPoint transformToInnerCrs(GeojsonPoint point, CRSUtils crsUtils) {
    try {
        Point toTransformed = crsUtils.convertToPointFrom(point, getCrs());
        Point crs84Point = (Point) crsUtils.transformOuterToInner(toTransformed, getCrs());
        return crsUtils.convertToGeojsonFrom(crs84Point);
    } catch (TransformException e) {
        throw new IoParseException("Could not transform to internally used CRS:84.", e);
    } catch (FactoryException e) {
        throw new IoParseException("Check if 'crs' parameter is a valid EPSG CRS. Was: '" + getCrs() + "'.", e);
    }
}
Also used : IoParseException(org.n52.io.IoParseException) FactoryException(org.opengis.referencing.FactoryException) TransformException(org.opengis.referencing.operation.TransformException) Point(com.vividsolutions.jts.geom.Point) GeojsonPoint(org.n52.io.geojson.old.GeojsonPoint)

Example 18 with FactoryException

use of org.opengis.referencing.FactoryException in project GeoGig by boundlessgeo.

the class FormatCommonV1 method readAttributeType.

private static AttributeType readAttributeType(DataInput in, FeatureTypeFactory typeFactory) throws IOException {
    final Name name = readName(in);
    final byte typeTag = in.readByte();
    final FieldType type = FieldType.valueOf(typeTag);
    if (Geometry.class.isAssignableFrom(type.getBinding())) {
        // as opposed to a raw
        final boolean isCRSCode = in.readBoolean();
        // WKT string
        final String crsText = in.readUTF();
        final CoordinateReferenceSystem crs;
        try {
            if (isCRSCode) {
                if ("urn:ogc:def:crs:EPSG::0".equals(crsText)) {
                    crs = null;
                } else {
                    boolean forceLongitudeFirst = crsText.startsWith("EPSG:");
                    crs = CRS.decode(crsText, forceLongitudeFirst);
                }
            } else {
                crs = CRS.parseWKT(crsText);
            }
        } catch (FactoryException e) {
            throw new RuntimeException(e);
        }
        return typeFactory.createGeometryType(name, type.getBinding(), crs, false, false, Collections.<Filter>emptyList(), null, null);
    } else {
        return typeFactory.createAttributeType(name, type.getBinding(), false, false, Collections.<Filter>emptyList(), null, null);
    }
}
Also used : FactoryException(org.opengis.referencing.FactoryException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Name(org.opengis.feature.type.Name) FieldType(org.locationtech.geogig.storage.FieldType)

Example 19 with FactoryException

use of org.opengis.referencing.FactoryException in project GeoGig by boundlessgeo.

the class FormatCommonV2 method readAttributeType.

private static AttributeType readAttributeType(DataInput in, FeatureTypeFactory typeFactory) throws IOException {
    final Name name = readName(in);
    final byte typeTag = in.readByte();
    final FieldType type = FieldType.valueOf(typeTag);
    if (Geometry.class.isAssignableFrom(type.getBinding())) {
        // as opposed to a raw WKT string
        final boolean isCRSCode = in.readBoolean();
        final String crsText = in.readUTF();
        final CoordinateReferenceSystem crs;
        try {
            if (isCRSCode) {
                if ("urn:ogc:def:crs:EPSG::0".equals(crsText)) {
                    crs = null;
                } else {
                    boolean forceLongitudeFirst = crsText.startsWith("EPSG:");
                    crs = CRS.decode(crsText, forceLongitudeFirst);
                }
            } else {
                crs = CRS.parseWKT(crsText);
            }
        } catch (FactoryException e) {
            throw new RuntimeException(e);
        }
        return typeFactory.createGeometryType(name, type.getBinding(), crs, false, false, Collections.<Filter>emptyList(), null, null);
    } else {
        return typeFactory.createAttributeType(name, type.getBinding(), false, false, Collections.<Filter>emptyList(), null, null);
    }
}
Also used : FactoryException(org.opengis.referencing.FactoryException) Integer.toBinaryString(java.lang.Integer.toBinaryString) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Name(org.opengis.feature.type.Name) FieldType(org.locationtech.geogig.storage.FieldType)

Example 20 with FactoryException

use of org.opengis.referencing.FactoryException in project GeoGig by boundlessgeo.

the class ResponseWriter method writeGeometryChanges.

/**
     * Writes the response for a set of diffs while also supplying the geometry.
     * 
     * @param geogig - a CommandLocator to call commands from
     * @param diff - a DiffEntry iterator to build the response from
     * @throws XMLStreamException
     */
public void writeGeometryChanges(final Context geogig, Iterator<DiffEntry> diff, int page, int elementsPerPage) throws XMLStreamException {
    Iterators.advance(diff, page * elementsPerPage);
    int counter = 0;
    Iterator<GeometryChange> changeIterator = Iterators.transform(diff, new Function<DiffEntry, GeometryChange>() {

        @Override
        public GeometryChange apply(DiffEntry input) {
            Optional<RevObject> feature = Optional.absent();
            Optional<RevObject> type = Optional.absent();
            String path = null;
            String crsCode = null;
            GeometryChange change = null;
            if (input.changeType() == ChangeType.ADDED || input.changeType() == ChangeType.MODIFIED) {
                feature = geogig.command(RevObjectParse.class).setObjectId(input.newObjectId()).call();
                type = geogig.command(RevObjectParse.class).setObjectId(input.getNewObject().getMetadataId()).call();
                path = input.getNewObject().path();
            } else if (input.changeType() == ChangeType.REMOVED) {
                feature = geogig.command(RevObjectParse.class).setObjectId(input.oldObjectId()).call();
                type = geogig.command(RevObjectParse.class).setObjectId(input.getOldObject().getMetadataId()).call();
                path = input.getOldObject().path();
            }
            if (feature.isPresent() && feature.get() instanceof RevFeature && type.isPresent() && type.get() instanceof RevFeatureType) {
                RevFeatureType featureType = (RevFeatureType) type.get();
                Collection<PropertyDescriptor> attribs = featureType.type().getDescriptors();
                for (PropertyDescriptor attrib : attribs) {
                    PropertyType attrType = attrib.getType();
                    if (attrType instanceof GeometryType) {
                        GeometryType gt = (GeometryType) attrType;
                        CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
                        if (crs != null) {
                            try {
                                crsCode = CRS.lookupIdentifier(Citations.EPSG, crs, false);
                            } catch (FactoryException e) {
                                crsCode = null;
                            }
                            if (crsCode != null) {
                                crsCode = "EPSG:" + crsCode;
                            }
                        }
                        break;
                    }
                }
                RevFeature revFeature = (RevFeature) feature.get();
                FeatureBuilder builder = new FeatureBuilder(featureType);
                GeogigSimpleFeature simpleFeature = (GeogigSimpleFeature) builder.build(revFeature.getId().toString(), revFeature);
                change = new GeometryChange(simpleFeature, input.changeType(), path, crsCode);
            }
            return change;
        }
    });
    while (changeIterator.hasNext() && (elementsPerPage == 0 || counter < elementsPerPage)) {
        GeometryChange next = changeIterator.next();
        if (next != null) {
            GeogigSimpleFeature feature = next.getFeature();
            ChangeType change = next.getChangeType();
            out.writeStartElement("Feature");
            writeElement("change", change.toString());
            writeElement("id", next.getPath());
            List<Object> attributes = feature.getAttributes();
            for (Object attribute : attributes) {
                if (attribute instanceof Geometry) {
                    writeElement("geometry", ((Geometry) attribute).toText());
                    break;
                }
            }
            if (next.getCRS() != null) {
                writeElement("crs", next.getCRS());
            }
            out.writeEndElement();
            counter++;
        }
    }
    if (changeIterator.hasNext()) {
        writeElement("nextPage", "true");
    }
}
Also used : FeatureBuilder(org.locationtech.geogig.api.FeatureBuilder) RevFeatureBuilder(org.locationtech.geogig.api.RevFeatureBuilder) Optional(com.google.common.base.Optional) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) FactoryException(org.opengis.referencing.FactoryException) PropertyType(org.opengis.feature.type.PropertyType) Geometry(com.vividsolutions.jts.geom.Geometry) GeometryType(org.opengis.feature.type.GeometryType) ChangeType(org.locationtech.geogig.api.plumbing.diff.DiffEntry.ChangeType) RevFeature(org.locationtech.geogig.api.RevFeature) Collection(java.util.Collection) RevObjectParse(org.locationtech.geogig.api.plumbing.RevObjectParse) RevObject(org.locationtech.geogig.api.RevObject) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) GeogigSimpleFeature(org.locationtech.geogig.api.GeogigSimpleFeature) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) DiffEntry(org.locationtech.geogig.api.plumbing.diff.DiffEntry)

Aggregations

FactoryException (org.opengis.referencing.FactoryException)32 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)22 TransformException (org.opengis.referencing.operation.TransformException)11 NoSuchAuthorityCodeException (org.opengis.referencing.NoSuchAuthorityCodeException)8 MathTransform (org.opengis.referencing.operation.MathTransform)8 Collection (java.util.Collection)6 GeometryType (org.opengis.feature.type.GeometryType)5 Geometry (com.vividsolutions.jts.geom.Geometry)4 Hints (org.geotools.factory.Hints)4 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)4 PropertyDescriptor (org.opengis.feature.type.PropertyDescriptor)4 PropertyType (org.opengis.feature.type.PropertyType)4 ValueComboBoxData (com.sldeditor.ui.widgets.ValueComboBoxData)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 ReferencedEnvelope (org.geotools.geometry.jts.ReferencedEnvelope)3 Geometry (org.locationtech.jts.geom.Geometry)3 InternationalString (org.opengis.util.InternationalString)3 Optional (com.google.common.base.Optional)2 VendorOptionVersion (com.sldeditor.common.vendoroption.VendorOptionVersion)2