use of org.opengis.feature.PropertyNotFoundException in project geotoolkit by Geomatys.
the class GeoJSONWriter method writeFeature.
/**
* Write a Feature.
*
* @param feature
* @throws IOException
* @throws IllegalArgumentException
*/
void writeFeature(Feature feature, Set<Feature> alreadyWritten) throws IOException, IllegalArgumentException {
alreadyWritten.add(feature);
writer.writeStartObject();
writer.writeStringField(TYPE, FEATURE);
/* As defined in GeoJSON spec, identifier is an optional attribute. For
* more details, see https://tools.ietf.org/html/rfc7946#section-3.2
*/
try {
final Object idValue = feature.getPropertyValue(AttributeConvention.IDENTIFIER);
// TODO : search for a property named id or identifier ?
if (idValue != null) {
writeAttribute(ID, idValue, true);
}
} catch (PropertyNotFoundException e) {
GeoJSONParser.LOGGER.log(Level.FINE, "Cannot write ID cause no matching property has been found.", e);
}
// write CRS
final CoordinateReferenceSystem crs = FeatureExt.getCRS(feature.getType());
if (crs != null && !Utilities.equalsApproximately(crs, CommonCRS.defaultGeographic())) {
if (!writeCRS(crs)) {
throw new IOException("Cannot determine a valid URN for " + crs.getName());
}
}
// write geometry
final Optional<Geometry> geom = FeatureExt.getDefaultGeometryValueSafe(feature).filter(Geometry.class::isInstance).map(Geometry.class::cast);
if (geom.isPresent()) {
writer.writeFieldName(GEOMETRY);
writeFeatureGeometry(geom.get());
}
// write properties
writeProperties(feature, PROPERTIES, true, alreadyWritten);
writer.writeEndObject();
writeNewLine();
}
use of org.opengis.feature.PropertyNotFoundException in project geotoolkit by Geomatys.
the class CategoryStyleBuilder method analyze.
public void analyze(final MapLayer layer) {
Resource resource = layer.getData();
if (!(resource instanceof FeatureSet)) {
throw new IllegalArgumentException("Layer resource must be a FeatureSet");
}
this.layer = layer;
fts.rules().clear();
properties.clear();
if (layer != null) {
FeatureType schema;
try {
schema = ((FeatureSet) resource).getType();
} catch (DataStoreException ex) {
throw new FeatureStoreRuntimeException(ex.getMessage(), ex);
}
for (PropertyType desc : schema.getProperties(true)) {
if (desc instanceof AttributeType) {
Class<?> type = ((AttributeType) desc).getValueClass();
if (!Geometry.class.isAssignableFrom(type)) {
properties.add(ff.property(desc.getName().tip().toString()));
}
}
}
// find the geometry class for template
Class<?> geoClass = null;
try {
PropertyType geo = FeatureExt.getDefaultGeometry(schema);
geoClass = Features.toAttribute(geo).map(AttributeType::getValueClass).orElse(null);
} catch (PropertyNotFoundException ex) {
LOGGER.log(Level.FINE, "No sis:geometry property found", ex);
}
if (geoClass == null) {
return;
}
if (Polygon.class.isAssignableFrom(geoClass) || MultiPolygon.class.isAssignableFrom(geoClass)) {
Stroke stroke = sf.stroke(Color.BLACK, 1);
Fill fill = sf.fill(Color.BLUE);
template = sf.polygonSymbolizer(stroke, fill, null);
expectedType = PolygonSymbolizer.class;
} else if (LineString.class.isAssignableFrom(geoClass) || MultiLineString.class.isAssignableFrom(geoClass)) {
Stroke stroke = sf.stroke(Color.BLUE, 2);
template = sf.lineSymbolizer(stroke, null);
expectedType = LineSymbolizer.class;
} else {
Stroke stroke = sf.stroke(Color.BLACK, 1);
Fill fill = sf.fill(Color.BLUE);
List<GraphicalSymbol> symbols = new ArrayList<>();
symbols.add(sf.mark(StyleConstants.MARK_CIRCLE, fill, stroke));
Graphic gra = sf.graphic(symbols, ff.literal(1), ff.literal(12), ff.literal(0), sf.anchorPoint(), sf.displacement());
template = sf.pointSymbolizer(gra, null);
expectedType = PointSymbolizer.class;
}
// try to rebuild the previous analyze if it was one
List<? extends FeatureTypeStyle> ftss = layer.getStyle().featureTypeStyles();
if (ftss.size() == 1) {
FeatureTypeStyle fts = ftss.get(0);
// defensive copy avoid synchronization
List<? extends Rule> candidateRules = new ArrayList<>(fts.rules());
for (Rule r : candidateRules) {
// defensive copy avoid synchronization
List<? extends Symbolizer> candidateSymbols = new ArrayList<>(r.symbolizers());
if (candidateSymbols.size() != 1)
break;
Symbolizer symbol = candidateSymbols.get(0);
if (expectedType.isInstance(symbol)) {
if (r.isElseFilter()) {
// it looks like it's a valid classification "other" rule
this.fts.rules().add((MutableRule) r);
template = symbol;
other = true;
} else {
Filter f = r.getFilter();
if (f != null && f.getOperatorType() == ComparisonOperatorName.PROPERTY_IS_EQUAL_TO) {
BinaryComparisonOperator equal = (BinaryComparisonOperator) f;
Expression exp1 = equal.getOperand1();
Expression exp2 = equal.getOperand2();
if (exp1 instanceof ValueReference && exp2 instanceof Literal) {
if (properties.contains(exp1)) {
// it looks like it's a valid classification property rule
this.fts.rules().add((MutableRule) r);
template = symbol;
currentProperty = (ValueReference) exp1;
} else {
// property is not in the schema
break;
}
} else if (exp2 instanceof ValueReference && exp1 instanceof Literal) {
if (properties.contains(exp2)) {
// it looks like it's a valid classification property rule
this.fts.rules().add((MutableRule) r);
template = symbol;
currentProperty = (ValueReference) exp2;
} else {
// property is not in the schema
break;
}
} else {
// mismatch analyze structure
break;
}
}
}
} else {
break;
}
}
}
}
}
use of org.opengis.feature.PropertyNotFoundException in project geotoolkit by Geomatys.
the class JAXPStreamFeatureReader method readFeature.
private Feature readFeature(final FeatureType featureType, final GenericName tagName) throws XMLStreamException {
final Feature feature = featureType.newInstance();
/*
* We create a map and a collection because we can encounter two cases :
* - The case featureType defines a property with max occur > 1.
* - The case featureType defines a property with max occur = 1, and its
* value instance of collection or map.
* We store all encountered name with its linked property in the map, so
* at each value parsed, we can add it in the existing property if its
* value is a list or map. The collection is the final property store,
* we add the all the created properties in it (so we can put multiple
* properties with the same name).
*/
final List<Entry<Operation, Object>> ops = new ArrayList<>();
// read attributes
final int nbAtts = reader.getAttributeCount();
for (int i = 0; i < nbAtts; i++) {
final QName attName = reader.getAttributeName(i);
if ("href".equals(attName.getLocalPart())) {
// or if can't be resolved we will still have the id
try {
final String attVal = reader.getAttributeValue(i);
feature.setPropertyValue(AttributeConvention.IDENTIFIER, attVal);
} catch (IllegalArgumentException ex) {
// do nothing
}
} else {
try {
final AttributeType pd = (AttributeType) featureType.getProperty("@" + attName.getLocalPart());
final String attVal = reader.getAttributeValue(i);
final Object val = ObjectConverters.convert(attVal, pd.getValueClass());
feature.setPropertyValue(pd.getName().toString(), val);
} catch (PropertyNotFoundException ex) {
// do nothing
}
}
}
boolean doNext = true;
// read a real complex type
while (!doNext || reader.hasNext()) {
if (doNext) {
reader.next();
}
doNext = true;
int event = reader.getEventType();
if (event == START_ELEMENT) {
GenericName propName = nameCache.get(reader.getName());
// we skip the boundedby attribute if it's present
if ("boundedBy".equals(propName.tip().toString())) {
toTagEnd("boundedBy");
continue;
}
final String nameAttribute = reader.getAttributeValue(null, "name");
// search property
PropertyType propertyType = null;
FeatureType associationSubType = null;
// search direct name
try {
propertyType = featureType.getProperty(propName.toString());
} catch (PropertyNotFoundException e) {
/*can happen*/
}
// search using only local part
if (propertyType == null) {
try {
propertyType = featureType.getProperty(propName.tip().toString());
} catch (PropertyNotFoundException e) {
/*can happen*/
}
}
// search if we are dealing with a subtype of a feature association role value type
if (propertyType == null) {
try {
final FeatureType candidate = featureTypes.get(propName.toString());
if (candidate != null) {
// search for a FeatureAssociationRole
for (PropertyType pt : featureType.getProperties(true)) {
if (pt instanceof FeatureAssociationRole) {
final FeatureAssociationRole far = (FeatureAssociationRole) pt;
final FeatureType vt = far.getValueType();
if (vt.isAssignableFrom(candidate)) {
propertyType = far;
associationSubType = candidate;
// change property name where data will be stored
propName = far.getName();
break;
}
}
}
}
} catch (IllegalNameException ex) {
Logger.getLogger(JAXPStreamFeatureReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
// skip property if we couldn't find it and user requested it
if (propertyType == null && Boolean.TRUE.equals(this.properties.get(SKIP_UNEXPECTED_PROPERTY_TAGS))) {
toTagEnd(propName.tip().toString());
continue;
}
// search if we have an _any attribute available
if (propertyType == null) {
try {
final AttributeType pd = (AttributeType) featureType.getProperty("_any");
// convert the content as a dom node
final Document doc = readAsDom(propName.tip().toString());
feature.setPropertyValue(pd.getName().toString(), doc);
doNext = false;
continue;
} catch (PropertyNotFoundException e) {
throw new XMLStreamException("Could not find any property fitting named tag " + propName);
}
}
if (propertyType instanceof Operation) {
final Operation opType = (Operation) propertyType;
final PropertyType resultType = (PropertyType) opType.getResult();
final Object value = readPropertyValue(resultType, null, null);
ops.add(new AbstractMap.SimpleImmutableEntry<>((Operation) propertyType, value));
if (resultType.getName().equals(propertyType.getName())) {
// we are already on the next element here, jaxb ate one
doNext = false;
}
continue;
}
// read attributes
if (propertyType instanceof AttributeType) {
final AttributeType<?> attType = (AttributeType) propertyType;
final int nbPropAtts = reader.getAttributeCount();
if (nbPropAtts > 0) {
final Attribute att = (Attribute) feature.getProperty(propName.toString());
for (int i = 0; i < nbPropAtts; i++) {
final QName qname = reader.getAttributeName(i);
final GenericName attName = nameCache.get(new QName(qname.getNamespaceURI(), "@" + qname.getLocalPart()));
final AttributeType<?> charType = attType.characteristics().get(attName.toString());
if (charType != null) {
final String attVal = reader.getAttributeValue(i);
final Object val = ObjectConverters.convert(attVal, charType.getValueClass());
final Attribute chara = charType.newInstance();
chara.setValue(val);
att.characteristics().put(attName.toString(), chara);
}
}
}
}
// check if attribute has it's own mapping
final XSDMapping mapping = GMLConvention.getMapping(propertyType);
if (mapping != null) {
mapping.readValue(reader, propName, feature);
} else {
// parse the value
final Object value = readPropertyValue(propertyType, associationSubType, feature);
setValue(feature, propertyType, propName, nameAttribute, value);
}
} else if (event == END_ELEMENT) {
final QName q = reader.getName();
if (q.getLocalPart().equals("featureMember") || nameCache.get(q).equals(tagName)) {
break;
}
}
}
return feature;
}
use of org.opengis.feature.PropertyNotFoundException in project geotoolkit by Geomatys.
the class Utils method getId.
/**
* Return a string value of the FeatureId for a given feature.
* If the feature id can not be foud, the fallback value will be returned.
*
* I the id contains the character ':', it will be replaced by '_' for xml validation purpose.
*
* @param feature The feature on which we want to extract the feature id.
* @param fallback Fallback value if we can not succeed to extract a featureId.
* @return
*/
public static String getId(Feature feature, String fallback) {
final ResourceId attId;
try {
attId = FeatureExt.getId(feature);
} catch (PropertyNotFoundException ex) {
return fallback;
}
if (attId == null)
return fallback;
final String id = attId.getIdentifier();
if (id == null)
return fallback;
if (id instanceof String) {
if (((String) id).isEmpty()) {
return fallback;
} else {
return ((String) id).replace(':', '_');
}
} else {
return String.valueOf(id).replace(':', '_');
}
}
use of org.opengis.feature.PropertyNotFoundException in project geotoolkit by Geomatys.
the class ShapefileFeatureStore method createFeatureType.
// //////////////////////////////////////////////////////////////////////////
// schema manipulation /////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
/**
* Set the FeatureType of this DataStore. This method will delete any
* existing local resources or throw an IOException if the featurestore is
* remote.
*
* @param featureType The desired FeatureType.
* @throws DataStoreException If the featurestore is remote.
*
* @todo must synchronize this properly
*/
@Override
public void createFeatureType(final FeatureType featureType) throws DataStoreException {
final GenericName typeName = featureType.getName();
if (!isWritable(typeName.toString())) {
throw new DataStoreException("Read-only acces prevent type creation.");
}
if (typeName == null) {
throw new DataStoreException("Type name can not be null.");
}
if (!featureType.isSimple()) {
throw new DataStoreException("Feature type must not be null and must be a simple feature type.");
}
if (!featureType.getName().equals(typeName)) {
throw new DataStoreException("Shapefile featurestore can only hold typename same as feature type name.");
}
try {
// delete the files
shpFiles.delete();
} catch (IOException ex) {
throw new DataStoreException("Cannot reset datastore content", ex);
}
final AccessManager locker = shpFiles.createLocker();
// update schema and name
name = typeName;
schema = featureType;
AttributeType desc;
try {
desc = Features.toAttribute(FeatureExt.getDefaultGeometry(featureType)).orElse(null);
} catch (PropertyNotFoundException e) {
getLogger().log(Level.FINE, e, () -> String.format("No geometry can be found in given datatype%n%s", featureType));
desc = null;
}
CoordinateReferenceSystem crs = null;
final Class<?> geomType;
final ShapeType shapeType;
if (desc != null) {
crs = FeatureExt.getCRS(desc);
geomType = desc.getValueClass();
shapeType = ShapeType.findBestGeometryType(geomType);
} else {
geomType = null;
shapeType = ShapeType.NULL;
}
if (shapeType == ShapeType.UNDEFINED) {
throw new DataStoreException("Cannot create a shapefile whose geometry type is " + geomType);
}
try (Closeable disposeLocker = locker::disposeReaderAndWriters) {
final StorageFile shpStoragefile = locker.getStorageFile(SHP);
final StorageFile shxStoragefile = locker.getStorageFile(SHX);
final StorageFile dbfStoragefile = locker.getStorageFile(DBF);
final StorageFile prjStoragefile = locker.getStorageFile(PRJ);
final StorageFile cpgStoragefile = locker.getStorageFile(CPG);
try (FileChannel shpChannel = shpStoragefile.getWriteChannel();
FileChannel shxChannel = shxStoragefile.getWriteChannel()) {
try (ShapefileWriter writer = new ShapefileWriter(shpChannel, shxChannel)) {
// try to get the domain first
final Envelope domain = CRS.getDomainOfValidity(crs);
if (domain != null) {
writer.writeHeaders(new JTSEnvelope2D(domain), shapeType, 0, 100);
} else {
// try to reproject the single overall envelope keeping poles out of the way
final JTSEnvelope2D env = new JTSEnvelope2D(-179, 179, -89, 89, CommonCRS.WGS84.normalizedGeographic());
JTSEnvelope2D transformedBounds;
if (crs != null) {
try {
transformedBounds = env.transform(crs);
} catch (Exception t) {
getLogger().log(Level.WARNING, t.getLocalizedMessage(), t);
// It can happen for local projections :
transformedBounds = new JTSEnvelope2D(crs);
}
} else {
transformedBounds = env;
}
writer.writeHeaders(transformedBounds, shapeType, 0, 100);
}
}
}
final DbaseFileHeader dbfheader = DbaseFileHeader.createDbaseHeader(schema);
dbfheader.setNumRecords(0);
try (WritableByteChannel dbfChannel = dbfStoragefile.getWriteChannel()) {
dbfheader.writeHeader(dbfChannel);
}
if (crs != null) {
// .prj files should have no carriage returns in them, this messes up
// ESRI's ArcXXX software, so we'll be compatible
final WKTFormat format = new WKTFormat(Locale.ENGLISH, null);
format.setConvention(Convention.WKT1_COMMON_UNITS);
format.setNameAuthority(Citations.ESRI);
format.setIndentation(WKTFormat.SINGLE_LINE);
final String s = format.format(crs);
IOUtilities.writeString(s, prjStoragefile.getFile(), Charset.forName("ISO-8859-1"));
} else {
getLogger().warning("PRJ file not generated for null CoordinateReferenceSystem");
Path prjFile = prjStoragefile.getFile();
Files.deleteIfExists(prjFile);
}
// write dbf encoding .cpg
CpgFiles.write(dbfCharset, cpgStoragefile.getFile());
} catch (IOException ex) {
throw new DataStoreException(ex);
}
// Once all writings have succeeded, we can commit them
try {
locker.replaceStorageFiles();
} catch (IOException e) {
throw new DataStoreException("Failed commiting file changes", e);
}
// force reading it again since the file type may be a little different
name = null;
schema = null;
// we still preserve the original type name and attribute classes which may be more restricted
final FeatureTypeBuilder ftb = new FeatureTypeBuilder(getFeatureType());
ftb.setName(typeName);
final AttributeTypeBuilder gtb = (AttributeTypeBuilder) ftb.getProperty("the_geom");
if (Geometry.class.equals(gtb.getValueClass())) {
gtb.setValueClass(shapeType.bestJTSClass());
}
gtb.setName(desc.getName());
for (PropertyType pt : featureType.getProperties(true)) {
if (pt instanceof AttributeType) {
final AttributeType at = (AttributeType) pt;
if (!Geometry.class.isAssignableFrom(at.getValueClass())) {
try {
((AttributeTypeBuilder) ftb.getProperty(at.getName().toString())).setValueClass(at.getValueClass()).setName(at.getName());
} catch (PropertyNotFoundException ex) {
}
}
}
}
schema = ftb.build();
name = schema.getName();
}
Aggregations