@Override
    public Feature decorate(Feature feature, KmlEncodingContext context) {
      Placemark pm = (Placemark) feature;
      // while it's possible to have more than one style object, GE will only paint
      // the first one
      Style style = pm.createAndAddStyle();
      List<Symbolizer> symbolizers = context.getCurrentSymbolizers();
      SimpleFeature sf = context.getCurrentFeature();
      if (symbolizers.size() > 0 && sf.getDefaultGeometry() != null) {
        // sort by point, text, line and polygon
        Map<Class, List<Symbolizer>> classified = classifySymbolizers(symbolizers);

        // if no point symbolizers, create a default one
        List<Symbolizer> points = classified.get(PointSymbolizer.class);
        if (points.size() == 0) {
          if (context.isDescriptionEnabled()) {
            setDefaultIconStyle(style, sf, context);
          }
        } else {
          org.geotools.styling.Style wholeStyle = context.getCurrentLayer().getStyle();
          IconProperties properties = IconPropertyExtractor.extractProperties(wholeStyle, sf);
          setIconStyle(style, wholeStyle, properties, context);
        }

        // handle label styles
        List<Symbolizer> texts = classified.get(TextSymbolizer.class);
        if (texts.size() == 0) {
          if (context.isDescriptionEnabled()) {
            setDefaultLabelStyle(style);
          }
        } else {
          // the XML schema allows only one text style, follow painter's model
          // and set the last one
          TextSymbolizer lastTextSymbolizer = (TextSymbolizer) texts.get(texts.size() - 1);
          setLabelStyle(style, sf, lastTextSymbolizer);
        }

        // handle line styles
        List<Symbolizer> lines = classified.get(LineSymbolizer.class);
        // the XML schema allows only one line style, follow painter's model
        // and set the last one
        if (lines.size() > 0) {
          LineSymbolizer lastLineSymbolizer = (LineSymbolizer) lines.get(lines.size() - 1);
          setLineStyle(style, sf, lastLineSymbolizer.getStroke());
        }

        // handle polygon styles
        boolean forceOutiline = lines.size() == 0;
        List<Symbolizer> polygons = classified.get(PolygonSymbolizer.class);
        if (polygons.size() > 0) {
          // the XML schema allows only one polygon style, follow painter's model
          // and set the last one
          PolygonSymbolizer lastPolygonSymbolizer =
              (PolygonSymbolizer) polygons.get(polygons.size() - 1);
          setPolygonStyle(style, sf, lastPolygonSymbolizer, forceOutiline);
        }
      }

      return feature;
    }
    @Override
    public Feature decorate(Feature feature, KmlEncodingContext context) {
      Placemark pm = (Placemark) feature;

      // try with the template
      SimpleFeature sf = context.getCurrentFeature();
      String title = null;
      try {
        title = context.getTemplate().title(sf);
      } catch (IOException e) {
        String msg = "Error occured processing 'title' template.";
        LOGGER.log(Level.WARNING, msg, e);
      }

      // if we got nothing, set the title to the ID, but also try the text symbolizers
      if (title == null || "".equals(title)) {
        title = sf.getID();
        StringBuffer label = new StringBuffer();

        for (Symbolizer sym : context.getCurrentSymbolizers()) {
          if (sym instanceof TextSymbolizer) {
            Expression e = SLD.textLabel((TextSymbolizer) sym);
            String value = e.evaluate(feature, String.class);

            if ((value != null) && !"".equals(value.trim())) {
              label.append(value);
            }
          }
        }

        if (label.length() > 0) {
          title = label.toString();
        }
      }

      pm.setName(title);
      return pm;
    }
  public void writeFeatures(List<Feature> features) throws KettleException {

    Kml kml = new Kml();
    Document document = kml.createAndSetDocument();

    if (this.documentName != null) {
      document.setName(documentName);
    }

    if (this.documentDescription != null) {
      document.setDescription(documentDescription);
    }

    // Si export des attributs
    if (exportWithAttributs) {

      Schema schema = document.createAndAddSchema();
      schema.setId("dataSchema");
      schema.setName("");

      Iterator<Field> fieldIt = this.fields.iterator();
      while (fieldIt.hasNext()) {

        Field field = fieldIt.next();

        // Pas pris en compte ici : une seule géométrie
        if (!field.getType().equals(FieldType.GEOMETRY)) {

          SimpleField simpleField = schema.createAndAddSimpleField();
          simpleField.setName(field.getName());

          // Texte
          if (field.getType().equals(FieldType.STRING)) {

            simpleField.setType("string");

            // Date
          } else if (field.getType().equals(FieldType.DATE)) {

            simpleField.setType("date");

            // Entier
          } else if (field.getType().equals(FieldType.LONG)) {

            simpleField.setType("int");

            // Double
          } else if (field.getType().equals(FieldType.DOUBLE)) {

            simpleField.setType("float");

            // Booléen
          } else if (field.getType().equals(FieldType.BOOLEAN)) {

            simpleField.setType("bool");

            // Autres types
          } else {
            simpleField.setType("string");
          }
        }
      }
    }

    // Récupération des champs utilisés
    Field geometryField = null;
    Field nameField = null;
    Field descriptionField = null;

    Iterator<Feature> featureIt = features.iterator();
    boolean first = true;
    while (featureIt.hasNext()) {

      Feature feature = featureIt.next();
      if (first) {

        geometryField = feature.getField(this.geometryFieldName);

        if (featureNameField != null) {
          nameField = feature.getField(this.featureNameField);
        }

        if (featureDescriptionField != null) {
          descriptionField = feature.getField(this.featureDescriptionField);
        }

        first = false;
      }

      Geometry geometry = (Geometry) feature.getValue(geometryField);
      Envelope envelope = geometry.getEnvelopeInternal();

      // Vérification de l'emprise : doit être en WGS 84
      if (envelope.getMaxX() > 180
          || envelope.getMinX() < -180
          || envelope.getMaxY() > 90
          || envelope.getMinY() < -90) {

        throw new KettleException("Bad coordinates for WGS84 system");
      }

      Placemark placemark = document.createAndAddPlacemark();

      // Nom de feature
      if (featureNameField != null) {
        String name = (String) feature.getValue(nameField);
        if (name != null) {
          placemark.setName(name);
        }
      }

      // Description de feature
      if (featureDescriptionField != null) {
        String description = (String) feature.getValue(descriptionField);
        if (description != null) {
          placemark.setDescription(description);
        }
      }

      // Attributs
      if (exportWithAttributs) {
        ExtendedData extendedData = placemark.createAndSetExtendedData();
        SchemaData schemaData = extendedData.createAndAddSchemaData();
        schemaData.setSchemaUrl("dataSchema");

        Iterator<Field> colIt = this.fields.iterator();
        while (colIt.hasNext()) {

          Field field = colIt.next();
          if (!field.getType().equals(FieldType.GEOMETRY)) {

            Object value = feature.getValue(field);
            SimpleData simpleData = schemaData.createAndAddSimpleData(field.getName());
            simpleData.setValue(String.valueOf(value));
          }
        }
      }

      // En fonction dy type de géométrie Jts, appel
      // aux fonctions de conversion en géométries Kml

      // POINT
      if (geometry instanceof Point) {

        placemark.setGeometry(getAsKmlPoint((Point) geometry));

        // LINESTRING
      } else if (geometry instanceof LineString) {

        placemark.setGeometry(getAsKmlLineString((LineString) geometry));

        // POLYGON
      } else if (geometry instanceof Polygon) {

        placemark.setGeometry(getAsKmlPolygon((Polygon) geometry));

        // MULTIPOINT
      } else if (geometry instanceof MultiPoint) {

        de.micromata.opengis.kml.v_2_2_0.MultiGeometry kmlMultiGeometry =
            placemark.createAndSetMultiGeometry();
        for (int i = 0; i < geometry.getNumGeometries(); i++) {

          kmlMultiGeometry.addToGeometry(getAsKmlPoint((Point) ((Point) geometry).getGeometryN(i)));
        }
        // MULTILINESTRING
      } else if (geometry instanceof MultiLineString) {

        de.micromata.opengis.kml.v_2_2_0.MultiGeometry kmlMultiGeometry =
            placemark.createAndSetMultiGeometry();
        for (int i = 0; i < geometry.getNumGeometries(); i++) {

          kmlMultiGeometry.addToGeometry(
              getAsKmlLineString((LineString) ((MultiLineString) geometry).getGeometryN(i)));
        }
        // MULTIPOLYGON
      } else if (geometry instanceof MultiPolygon) {

        de.micromata.opengis.kml.v_2_2_0.MultiGeometry kmlMultiGeometry =
            placemark.createAndSetMultiGeometry();
        for (int i = 0; i < geometry.getNumGeometries(); i++) {

          kmlMultiGeometry.addToGeometry(
              getAsKmlPolygon((Polygon) ((MultiPolygon) geometry).getGeometryN(i)));
        }
        // GEOMETRYCOLLECTION
      } else if (geometry instanceof GeometryCollection) {

        de.micromata.opengis.kml.v_2_2_0.MultiGeometry kmlMultiGeometry =
            placemark.createAndSetMultiGeometry();
        for (int i = 0; i < geometry.getNumGeometries(); i++) {

          Geometry currentGeometry = geometry.getGeometryN(i);

          if (currentGeometry instanceof Point) {
            kmlMultiGeometry.addToGeometry(getAsKmlPoint((Point) currentGeometry));
          } else if (currentGeometry instanceof LineString) {
            kmlMultiGeometry.addToGeometry(getAsKmlLineString((LineString) currentGeometry));
          } else if (currentGeometry instanceof Polygon) {
            kmlMultiGeometry.addToGeometry(getAsKmlPolygon((Polygon) currentGeometry));
          } else if (currentGeometry instanceof MultiPoint) {

            for (int j = 0; j < currentGeometry.getNumGeometries(); j++) {
              kmlMultiGeometry.addToGeometry(
                  getAsKmlPoint((Point) ((Point) currentGeometry).getGeometryN(j)));
            }

          } else if (currentGeometry instanceof MultiLineString) {

            for (int j = 0; j < currentGeometry.getNumGeometries(); j++) {
              kmlMultiGeometry.addToGeometry(
                  getAsKmlLineString((LineString) ((LineString) currentGeometry).getGeometryN(j)));
            }

          } else if (currentGeometry instanceof MultiPolygon) {

            for (int j = 0; j < currentGeometry.getNumGeometries(); j++) {
              kmlMultiGeometry.addToGeometry(
                  getAsKmlPolygon((Polygon) ((Polygon) currentGeometry).getGeometryN(j)));
            }
          }
        }
      }
    }

    if (isServletOutput) {

      if (features.size() > 0) {
        kml.marshal();
        kml.marshal(writer);
      }

    } else {

      try {

        FileOutputStream fileOutputStream = new FileOutputStream(this.kmlFileName);
        kml.marshal();
        kml.marshal(fileOutputStream);
        fileOutputStream.close();

      } catch (FileNotFoundException e) {
        throw new KettleException("Error writing features to " + this.kmlFileName, e);
      } catch (IOException e) {
        throw new KettleException("Error writing features to " + this.kmlFileName, e);
      }
    }
  }
Example #4
0
  private void execute(String sourcePath, String targetPath, String species, String language)
      throws NullPointerException {

    if (language.equals("espanol") || language.equals("español")) {
      System.out.println("bienvenido \n seleccione la opcion que desee");
      System.out.println("1. crear el archivo properties");
      System.out.println("2. convierte archivo .shp a kml, protected areas");
      System.out.println(
          "3. convierte archivo .csv a kml; puntos y poligonos - ocurrencias y chull, chull-buff");
      System.out.println("4. convierte archivo .asc a png, variables bioclimaticas");
      System.out.println("5. convierte archivo .asc a png, distribucion de especies");
      System.out.println("6. realiza todos los procesos anteriores");
      System.out.println(
          "para mas info consulta en la wiki del proyecto http://code.google.com/p/iabin-threats/wiki/HowToBuildITAMaps");
    }
    if (language.equals("english")) {
      System.out.println("welcome \n select the option: ");
      System.out.println("1. create default properties file");
      System.out.println("2. convert file .shp to kml, protected areas");
      System.out.println(
          "3. convert file .csv to kml; points and polygons - ocurrences and chull, chull-buff");
      System.out.println("4. convert file .asc to png, variables bioclimaticas");
      System.out.println("5. convert file .asc to png, species distribution");
      System.out.println("6. performs all the previous tasks");
      System.out.println(
          "for more info visit the project's wiki page at http://code.google.com/p/iabin-threats/wiki/HowToBuildITAMaps");
    }
    String option;
    String horaEmpieza = this.getDateTime();
    if (language.equals("english")) System.out.println("started at : " + horaEmpieza);
    if (language.equals("espanol") || language.equals("español"))
      System.out.println("empieza a las : " + horaEmpieza);
    if (language.equals("english")) System.out.print("please select an option :");
    if (language.equals("espanol") || language.equals("español"))
      System.out.print("por favor seleccione una opcion :");

    Scanner in = new Scanner(System.in);
    option = in.nextLine();

    int opt = Integer.parseInt(option);
    if (opt == 1 || opt == 6) {

      if (language.equals("english")) System.out.println("you selected option :" + option);
      if (language.equals("espanol") || language.equals("español"))
        System.out.println("usted escogio la opcion :" + option);

      // esta sección crea el archivo properties con la configuración por defecto.
      PropertiesGenerator propGen =
          new PropertiesGenerator(targetPath + "default-iabin.properties");
      try {
        propGen.write();
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    } // cierra el case1

    // protected areas shape to kml

    if (opt == 2 || opt == 6) {

      if (language.equals("english")) System.out.println("you selected option :" + option);
      if (language.equals("espanol") || language.equals("español"))
        System.out.println("usted escogio la opcion :" + option);

      String[] shapesID = PropertiesManager.getInstance().getPropertiesAsStringArray("shapes");

      for (String shapeID : shapesID) {
        System.out.println(shapeID);
        String group = PropertiesManager.getInstance().getPropertiesAsString(shapeID + ".group");
        String pathGroup = PropertiesManager.getInstance().getPropertiesAsString(group + ".path");
        String fileName =
            PropertiesManager.getInstance().getPropertiesAsString(shapeID + ".shapefile");
        int[] columnIndexes =
            PropertiesManager.getInstance()
                .getPropertiesAsIntArray(shapeID + ".shape.column.indexes");
        String[] columnName =
            PropertiesManager.getInstance()
                .getPropertiesAsStringArray(shapeID + ".shape.column.names");

        String sourceFile = sourcePath + pathGroup + fileName;
        String targetFile = targetPath + pathGroup + shapeID;
        SortedMap<Integer, String> atributos = new TreeMap<Integer, String>();
        for (int i = 0; i < columnIndexes.length; i++) {
          atributos.put(columnIndexes[i], columnName[i]);
        }
        File file = new File(sourceFile); // loads the shape file to read
        System.out.println("folder of shape file: " + sourceFile);
        System.out.println("file: " + file);
        shp = new Shapefile(file);
        SimpleFeature sf = null;
        FeatureIterator<SimpleFeature> fi = shp.getFeatures();
        final Kml kml2 = new Kml();
        Folder folder = kml2.createAndSetFolder();
        String ruta = targetFile + File.separator + "total-info.kml";
        System.out.println("ruta: " + ruta);

        DecimalFormat formatter = new DecimalFormat("####.####");
        while (fi.hasNext()) { // && count-- > 0) {				
          sf = fi.next();
          Set<Integer> keySet = atributos.keySet();
          String descripcion =
              "<div><h2 align=\"center\"><span>Information Protected Area</span></h2></div><h5><table bgcolor=\"#BCD56C\" border=\"1\" align=\"center\">";

          for (Integer i :
              keySet) { // se crean los titulos de la tabla de la informacion del poligono
            descripcion += "<tr align=\"left\"><th>" + atributos.get(i) + "</th>";
            String contenido = (String) sf.getAttribute(i).toString();
            if (isValidDouble(contenido)) {
              contenido = formatter.format(Double.parseDouble(contenido));
            }

            descripcion += "<td>" + contenido + "</td>";
          }
          // descripcion += "</tr><tr>";
          descripcion += "</tr></table></h5>";

          Placemark placemark = KmlFactory.createPlacemark();
          String estilo = PropertiesManager.getInstance().getPropertiesAsString("style.url");
          // se recorre la lista generando las coordenadas y agregando al folder
          placemark = folder.createAndAddPlacemark(); // se crea el placemark y se añade al folder
          placemark.withName(atributos.get(1)).withDescription(descripcion).withStyleUrl(estilo);
          Point punto = Shapefile.getPointForMarker(sf);
          // se crean las coordenadas y se registran al placemark
          placemark.createAndSetPoint().addToCoordinates(punto.getX(), punto.getY());
        } // fin while
        kml2.setFeature(folder); // se registra el folder al kml

        File dir = new File(targetFile);
        dir.mkdirs();
        // kml.marshal();//se imprime kml en consola
        try {
          kml2.marshal(new File(ruta));
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } // se guarda kml en archivo
      }
    } // fin case 2
    // **********************************************************************************************************
    // Esta seccion se encarga de recorrer la carpeta data y cargar los
    // archivos csv para convertir a kml
    // puntos y poligonos - ocurrencias y chull, chull-buff

    if (opt == 3 || opt == 6) {

      if (language.equals("english")) System.out.println("you selected option :" + option);
      if (language.equals("espanol") || language.equals("español"))
        System.out.println("usted escogio la opcion :" + option);

      // se debe agregar properties
      String estilo = PropertiesManager.getInstance().getPropertiesAsString("style.url");
      String estilo1 = PropertiesManager.getInstance().getPropertiesAsString("style1.url");

      File folder = new File(sourcePath + species);
      // *************************************************************************************

      File[] listOfFiles = folder.listFiles();

      int contador = 100;
      for (File s : listOfFiles) {

        if (s.isDirectory()) {

          String ruta =
              folder.getPath() + File.separator + s.getName() + File.separator + s.getName();
          if (contador % 100 == 0) {
            System.out.println("File " + ruta);
            System.gc();
          }
          contador++;

          CsvFile file1 = new CsvFile(ruta + ".csv");
          lista = file1.getLista();

          CsvFile chull = new CsvFile(ruta + "-chull.csv");
          listaChull = chull.getLista();
          CsvFile chullbuff = new CsvFile(ruta + "-chull-buff.csv");
          listaChullBuff = chullbuff.getLista();

          Csv2Point point = new Csv2Point(lista);
          try {
            point.createKML(
                targetPath + species + s.getName() + File.separator,
                s.getName(),
                estilo); // cambiar a properties file
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }

          Csv2Polygon pol = new Csv2Polygon(listaChull, listaChullBuff, estilo, estilo1);
          try {
            pol.createKMLchull(
                targetPath + species + s.getName() + File.separator,
                s.getName(),
                estilo); // crea kml chull
            pol.createKMLchullbuff(
                targetPath + species + s.getName() + File.separator,
                s.getName(),
                estilo1); // crea kml chull buff

          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }
        }
      }
    } // fin case3

    // bioclim variables
    if (opt == 4 || opt == 6) {

      if (language.equals("english")) System.out.println("you selected option :" + option);
      if (language.equals("espanol") || language.equals("español"))
        System.out.println("usted escogio la opcion :" + option);

      try {
        TileCutter.execute(propertiesFile);
      } catch (IOException e) {
        System.out.println("file not found");
        e.getMessage();
        e.printStackTrace();
      }
    } // fin case 4

    // se crean las imagenes de distribucion de especies a partir de los rasters .asc
    if (opt == 5 || opt == 6) {

      if (language.equals("english")) System.out.println("you selected option :" + option);
      if (language.equals("espanol") || language.equals("español"))
        System.out.println("usted escogio la opcion :" + option);

      if (opt == 5) {

        if (language.equals("english"))
          System.out.println("Do you want to run the script for all species? y/n :");
        if (language.equals("espanol") || language.equals("español"))
          System.out.println("Desea correr el algoritmo para todas las especies? s/n" + option);
        option = in.nextLine();

        if (option.equalsIgnoreCase("n")) {
          if (language.equals("english"))
            System.out.println(
                "Please write the minimum and maximum species directory separated by (-), format: 78465-98750543:");
          if (language.equals("espanol") || language.equals("español"))
            System.out.println(
                "Por favor, indique el codigo de especie minimo y maximo, formato: 78465-98750543");
          option = in.nextLine();
          String[] minMax = option.split("-");
          if (minMax.length == 2) {
            String min = minMax[0];
            String max = minMax[1];
            try {
              TileCutter.createSpeciesDistributionImages(propertiesFile, min, max);
            } catch (IOException e) {
              System.out.println("file not found");
              e.getMessage();
              e.printStackTrace();
            }
          } else {
            if (language.equals("english")) System.out.println("Invalid format!");
            if (language.equals("espanol") || language.equals("español"))
              System.out.println("Formato incorrecto!");
          }
        } else {
          try {
            TileCutter.createSpeciesDistributionImages(propertiesFile, null, null);
          } catch (IOException e) {
            System.out.println("file not found");
            e.getMessage();
            e.printStackTrace();
          }
        }
      } else {
        try {
          TileCutter.createSpeciesDistributionImages(propertiesFile, null, null);
        } catch (NumberFormatException e) {
          System.out.println("format error");
          e.getMessage();
          e.printStackTrace();
        } catch (IOException e) {
          System.out.println("file not found");
          e.getMessage();
          e.printStackTrace();
        }
      }
    } // fin case 5

    String horaTermina = this.getDateTime();
    if (language.equals("espanol") || language.equals("español"))
      System.out.println(
          "empezo a las : " + horaEmpieza + "\r\n" + " finalizo a las : " + horaTermina);
    if (language.equals("english"))
      System.out.println("started at : " + horaEmpieza + "\r\n" + " ended at : " + horaTermina);
  } // fin switch