4

I am transforming a shapefile by adding a new column attributes. Since this task is performed using Java, the only option I know for now is using Geotools. I have 2 main concerns:

1. I am not able to figure out how do I actually add a new column variable. Is the feature.setAttribute("col","value") the answer?

I see from this post just the example:https://gis.stackexchange.com/questions/215660/modifying-feature-attributes-of-a-shapefile-in-geotools but I dont get the solution.

   //Upload the ShapeFile
    File file = JFileDataStoreChooser.showOpenFile("shp", null);
    Map<String, Object> params = new HashMap<>();
    params.put("url", file.toURI().toURL());

    DataStore store = DataStoreFinder.getDataStore(params);
    SimpleFeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
    String typeName = store.getTypeNames()[0];


     FeatureSource<SimpleFeatureType, SimpleFeature> source =
            store.getFeatureSource(typeName);
        Filter filter = Filter.INCLUDE;

    FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(filter);
    try (FeatureIterator<SimpleFeature> features = collection.features()) {
        while (features.hasNext()) {
            SimpleFeature feature = features.next();

            //adding new columns

            feature.setAttribute("ShapeID", "SHP1213");
            feature.setAttribute("UserName", "John");

            System.out.print(feature.getID());
            System.out.print(":");
            System.out.println(feature.getDefaultGeometryProperty().getValue());
        }
    }

/*
 * Write the features to the shapefile
 */
Transaction transaction = new DefaultTransaction("create");


// featureSource.addFeatureListener(fl);

if (featureSource instanceof SimpleFeatureStore) {
    SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

    featureStore.setTransaction(transaction);
    try {
        featureStore.addFeatures(collection);
        transaction.commit();

    } catch (Exception problem) {
        problem.printStackTrace();
        transaction.rollback();

    } finally {
        transaction.close();
    }
    System.exit(0); // success!
} else {
    System.out.println(typeName + " does not support read/write access");
    System.exit(1);
}

Assuming that setattribute is the one which adds, I get the following error for the above code.

Exception in thread "main" org.geotools.feature.IllegalAttributeException:Unknown attribute ShapeID:null value:null
    at org.geotools.feature.simple.SimpleFeatureImpl.setAttribute(SimpleFeatureImpl.java:238)
    at org.geotools.Testing.WritetoDatabase.main(WritetoDatabase.java:73)

2. After modifying these changes I want to store it in the database(PostGIS). I figured out the below snippet does the task, but doesn't seems to work for me with just shape file insertion

  Properties params = new Properties();
    params.put("user", "postgres");
    params.put("passwd", "postgres");
    params.put("port", "5432");
    params.put("host", "127.0.0.1");
    params.put("database", "test");
    params.put("dbtype", "postgis");

  dataStore = DataStoreFinder.getDataStore(params);

The error is a NullPointerException in the above case.

GeoFresher
  • 301
  • 2
  • 12

1 Answers1

5

In GeoTools a (Simple)FeatureType is immutable (unchangeable) so you can't just add a new attribute to a shapefile. So first you must make a new FeatureType with your new attribute included.

FileDataStore ds = FileDataStoreFinder.getDataStore(new File("/home/ian/Data/states/states.shp"));
SimpleFeatureType schema = ds.getSchema();
// create new schema
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName(schema.getName());
builder.setSuperType((SimpleFeatureType) schema.getSuper());
builder.addAll(schema.getAttributeDescriptors());
// add new attribute(s)
builder.add("shapeID", String.class);
// build new schema
SimpleFeatureType nSchema = builder.buildFeatureType();

Then you need to convert all your existing features to the new schema and add the new attribute.

// loop through features adding new attribute
List<SimpleFeature> features = new ArrayList<>();
try (SimpleFeatureIterator itr = ds.getFeatureSource().getFeatures().features()) {
  while (itr.hasNext()) {
    SimpleFeature f = itr.next();
    SimpleFeature f2 = DataUtilities.reType(nSchema, f);
    f2.setAttribute("shapeID", "newAttrValue");
    //System.out.println(f2);
    features.add(f2);
  }
}

Finally, open the Postgis datastore and write the new features to it.

Properties params = new Properties();
params.put("user", "postgres");
params.put("passwd", "postgres");
params.put("port", "5432");
params.put("host", "127.0.0.1");
params.put("database", "test");
params.put("dbtype", "postgis");

DataStore dataStore = DataStoreFinder.getDataStore(params);
SimpleFeatureSource source = dataStore.getFeatureSource("tablename");
if (source instanceof SimpleFeatureStore) {
  SimpleFeatureStore store = (SimpleFeatureStore) source;
  store.addFeatures(DataUtilities.collection(features));
} else {
  System.err.println("Unable to write to database");
}
Ian Turton
  • 10,018
  • 1
  • 28
  • 47
  • This answers every problem which I was facing...Thumbs up Ian :) – GeoFresher Sep 30 '18 at 12:17
  • the "tablename: creates a new table right? as per this documentation it seems that http://docs.geotools.org/latest/javadocs/org/geotools/data/DataStore.html, however I am getting java.lang.NullPointerException at that line. – GeoFresher Sep 30 '18 at 21:58
  • No, it won't create the table by default, if it doesn't exist you need to call store.dataStore.createSchema(nSchema); to create the table. – Ian Turton Oct 01 '18 at 07:47
  • I tried executing with an existing tablename and the it fails with a nullpointer exception. I also tried creating a new table based on your input using dataStore.createSchema(nSchema), I got the same nullpointer exception at the same point. Am i missing something in specific w.r.t dependency for PostGIS? It works fine till attribute addition, after that the code fails after reading the postgis parameter details. I am kind of lost with half knowledge in this implementation. – GeoFresher Oct 01 '18 at 15:42
  • 1
    did you add gt-postgis to the dependencies? might be best to ask a new q with the code and stack trace – Ian Turton Oct 01 '18 at 16:35
  • Sure...Thanks for your inputs Ian.. :) I will try posting a new question in stack trace...this seems to go out of the box for this question .. – GeoFresher Oct 01 '18 at 16:48