public void run(WebGenRequest wgreq) {
   FeatureCollection fc = wgreq.getFeatureCollection("geom");
   double tolerance = wgreq.getParameterDouble("tolerance");
   GenAreaAggregation gaa = new GenAreaAggregation();
   gaa.init(tolerance);
   Feature f;
   Polygon p;
   for (Iterator iter = fc.iterator(); iter.hasNext(); ) {
     try {
       f = (Feature) iter.next();
       p = (Polygon) f.getGeometry();
       gaa.addDataPolygon(p, f, 0.0);
     } catch (ClassCastException e) {
       this.addError("only polygons can be aggregated");
       return;
     }
   }
   if (gaa.execute()) {
     ConstrainedFeatureCollection fcr = new ConstrainedFeatureCollection(fc.getFeatureSchema());
     for (int i = 0; i < gaa.getDataCount(); i++) {
       f = (Feature) gaa.getDataLinkedObject(i);
       f.setGeometry(gaa.getDataPolygon(i));
       fcr.add(f);
     }
     wgreq.addResult("result", fcr);
   }
 }
  private SimpleMatchList generateMatches(SimpleMatchSettings settings) {
    JosmTaskMonitor monitor = new JosmTaskMonitor();
    monitor.beginTask("Generating matches");

    // create Features and collections from primitive selections
    Set<OsmPrimitive> allPrimitives = new HashSet<>();
    allPrimitives.addAll(settings.getReferenceSelection());
    allPrimitives.addAll(settings.getSubjectSelection());
    FeatureCollection allFeatures = createFeatureCollection(allPrimitives);
    FeatureCollection refColl = new FeatureDataset(allFeatures.getFeatureSchema());
    FeatureCollection subColl = new FeatureDataset(allFeatures.getFeatureSchema());
    for (Feature f : allFeatures.getFeatures()) {
      OsmFeature osmFeature = (OsmFeature) f;
      if (settings.getReferenceSelection().contains(osmFeature.getPrimitive()))
        refColl.add(osmFeature);
      if (settings.getSubjectSelection().contains(osmFeature.getPrimitive()))
        subColl.add(osmFeature);
    }

    // TODO: pass to MatchFinderPanel to use as hint/default for DistanceMatchers
    // get maximum possible distance so scores can be scaled (FIXME: not quite accurate)
    //        Envelope envelope = refColl.getEnvelope();
    //        envelope.expandToInclude(subColl.getEnvelope());
    //        double maxDistance = Point2D.distance(
    //            envelope.getMinX(),
    //            envelope.getMinY(),
    //            envelope.getMaxX(),
    //            envelope.getMaxY());

    // build matcher
    FCMatchFinder finder = settings.getMatchFinder();

    // FIXME: ignore/filter duplicate objects (i.e. same object in both sets)
    // FIXME: fix match functions to work on point/linestring features as well
    // find matches
    Map<Feature, Matches> map = finder.match(refColl, subColl, monitor);

    monitor.subTask("Finishing match list");

    // convert to simple one-to-one match
    SimpleMatchList list = new SimpleMatchList();
    for (Map.Entry<Feature, Matches> entry : map.entrySet()) {
      OsmFeature target = (OsmFeature) entry.getKey();
      OsmFeature subject = (OsmFeature) entry.getValue().getTopMatch();
      if (target != null && subject != null)
        list.add(
            new SimpleMatch(
                target.getPrimitive(), subject.getPrimitive(), entry.getValue().getTopScore()));
    }

    monitor.finishTask();
    monitor.close();
    return list;
  }
  public boolean execute(PlugInContext context) throws Exception {
    if (context.getLayerViewPanel() == null) return false;
    this.networkMgr = NetworkModuleUtilWorkbench.getNetworkManager(context);
    configProperties = new CalcRutaConfigFileReaderWriter();
    if (configProperties.getRedesNames() == null) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser(
              I18N.get("calcruta", "routeengine.calcularruta.errormessage.emptyconfiguration"));
      return false;
    }
    this.context = context;
    nodesInfo = new HashMap<Integer, VirtualNodeInfo>();
    configuatorNetworks = new HashMap<String, Network>();

    nodesFeatureCol = AddNewLayerPlugIn.createBlankFeatureCollection();
    nodesFeatureCol.getFeatureSchema().addAttribute("nodeId", AttributeType.INTEGER);

    if (context.getLayerManager().getLayer("Puntos para TSP") != null) {
      context.getLayerManager().remove(sourcePointLayer);
    }

    sourcePointLayer = context.addLayer("Puntos TSP", "Puntos para TSP", nodesFeatureCol);

    //		LabelStyle labelStyle = new LabelStyle();
    //		labelStyle.setAttribute("nodeId");
    //		labelStyle.setColor(Color.black);
    //		labelStyle.setScaling(false);
    //		labelStyle.setEnabled(true);
    //		sourcePointLayer.addStyle(labelStyle);

    if (networkMgr == null) {
      context.getLayerViewPanel().getContext().warnUser("Error en el NetworkManager.");
      return false;
    }

    if (networkMgr.getNetworks().isEmpty()) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser("No hay redes cargadas en el NetworkManager");
      return false;
    }

    if (configProperties.getRedesNames().length <= 0) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser("Error en la configuracion. Inicie el configurador de rutas");
    }

    String redes[] = configProperties.getRedesNames();
    for (int i = 0; i < redes.length; i++) {
      configuatorNetworks.put(
          redes[i], ((LocalGISNetworkManager) networkMgr).getAllNetworks().get(redes[i]));
    }
    for (int m = 0; m < configuatorNetworks.values().size(); m++) {
      if (configuatorNetworks.values().toArray()[m] == null) {
        context
            .getLayerViewPanel()
            .getContext()
            .warnUser("Error en la configuracion. Inicie el configurador de rutas");
        return false;
      }
    }

    ToolboxDialog toolbox = new ToolboxDialog(context.getWorkbenchContext());
    //		toolbox.add();
    //
    //		RouteEngineDrawPointTool.createCursor(IconLoader.icon("bandera.gif").getImage());
    context
        .getLayerViewPanel()
        .setCurrentCursorTool(RouteEngineTSPDrawPointTool.create(toolbox.getContext()));

    return false;
  }
  private static void addSourceToRoute(Point p, boolean b) {
    // TODO Auto-generated method stub
    String[] redes = configProperties.getRedesNames();
    GeometryFactory fact = new GeometryFactory();
    try {
      if (redes != null) {

        NetworkManager networkMgr = NetworkModuleUtilWorkbench.getNetworkManager(context);

        CoordinateSystem coordSys = context.getLayerManager().getCoordinateSystem();
        if (coordSys != null) {
          p.setSRID(coordSys.getEPSGCode());
        }
        CoordinateReferenceSystem crs = CRS.decode("EPSG:" + coordSys.getEPSGCode());
        org.opengis.geometry.primitive.Point primitivePoint =
            GeographicNodeUtil.createISOPoint(p, crs);

        ExternalInfoRouteLN externalInfoRouteLN = new ExternalInfoRouteLN();
        ArrayList<VirtualNodeInfo> virtualNodesInfo = new ArrayList<VirtualNodeInfo>();
        for (int i = 0; i < redes.length; i++) {

          configuatorNetworks.put(
              redes[i], ((LocalGISNetworkManager) networkMgr).getAllNetworks().get(redes[i]));
          VirtualNodeInfo nodeInfo = null;
          try {
            nodeInfo =
                externalInfoRouteLN.getVirtualNodeInfo(
                    new GeopistaRouteConnectionFactoryImpl(),
                    primitivePoint,
                    networkMgr,
                    redes[i],
                    100);
          } catch (Exception e) {
            e.printStackTrace();
          }
          if (nodeInfo != null) {
            virtualNodesInfo.add(nodeInfo);
          }
        }
        if (virtualNodesInfo.size() == 0) return;
        Iterator<VirtualNodeInfo> it = virtualNodesInfo.iterator();
        double lastDistante = -1;
        VirtualNodeInfo selectedNodeInfo = null;
        while (it.hasNext()) {
          VirtualNodeInfo vNodeinfo = it.next();
          if (lastDistante == -1 || lastDistante > vNodeinfo.getDistance()) {
            selectedNodeInfo = vNodeinfo;
            lastDistante = vNodeinfo.getDistance();
          }
        }

        //
        //	((LocalGISNetworkManager)networkMgr).addNewVirtualNode(networkMgr.getNetwork(selectedNodeInfo.getNetworkName()).getGraph()
        //						, selectedNodeInfo.getEdge()
        //						, selectedNodeInfo.getRatio()
        //						, this);
        nodesInfo.put(selectedNodeInfo.hashCode(), selectedNodeInfo);
        //
        Coordinate coord = selectedNodeInfo.getLinestringVtoB().getCoordinateN(0);
        Point geom_nodes = fact.createPoint(coord);
        Feature feature = new BasicFeature(nodesFeatureCol.getFeatureSchema());
        feature.setGeometry(geom_nodes);
        //				feature.setAttribute("nodeId", new Integer(node.getID()));
        feature.setAttribute("nodeId", selectedNodeInfo.hashCode());
        sourcePointLayer.getFeatureCollectionWrapper().add(feature);

      } else {

      }
    } catch (NoSuchAuthorityCodeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FactoryException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Write a dbf file with the information from the featureCollection.
   *
   * @param featureCollection column data from collection
   * @param fname name of the dbf file to write to
   */
  void writeDbf(FeatureCollection featureCollection, String fname) throws Exception {
    DbfFileWriter dbf;
    FeatureSchema fs;
    int t;
    int f;
    int u;
    int num;

    fs = featureCollection.getFeatureSchema();

    // -1 because one of the columns is geometry
    DbfFieldDef[] fields = new DbfFieldDef[fs.getAttributeCount() - 1];

    // dbf column type and size
    f = 0;

    for (t = 0; t < fs.getAttributeCount(); t++) {
      AttributeType columnType = fs.getAttributeType(t);
      String columnName = fs.getAttributeName(t);

      if (columnType == AttributeType.INTEGER) {
        fields[f] = new DbfFieldDef(columnName, 'N', 16, 0);
        f++;
      } else if (columnType == AttributeType.DOUBLE) {
        fields[f] = new DbfFieldDef(columnName, 'N', 33, 16);
        f++;
      } else if (columnType == AttributeType.STRING) {
        int maxlength = findMaxStringLength(featureCollection, t);

        if (maxlength > 255) {
          throw new Exception(
              "ShapefileWriter does not support strings longer than 255 characters");
        }

        fields[f] = new DbfFieldDef(columnName, 'C', maxlength, 0);
        f++;
      } else if (columnType == AttributeType.DATE) {
        fields[f] = new DbfFieldDef(columnName, 'D', 8, 0);
        f++;
      } else if (columnType == AttributeType.GEOMETRY) {
        // do nothing - the .shp file handles this
      } else {
        throw new Exception("Shapewriter: unsupported AttributeType found in featurecollection.");
      }
    }

    // write header
    dbf = new DbfFileWriter(fname);
    dbf.writeHeader(fields, featureCollection.size());

    // write rows
    num = featureCollection.size();

    List features = featureCollection.getFeatures();

    for (t = 0; t < num; t++) {
      // System.out.println("dbf: record "+t);
      Feature feature = (Feature) features.get(t);
      Vector DBFrow = new Vector();

      // make data for each column in this feature (row)
      for (u = 0; u < fs.getAttributeCount(); u++) {
        AttributeType columnType = fs.getAttributeType(u);

        if (columnType == AttributeType.INTEGER) {
          Object a = feature.getAttribute(u);

          if (a == null) {
            DBFrow.add(new Integer(0));
          } else {
            DBFrow.add((Integer) a);
          }
        } else if (columnType == AttributeType.DOUBLE) {
          Object a = feature.getAttribute(u);

          if (a == null) {
            DBFrow.add(new Double(0.0));
          } else {
            DBFrow.add((Double) a);
          }
        } else if (columnType == AttributeType.DATE) {
          Object a = feature.getAttribute(u);
          if (a == null) {
            DBFrow.add("");
          } else {
            DBFrow.add(DbfFile.DATE_PARSER.format((Date) a));
          }
        } else if (columnType == AttributeType.STRING) {
          Object a = feature.getAttribute(u);

          if (a == null) {
            DBFrow.add(new String(""));
          } else {
            // MD 16 jan 03 - added some defensive programming
            if (a instanceof String) {
              DBFrow.add(a);
            } else {
              DBFrow.add(a.toString());
            }
          }
        }
      }

      dbf.writeRecord(DBFrow);
    }

    dbf.close();
  }
 public void setTargetFeatureCollection(FeatureCollection targetCollection) {
   this.targetFeatureCollection = targetCollection;
   setTargetSchema(targetFeatureCollection.getFeatureSchema());
 }
 public void setSourceDataSet(FeatureCollection sourceDataSet) {
   this.sourceFeatureCollection = sourceDataSet;
   setSourceSchema(sourceDataSet.getFeatureSchema());
 }