예제 #1
0
 /** HelloKML Sample project */
 public static void main(String[] args) throws FileNotFoundException {
   final Kml kml = new Kml();
   kml.createAndSetPlacemark()
       .withName("London, UK")
       .withOpen(Boolean.TRUE)
       .createAndSetPoint()
       .addToCoordinates(-0.126236, 51.500152);
   // marshals to console
   kml.marshal();
   // marshals into file
   kml.marshal(new File("HelloKml.kml"));
 }
예제 #2
0
  /**
   * Creates a list of {@link NetworkLink}s, one for each {@link ddf.catalog.source.Source}
   * including the local catalog.
   *
   * @param uriInfo - injected resource provding the URI.
   * @return - {@link Kml} containing a folder of {@link NetworkLink}s.
   */
  @GET
  @Path(FORWARD_SLASH + "sources")
  @Produces(KML_MIME_TYPE)
  public Kml getAvailableSources(@Context UriInfo uriInfo) {
    try {
      SourceInfoResponse response = framework.getSourceInfo(new SourceInfoRequestEnterprise(false));

      Kml kml = KmlFactory.createKml();
      Folder folder = kml.createAndSetFolder();
      folder.setOpen(true);
      for (SourceDescriptor descriptor : response.getSourceInfo()) {
        UriBuilder builder = UriBuilder.fromUri(uriInfo.getBaseUri());
        builder =
            generateEndpointUrl(
                servicesContextRoot
                    + FORWARD_SLASH
                    + CATALOG_URL_PATH
                    + FORWARD_SLASH
                    + OPENSEARCH_URL_PATH,
                builder);
        builder = builder.queryParam(SOURCE_PARAM, descriptor.getSourceId());
        builder = builder.queryParam(OPENSEARCH_SORT_KEY, OPENSEARCH_DEFAULT_SORT);
        builder = builder.queryParam(OPENSEARCH_FORMAT_KEY, KML_TRANSFORM_PARAM);
        NetworkLink networkLink =
            generateViewBasedNetworkLink(builder.build().toURL(), descriptor.getSourceId());
        folder.getFeature().add(networkLink);
      }

      return kml;
    } catch (SourceUnavailableException e) {
      throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    } catch (UnknownHostException e) {
      throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    } catch (MalformedURLException e) {
      throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    } catch (IllegalArgumentException e) {
      throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    } catch (UriBuilderException e) {
      throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    }
  }
예제 #3
0
  private Kml createRootNetworkLink(UriInfo uriInfo) throws UnknownHostException {
    Kml kml = KmlFactory.createKml();
    NetworkLink rootNetworkLink = kml.createAndSetNetworkLink();

    rootNetworkLink.setName(this.productName);
    rootNetworkLink.setSnippet(KmlFactory.createSnippet().withMaxLines(0));
    UriBuilder baseUrlBuidler = UriBuilder.fromUri(uriInfo.getBaseUri());
    baseUrlBuidler.replacePath("");
    this.baseUrl = baseUrlBuidler.build().toString();
    String descriptionHtml = description;
    Handlebars handlebars = new Handlebars(templateLoader);
    try {
      Template template = handlebars.compile("description");
      descriptionHtml = template.apply(this);
      LOGGER.debug(descriptionHtml);
    } catch (IOException e) {
      LOGGER.error("Failed to apply description Template", e);
    }
    rootNetworkLink.setDescription(descriptionHtml);
    rootNetworkLink.setOpen(true);
    rootNetworkLink.setVisibility(false);
    Link link = rootNetworkLink.createAndSetLink();
    UriBuilder builder = UriBuilder.fromUri(uriInfo.getBaseUri());
    builder =
        generateEndpointUrl(
            servicesContextRoot
                + FORWARD_SLASH
                + CATALOG_URL_PATH
                + FORWARD_SLASH
                + KML_TRANSFORM_PARAM
                + FORWARD_SLASH
                + "sources",
            builder);
    link.setHref(builder.build().toString());
    link.setViewRefreshMode(ViewRefreshMode.NEVER);
    link.setRefreshMode(RefreshMode.ON_INTERVAL);
    link.setRefreshInterval(REFRESH_INTERVAL);

    return kml;
  }
예제 #4
0
 /**
  * Attempts to load a KML {@link de.micromata.opengis.kml.v_2_2_0.Style} from a file provided via
  * a file system path.
  *
  * @param url - the path to the file.
  */
 public void setStyleUrl(String url) {
   if (StringUtils.isNotBlank(url)) {
     try {
       styleDoc = null;
       styleUrl = url;
       styleDoc = Kml.unmarshal(new URL(styleUrl).openStream());
     } catch (MalformedURLException e) {
       LOGGER.warn(
           "StyleUrl is not a valid URL. Unable to serve up custom KML de.micromata.opengis.kml.v_2_2_0.Style.",
           e);
     } catch (IOException e) {
       LOGGER.warn(
           "Unable to open de.micromata.opengis.kml.v_2_2_0.Style Document from StyleUrl.", e);
     }
   }
 }
예제 #5
0
  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);
      }
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    String name = req.getParameter("name");
    Shape shape = null;
    String country = req.getParameter("country");
    if (country != null && country.length() == 3) {
      InputStream in = WicketApplication.getStreamFromDataResource("countries-poly.txt");
      try {
        SampleDataReader reader = new SampleDataReader(in);
        while (reader.hasNext()) {
          SampleData data = reader.next();
          if (country.equalsIgnoreCase(data.id)) {
            if (StringUtils.isEmpty(name)) name = data.name;
            shape = ctx.readShape(data.shape);
            break;
          }
        }
      } finally {
        IOUtils.closeQuietly(in);
      }

      if (shape == null) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to find: " + country);
        return;
      }
    }
    int depth = getIntParam(req, "depth", 16);

    String gridtype = req.getParameter("gridType");

    SpatialPrefixTree grid;
    if ("geohash".equals(gridtype)) {
      grid = new GeohashPrefixTree(ctx, depth);
    } else if ("quad".equals(gridtype)) {
      grid = new QuadPrefixTree(ctx, depth);
    } else {
      res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unknown grid type: " + gridtype);
      return;
    }

    // If they don't set a country, then use the input
    if (shape == null) {
      String geo = req.getParameter("geo");
      if (geo == null) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing parameter: 'geo'");
        return;
      }
      try {
        shape = ctx.readShape(geo);
      } catch (Exception ex) {
        ex.printStackTrace();
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "error parsing geo: " + ex);
      }
    }
    SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, shape);
    double distErrPct = getDoubleParam(req, "distErrPct", SpatialArgs.DEFAULT_DISTERRPCT);
    double distErr = args.resolveDistErr(grid.getSpatialContext(), distErrPct);
    int detailLevel = grid.getLevelForDistance(distErr);
    List<Cell> nodes = grid.getCells(shape, detailLevel, false, true);

    int biggestLevel = 100;
    for (Cell node : nodes) {
      biggestLevel = Math.min(biggestLevel, node.getLevel());
    }
    String msg =
        "Using detail level "
            + detailLevel
            + " (biggest is "
            + biggestLevel
            + ") yielding "
            + nodes.size()
            + " tokens.";
    log(msg);

    List<String> info = SpatialPrefixTree.cellsToTokenStrings(nodes);
    String format = req.getParameter("format");
    if ("kml".equals(format)) {
      if (name == null || name.length() < 2) {
        name = "KML - " + new Date(System.currentTimeMillis());
      }
      Kml kml = KMLHelper.toKML(name, grid, info);

      res.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\";");
      res.setContentType("application/vnd.google-earth.kml+xml");
      kml.marshal(res.getOutputStream());
      return;
    }

    res.setContentType("text/plain");
    PrintStream out = new PrintStream(res.getOutputStream());
    out.println(msg);
    out.println(info.toString());
  }
예제 #7
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
  @POST
  @Path("newticket")
  @Produces(MediaType.APPLICATION_JSON)
  @TransactionAttribute(TransactionAttributeType.NEVER)
  public Response newticket(
      @FormParam("noiselogger") String noiselogger, @Context HttpServletRequest req)
      throws AddressException, MessagingException {
    Date date = new Date();

    TicketDTO newTicket = new TicketDTO();

    JsonResponse json = new JsonResponse();
    json.setData(newTicket); // just return the date we received

    Principal principal = req.getUserPrincipal();
    // only login if not already logged in...
    if (principal == null) {
      json.setStatus("FAILED");
      json.setErrorMsg("Authentication failed");
      return Response.ok().entity(json).build();
    }

    // Retrive info for the noise logger selected
    String path = "/Users/pelldav/University/Tesi/SmartWaterProject/web/file/Noise_loggers.kml";
    Kml kml = Kml.unmarshal(new File(path));
    Document document = (Document) kml.getFeature(); // Get the document features
    Iterator<Feature> iterator =
        document.getFeature().iterator(); // Create an iterator for the placemark
    Feature feature = null;
    while (iterator.hasNext()) {
      feature = iterator.next();
      if (feature.getName().compareTo(noiselogger) == 0) {
        break;
      }
    }
    req.getServletContext().log("ECCOLOOOOOO: " + feature.getDescription());
    String[] description = feature.getDescription().split("<br>");
    String battery = description[1].split("<b>")[1].split("%")[0];
    String status = description[2].split("<b>")[1].split("</b>")[0];

    // set the Company name
    User user = userBean.find(principal.getName());
    newTicket.setCompany(user.getCompany());

    // set the id
    newTicket.setId("" + date.getTime());

    // set the noise logger id
    newTicket.setNoiselogger(noiselogger);

    // retrive state and info from kml
    if (status.compareTo("OK") != 0) { // Error on network sensor
      newTicket.setInfo("Richiesta verifica rete noise loggers");
    } else { // Low battery
      newTicket.setInfo("Richiesta sostituzione batteria - Livello: " + battery + "%");
    }

    // set stato - initial state is always "attivo"
    newTicket.setStato("attivo");

    req.getServletContext().log("ticket creato" + newTicket);

    json.setData(newTicket); // just return the date we received

    Ticket ticket = new Ticket(newTicket);

    // this could cause a runtime exception, i.e. in case the user already exists
    // such exceptions will be caught by our ExceptionMapper, i.e.
    // javax.transaction.RollbackException
    ticketBean.save(
        ticket); // this would use the clients transaction which is committed after save() has
                 // finished

    // Send email to user
    String host = "smtp.gmail.com";
    String from = "*****@*****.**";
    String pass = "******";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    String[] to = {user.getEmail()};

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    InternetAddress[] toAddress = new InternetAddress[to.length];

    for (int i = 0; i < to.length; i++) { // To get the array of addresses
      toAddress[i] = new InternetAddress(to[i]);
    }
    System.out.println(Message.RecipientType.TO);

    for (int i = 0; i < toAddress.length; i++) {
      message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }
    message.setSubject("Smart Leak Detection - Richiesta Manutenzione");
    message.setContent(
        "<h1>Smart Leak Detection</h1> <br> <div> Registrazione di manutenzione inviata <br>"
            + newTicket.toString()
            + "</div>",
        "text/html");
    Transport transport = session.getTransport("smtp");
    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    req.getServletContext().log("Email sent to: '" + user.getEmail());

    json.setStatus("SUCCESS");

    req.getServletContext()
        .log(
            "successfully added new ticket: '"
                + newTicket.getCompany()
                + "':'"
                + newTicket.getId()
                + "'");

    return Response.ok().entity(json).build();
  }