HI,

I'm trying to add an attribute to all the features of a shape file. In order
to accomplish this I perform the following steps:

1) Read all the features contained in the shape file
2) Create a collection of features who are the copy of the original features
plus the extra attribute
3) Write the new collection in a new shape file.

The code I've written does not give any error, unfortunately the  shape file
it generates is extremely small, and by displaying it I get an empty map.
I don't know if it can depend on the file I use as input, if it could be the
case, here the link to the file:
http://www3.istat.it/ambiente/cartografia/generalizzati/2011/com2011_g.zip

and here my code, thanks in advance:

public class  GeoToolsVisualization {

    public static void main(String[] args) throws Exception {


        File file = JFileDataStoreChooser.showOpenFile("shp", null);
        if (file == null) {
            return;
        }

        FileDataStore store =
FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource =
store.getFeatureSource(store.getTypeNames()[0]);

        //Access a feature to get its type, and use this type to generate
the new type (the one with the extra attribute)
        SimpleFeatureIterator it = featureSource.getFeatures().features();
        SimpleFeature sf = it.next();
        SimpleFeatureType sft = sf.getType();

        //Create the new type using the former as a template
        SimpleFeatureTypeBuilder stb = new SimpleFeatureTypeBuilder();
        stb.setName("newFeatureType");
        stb.setCRS(DefaultGeographicCRS.WGS84); //is this correct?
        stb.addAll(sft.getAttributeDescriptors());
        //Add the new attribute
        stb.add("Cluster", Integer.class);
        SimpleFeatureType newFeatureType = stb.buildFeatureType();




        //Create the collection of new Features
        SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(newFeatureType);

        SimpleFeatureCollection collection =
FeatureCollections.newCollection();
        SimpleFeature newFeature;

        it = featureSource.getFeatures().features();
        while(it.hasNext() && collection.size() <= 10){ //Only then features
to make the execution faster
            sf = it.next();
            List<Object> lat = sf.getAttributes();
            lat.add(new Integer(0));
            sfb.addAll(lat);
            newFeature = sfb.buildFeature(sf.getID());
            collection.add(newFeature);
        }


        File newFile = getNewShapeFile(file);

        ShapefileDataStoreFactory dataStoreFactory = new
ShapefileDataStoreFactory();

        Map<String, Serializable> params = new HashMap<String,
Serializable>();
        params.put("url", newFile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);

        ShapefileDataStore newDataStore = (ShapefileDataStore)
dataStoreFactory.createNewDataStore(params);
        newDataStore.createSchema(newFeatureType);

        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); //Shall I
comment this?

        Transaction transaction = new DefaultTransaction("create");

        String typeName = newDataStore.getTypeNames()[0];
        SimpleFeatureSource newFeatureSource =
newDataStore.getFeatureSource(typeName);

        if (newFeatureSource 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();
            }
        } else {
            System.out.println(typeName + " does not support read/write
access");
            System.exit(1);
        }

        //Start the opertaion to display the generated file
        FileDataStore store2 = FileDataStoreFinder.getDataStore(newFile);
        SimpleFeatureSource featureSource2 =
store2.getFeatureSource();

        MapContent map = new MapContent();
        map.setTitle("Quickstart");

        Style style = SLD.createSimpleStyle(featureSource2.getSchema());
        Layer layer = new FeatureLayer(featureSource2, style);
        map.addLayer(layer);

        JMapFrame.showMap(map);
    }

    private static File getNewShapeFile(File oldFile) {
        String path = oldFile.getAbsolutePath();
        String newPath = path.substring(0, path.length() - 4) + ".shp";

        JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
        chooser.setDialogTitle("Save shapefile");
        chooser.setSelectedFile(new File(newPath));

        int returnVal = chooser.showSaveDialog(null);

        if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
            // the user canceled the dialog
            System.exit(0);
        }

        File newFile = chooser.getSelectedFile();
        if (newFile.equals(oldFile)) {
            System.out.println("Error: cannot replace " + oldFile);
            System.exit(0);
        }

        return newFile;
    }

}



Roberto
------------------------------------------------------------------------------
EMC VNX: the world's simplest storage, starting under $10K
The only unified storage solution that offers unified management 
Up to 160% more powerful than alternatives and 25% more efficient. 
Guaranteed. http://p.sf.net/sfu/emc-vnx-dev2dev
_______________________________________________
Geotools-gt2-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/geotools-gt2-users

Reply via email to