Problemas com geotools -iniciante

6 respostas
D

Olá pessoal

Estou desenvolvendo um programa em java com netbeans, estou utilizando a biblioteca geotools, mas quando insiro o código <String, Serializable> Map params = new HashMap <String, Serializable> (); me surge um erro nesse comando e não estou conseguindo corrigir, esto usando o maven, será que estou esqucedo algum import?

6 Respostas

wpivotto

doeslei:
Olá pessoal

Estou desenvolvendo um programa em java com netbeans, estou utilizando a biblioteca geotools, mas quando insiro o código <String, Serializable> Map params = new HashMap <String, Serializable> (); me surge um erro nesse comando e não estou conseguindo corrigir, esto usando o maven, será que estou esqucedo algum import?

Sem saber o erro específico fica difícil saber se o problema é alguma lib faltando…
Tenho um projeto que funciona e no meu maven:

<repositories>
   <repository>
      <id>osgeo</id>
      <name>Open Source Geospatial Foundation Repository</name>
      <url>http://download.osgeo.org/webdav/geotools/</url>
    </repository>
</repositories>

Para o geotools:

<dependency>
      <groupId>org.geotools</groupId>
      <artifactId>gt-main</artifactId>
      <version>2.7.0</version>
   </dependency>

   <dependency>
      <groupId>org.geotools</groupId>
      <artifactId>gt-shapefile</artifactId>
      <version>2.7.0</version>
   </dependency>
		
   <dependency>
      <groupId>org.geotools</groupId>
      <artifactId>gt-epsg-hsql</artifactId>
      <version>2.7.0</version>
   </dependency>
D
O código do java segue:
package org.geotools.geotools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
//import org.opengis.*;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;

/**
 * This example reads data for point locations and associated attributes from a comma separated text
 * (CSV) file and exports them as a new shapefile. It illustrates how to build a feature type.
 * <p>
 * Note: to keep things simple in the code below the input file should not have additional spaces or
 * tabs between fields.
 *
 * @source $URL:
 *         http://svn.osgeo.org/geotools/branches/2.6.x/demo/example/src/main/java/org/geotools
 *         /demo/Csv2Shape.java $
 */

/**
 *
 * @author USUARIO
 */
public class Csv2Shape {

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

        File file = JFileDataStoreChooser.showOpenFile("csv", null);
        if (file == null) {
            return;
        }
   /*
         * We use the DataUtilities class to create a FeatureType that will describe the data in our
         * shapefile.
         *
         * See also the createFeatureType method below for another, more flexible approach.
         */
        final SimpleFeatureType TYPE = (SimpleFeatureType) DataUtilities.createType(
                "Location",                   // <- the name for our feature type
                "location:Point:srid=4326," + // <- the geometry attribute: Point type
                "name:String"         // <- a String attribute
        );
   /*
         * We create a FeatureCollection into which we will put each Feature created from a record
         * in the input csv data file
         */
        SimpleFeatureCollection collection = FeatureCollections.newCollection();

        /*
         * GeometryFactory will be used to create the geometry attribute of each feature (a Point
         * object for the location)
         */
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);

        BufferedReader reader = new BufferedReader(new FileReader(file));
        try {
            /* First line of the data file is the header */
            String line = reader.readLine();
            System.out.println("Header: " + line);

            for (line = reader.readLine(); line != null; line = reader.readLine()) {
                if (line.trim().length() > 0) { // skip blank lines
                    String tokens[] = line.split("\\,");

                    double longitude = Double.parseDouble(tokens[0]);
                    double latitude = Double.parseDouble(tokens[1]);
                    String name = tokens[2].trim();

                    /* Longitude (= x coord) first ! */
                    Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));

                    featureBuilder.add(point);
                    featureBuilder.add(name);
                    SimpleFeature feature = featureBuilder.buildFeature(null);
                    collection.add(feature);
                }
            }

        } finally {
            reader.close();
        }
/*
         * Get an output file name and create the new shapefile
         */
        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(TYPE);

        /*
         * You can comment out this line if you are using the createFeatureType
         * method (at end of class file) rather than DataUtilities.createType
         */
        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
  /*
         * Write the features to the shapefile
         */
        Transaction transaction = new DefaultTransaction("create");

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

        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);
        }
    }
     //* Prompt the user for the name and path to use for the output shapefile
     //*
     //* @param csvFile
     /*            the input csv file used to create a default shapefile name
     *
     * @return name and path for the shapefile as a new File object
     */
    private static File getNewShapeFile(File csvFile) {
        String path = csvFile.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 cancelled the dialog
            System.exit(0);
        }

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

        return newFile;
    }


}
E o maven segue:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.geotools</groupId>
<artifactId>tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>tutorial</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<geotools.version>8.0-M2</geotools.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
   <groupId>org.geotools</groupId>
   <artifactId>gt-main</artifactId>
   <version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
   <groupId>org.geotools</groupId>
   <artifactId>gt-epsg-hsql</artifactId>
   <version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools.jdbc</groupId>
<artifactId>gt-jdbc-postgis</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools.jdbc</groupId>
<artifactId>gt-data</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name>
<url>http://download.java.net/maven/2</url>
</repository>
<repository>
<id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url>
</repository>
</repositories>
</project>
wpivotto

doeslei formate o código dentro das tags [code] aqui no fórum.
Poste suas dúvidas no fórum apropriado também. Aqui é só para frameworks e bibliotecas brasileiros.

qual é o erro mesmo? o código não compila? é lançada uma exceção?

D

Opa desculpe sou novo aqui.
O código não compila, na linha

Me acusa erro e não sei se está faltando alguma coisa no meu código (import) ou algum comando no maven.

Segue o erro: generics are not supported in source 1.3 (use -source 5 or higter to enable generics)

wpivotto

doeslei:
Opa desculpe sou novo aqui.
O código não compila, na linha

Me acusa erro e não sei se está faltando alguma coisa no meu código (import) ou algum comando no maven.

Segue o erro: generics are not supported in source 1.3 (use -source 5 or higter to enable generics)

você esta compilando pelo Maven?

O erro é claro, ele esta usando a versão 1.3 do java (default do maven), e essa versão não suporta generics (Map<String, Serializable>)

adicione no seu pom.xml

<plugin>
	<artifactId>maven-compiler-plugin</artifactId>
	<version>2.3.2</version>
	<configuration>
		<source>1.6</source>
		<target>1.6</target>
		<encoding>UTF-8</encoding>
	</configuration>
</plugin>

ou para a versão 1.5

D

Obrigado, era isso mesmo.

Eu estava preocupado com o código e esqueci de ver a versão do jdk que esta usando.

Criado 3 de novembro de 2011
Ultima resposta 4 de nov. de 2011
Respostas 6
Participantes 2