コード例 #1
0
  private void parseInput() {
    inputType = TYPE_UNKNOWN;
    int fcSrcSize = fcSrc.size();
    int fcDestSize = fcDest.size();

    // error - # geoms must match
    if (fcSrcSize != fcDestSize) {
      parseErrMsg = "Control point collections must be same size";
      return;
    }
    // for now only handling pair of geoms to define control points
    if (fcSrcSize != 1) {
      parseErrMsg = "Control points must be a single geometry";
      return;
    }

    geomSrc[0] = ((Feature) fcSrc.iterator().next()).getGeometry();
    geomDest[0] = ((Feature) fcDest.iterator().next()).getGeometry();

    if (geomSrc[0].getClass() != geomDest[0].getClass()) {
      parseErrMsg = "Control points must be LineStrings";
      return;
    }

    // for now only handling LineStrings
    if (!(geomSrc[0] instanceof LineString)) {
      parseErrMsg = "Control points must be LineStrings";
      return;
    }

    parseLines();
    return;
  }
コード例 #2
0
 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);
   }
 }
コード例 #3
0
  /**
   * Find the generic geometry type of the feature collection. Simple method - find the 1st non null
   * geometry and its type is the generic type. returns 0 - all empty/invalid <br>
   * 1 - point <br>
   * 2 - line <br>
   * 3 - polygon <br>
   *
   * @param fc feature collection containing tet geometries.
   */
  int findBestGeometryType(FeatureCollection fc) {
    Geometry geom;

    for (Iterator i = fc.iterator(); i.hasNext(); ) {
      geom = ((Feature) i.next()).getGeometry();

      if (geom instanceof Point) {
        return 1;
      }

      if (geom instanceof MultiPoint) {
        return 1;
      }

      if (geom instanceof Polygon) {
        return 3;
      }

      if (geom instanceof MultiPolygon) {
        return 3;
      }

      if (geom instanceof LineString) {
        return 2;
      }

      if (geom instanceof MultiLineString) {
        return 2;
      }
    }

    return 0;
  }
コード例 #4
0
 private int getFeatureCollectionSize(FeatureCollection fc, String attribute, boolean nullAsZero) {
   int size = 0;
   for (Iterator it = fc.iterator(); it.hasNext(); ) {
     Feature f = (Feature) it.next();
     if (nullAsZero || f.getAttribute(attribute) != null) size++;
   }
   return size;
 }
コード例 #5
0
  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;
  }
コード例 #6
0
  /**
   * look at all the data in the column of the featurecollection, and find the largest string!
   *
   * @param fc features to look at
   * @param attributeNumber which of the column to test.
   */
  int findMaxStringLength(FeatureCollection fc, int attributeNumber) {
    int l;
    int maxlen = 0;
    Feature f;

    for (Iterator i = fc.iterator(); i.hasNext(); ) {
      f = (Feature) i.next();
      l = f.getString(attributeNumber).length();

      if (l > maxlen) {
        maxlen = l;
      }
    }

    return maxlen;
  }
コード例 #7
0
  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;
  }
コード例 #8
0
  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();
    }
  }
コード例 #9
0
  /**
   * return a single geometry collection <br>
   * result.GeometryN(i) = the i-th feature in the FeatureCollection<br>
   * All the geometry types will be the same type (ie. all polygons) - or they will be set to<br>
   * NULL geometries<br>
   * <br>
   * GeometryN(i) = {Multipoint,Multilinestring, or Multipolygon)<br>
   *
   * @param fc feature collection to make homogeneous
   */
  public GeometryCollection makeSHAPEGeometryCollection(FeatureCollection fc) throws Exception {
    GeometryCollection result;
    Geometry[] allGeoms = new Geometry[fc.size()];

    int geomtype = findBestGeometryType(fc);

    if (geomtype == 0) {
      throw new Exception(
          "Could not determine shapefile type - data is either all GeometryCollections or empty");
    }

    List features = fc.getFeatures();

    for (int t = 0; t < features.size(); t++) {
      Geometry geom;
      geom = ((Feature) features.get(t)).getGeometry();

      switch (geomtype) {
        case 1: // point
          if ((geom instanceof Point)) {
            // good!
            Point[] p = new Point[1];
            p[0] = (Point) geom;

            allGeoms[t] = new MultiPoint(p, new PrecisionModel(), 0);
          } else if (geom instanceof MultiPoint) {
            allGeoms[t] = geom;
          } else {
            allGeoms[t] = new MultiPoint(null, new PrecisionModel(), 0);
          }

          break;

        case 2: // line
          if ((geom instanceof LineString)) {
            LineString[] l = new LineString[1];
            l[0] = (LineString) geom;

            allGeoms[t] = new MultiLineString(l, new PrecisionModel(), 0);
          } else if (geom instanceof MultiLineString) {
            allGeoms[t] = geom;
          } else {
            allGeoms[t] = new MultiLineString(null, new PrecisionModel(), 0);
          }

          break;

        case 3: // polygon
          if (geom instanceof Polygon) {
            // good!
            Polygon[] p = new Polygon[1];
            p[0] = (Polygon) geom;

            allGeoms[t] = makeGoodSHAPEMultiPolygon(new MultiPolygon(p, new PrecisionModel(), 0));
          } else if (geom instanceof MultiPolygon) {
            allGeoms[t] = makeGoodSHAPEMultiPolygon((MultiPolygon) geom);
          } else {
            allGeoms[t] = new MultiPolygon(null, new PrecisionModel(), 0);
          }

          break;
      }
    }

    result = new GeometryCollection(allGeoms, new PrecisionModel(), 0);

    return result;
  }
コード例 #10
0
  /**
   * 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();
  }
コード例 #11
0
  private FeatureDataset classifyAndCreatePlot(TaskMonitor monitor, final PlugInContext context)
      throws Exception {

    monitor.report(this.sCalculateBreaks);
    // =============== get DATA and prepare ==============/
    FeatureSchema fs = this.fc.getFeatureSchema();
    AttributeType type = null;
    if ((fs.getAttributeType(this.selAttribute) == AttributeType.DOUBLE)
        || (fs.getAttributeType(this.selAttribute) == AttributeType.INTEGER)) {
      // -- move on
      type = fs.getAttributeType(this.selAttribute);
    } else {
      // System.out.println("ClassifyAttributesPlugIn: wrong datatype of chosen attribute");
      context.getWorkbenchFrame().warnUser(sWrongDataType);
      return null;
    }

    int size = getFeatureCollectionSize(this.fc, this.selAttribute, this.nullAsZero);
    if (size < 3) {
      return null;
    }
    this.ranges = Math.min(this.ranges, size);

    double[] data = new double[size];
    double[][] plotdata = new double[2][size]; // for drawing 1-D scatter plot
    int[] fID = new int[size];
    int i = 0;
    for (Iterator iter = fc.iterator(); iter.hasNext(); ) {
      Feature f = (Feature) iter.next();
      if (f.getAttribute(this.selAttribute) == null && !nullAsZero) continue;
      fID[i] = f.getID();
      plotdata[1][i] = 1;
      Object val = f.getAttribute(this.selAttribute);
      if (type == AttributeType.DOUBLE) {
        if (val == null) data[i] = 0.0;
        else data[i] = ((Double) val).doubleValue();
      } else if (type == AttributeType.INTEGER) {
        if (val == null) data[i] = 0;
        else data[i] = ((Integer) val).intValue();
      }
      plotdata[0][i] = data[i];
      i++;
    }
    /*
    //-- some testdata
    double[][] plotdata2 = new double[2][8];
    double[] data2 = { -2, 4, 6, 5, 0, 10, 7, 1 };
    double[] axis2 =  {  1, 1, 1, 1, 1, 1, 1, 1 };
    plotdata2[0] = data2;
    plotdata2[1] = axis2;
    */

    if (monitor.isCancelRequested()) {
      return null;
    }

    // =============== find breaks according to chosen method ==============/
    double[] limits = null;

    if (this.useKmeans == false) {
      if (this.selClassifier == Classifier1D.EQUAL_NUMBER) {
        limits = Classifier1D.classifyEqualNumber(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.EQUAL_RANGE) {
        limits = Classifier1D.classifyEqualRange(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.MEAN_STDEV) {
        limits = Classifier1D.classifyMeanStandardDeviation(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.MAX_BREAKS) {
        limits = Classifier1D.classifyMaxBreaks(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.JENKS_BREAKS) {
        limits = Classifier1D.classifyNaturalBreaks(data, this.ranges);
      }
    } else {
      if (this.selClassifier == Classifier1D.EQUAL_NUMBER) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 3);
      } else if (this.selClassifier == Classifier1D.EQUAL_RANGE) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 2);
      } else if (this.selClassifier == Classifier1D.MEAN_STDEV) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 4);
      } else if (this.selClassifier == Classifier1D.MAX_BREAKS) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 1);
      } else if (this.selClassifier == Classifier1D.JENKS_BREAKS) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 5);
      }
    }

    if (monitor.isCancelRequested()) {
      return null;
    }

    monitor.report(this.sDisplayBreaks);
    // =============== plot data and class breaks ==============/
    // -- do display here - in case we later want to allow interactive editing of the limits

    // -- reformat limits
    double[][] limits2show = new double[2][limits.length];
    // -- due to bug in jmathplot add limits twice if only three classes = 2breaks are sought
    if (limits.length == 2) {
      limits2show = new double[2][limits.length * 2];
    }
    for (int j = 0; j < limits.length; j++) {
      limits2show[0][j] = limits[j]; // x-axis
      limits2show[1][j] =
          Math.floor(
              i / (4.0 * this.ranges)); // y-axis, estimate height of "bar" from number of items
      // limits2show[1][j]= 1;
      // -- due to bug in jmathplot add limits twice if only three classes are sought
      if (limits.length == 2) {
        limits2show[0][limits.length + j] = limits[j];
        limits2show[1][limits.length + j] = Math.floor(i / (4.0 * this.ranges));
      }
    }

    // =============== plot data and class breaks ==============/
    // -- create plots
    /*final Plot2DPanelOJ*/ plot = new Plot2DPanelOJ();
    plot.addHistogramPlotOJ(
        this.selAttribute, data, this.ranges * 3, context, selLayer, this.selAttribute);
    plot.addScatterPlotOJ(this.sDatapoints, plotdata, fID, context, this.selLayer);
    plot.addBarPlot(this.sClassbreaks, limits2show);
    plot.plotToolBar.setVisible(true);
    plot.setAxisLabel(0, this.selAttribute);
    plot.setAxisLabel(1, this.sCount);
    plot.addLegend("SOUTH");

    // [mmichaud 2012-04-09] Moved in run method after the addLayer method
    // to avoid the problem of the focus change

    // JInternalFrame frame = new JInternalFrame(this.sHistogram);
    // frame.setLayout(new BorderLayout());
    // frame.add(plot, BorderLayout.CENTER);
    // frame.setClosable(true);
    // frame.setResizable(true);
    // frame.setMaximizable(true);
    // frame.setSize(450, 450);
    // frame.setVisible(true);

    // context.getWorkbenchFrame().addInternalFrame(frame);

    // =============== classify data ==============/
    if (monitor.isCancelRequested()) {
      return null;
    }
    monitor.report(this.sClassifying);
    int[] classes = Classifier1D.classifyData(data, limits);
    // double[] classes = org.math.array.StatisticSample.one(data.length);
    // context.getWorkbenchFrame().warnUser("classification not yet implemented");

    // =============== add field ==============/
    if (monitor.isCancelRequested()) {
      return null;
    }
    monitor.report(sAddingField);

    FeatureDataset fd = null;
    ArrayList outData = new ArrayList();
    FeatureSchema targetFSnew = null;
    int count = 0;
    Iterator iterp = fc.iterator();
    String attname = this.selAttribute + "_" + this.selClassifier;
    while (iterp.hasNext()) {
      // count=count+1;
      //	    	if(monitor != null){
      //	    	    monitor.report("item: " + count + " of " + size);
      //	    	}
      Feature p = (Feature) iterp.next();
      Object val = p.getAttribute(this.selAttribute);
      if (val == null && !this.nullAsZero) continue;
      else count++;
      if (count == 1) {
        FeatureSchema targetFs = p.getSchema();
        targetFSnew = FeatureSchemaTools.copyFeatureSchema(targetFs);
        if (targetFSnew.hasAttribute(attname)) {
          // attribute will be overwriten
        } else {
          // add attribute
          targetFSnew.addAttribute(attname, AttributeType.INTEGER);
        }
      }
      // -- evaluate value for every polygon
      Feature fcopy = FeatureSchemaTools.copyFeature(p, targetFSnew);
      // fcopy.setAttribute(this.selClassifier, new Integer(classes[count-1]));
      fcopy.setAttribute(attname, new Integer(classes[count - 1]));
      outData.add(fcopy);
    }
    fd = new FeatureDataset(targetFSnew);
    fd.addAll(outData);
    return fd;
  }
コード例 #12
0
 public void setTargetFeatureCollection(FeatureCollection targetCollection) {
   this.targetFeatureCollection = targetCollection;
   setTargetSchema(targetFeatureCollection.getFeatureSchema());
 }
コード例 #13
0
 public void setSourceDataSet(FeatureCollection sourceDataSet) {
   this.sourceFeatureCollection = sourceDataSet;
   setSourceSchema(sourceDataSet.getFeatureSchema());
 }
コード例 #14
0
ファイル: ImportarUtils.java プロジェクト: e-admin/allocalgis
  public static Geometry obtenerGeometriaParcela(String dxf, WorkbenchContext context) {

    Geometry geometryParcela = null;

    GeopistaLoadDxfQueryChooser dxfLoad =
        new GeopistaLoadDxfQueryChooser(Dxf.class, "GEOPISTA dxf", extensions(Dxf.class), context);

    InputStream fileDXF = ImportarUtils_LCGIII.parseStringToIS(dxf);

    try {
      Assert.isTrue(!dxfLoad.getDataSourceQueries(fileDXF).isEmpty());
    } catch (AssertionFailedException e) {
      throw new AssertionFailedException(I18N.get("FileEmpty"));
    }

    fileDXF = ImportarUtils_LCGIII.parseStringToIS(dxf);

    boolean exceptionsEncountered = false;
    for (Iterator i = dxfLoad.getDataSourceQueries(fileDXF).iterator(); i.hasNext(); ) {
      DataSourceQuery dataSourceQuery = (DataSourceQuery) i.next();

      ArrayList exceptions = new ArrayList();
      Assert.isTrue(dataSourceQuery.getDataSource().isReadable());

      Connection connection = dataSourceQuery.getDataSource().getConnection();
      try {
        FeatureCollection dataset =
            dataSourceQuery
                .getDataSource()
                .installCoordinateSystem(
                    connection.executeQuery(dataSourceQuery.getQuery(), exceptions, null), null);
        if (dataset != null) {

          String layerName = dataSourceQuery.toString();
          Geometry geometriaInicial = null;
          GeopistaFeature featureInicial = null;

          if (layerName.startsWith("PG-LP")) {
            // Obtener el borde con las features de la capa
            ArrayList lstFeatures = new ArrayList();
            for (Iterator features = dataset.getFeatures().iterator(); features.hasNext(); ) {
              GeopistaFeature feature = (GeopistaFeature) features.next();
              lstFeatures.add(feature);
            }
            ArrayList coordenadas = new ArrayList();

            if (lstFeatures != null && lstFeatures.size() > 0) {

              featureInicial = (GeopistaFeature) lstFeatures.iterator().next();
              lstFeatures.remove(featureInicial);
              geometriaInicial = featureInicial.getGeometry();
              for (int indice = 0; indice < geometriaInicial.getCoordinates().length; indice++)
                coordenadas.add(geometriaInicial.getCoordinates()[indice]);

              if (geometriaInicial instanceof LineString) {

                Point puntoFinal = ((LineString) geometriaInicial).getEndPoint();
                GeopistaFeature feature = null;
                Geometry geometria = null;
                int indice;

                while (lstFeatures.size() > 0) {
                  boolean encontrado = false;
                  Iterator features = lstFeatures.iterator();
                  while (features.hasNext() && !encontrado) {

                    feature = (GeopistaFeature) features.next();
                    geometria = feature.getGeometry();
                    if (geometria instanceof LineString) {

                      if (puntoFinal.distance(((LineString) geometria).getStartPoint()) == 0) {

                        for (indice = 1; indice < geometria.getCoordinates().length; indice++)
                          coordenadas.add(geometria.getCoordinates()[indice]);
                        puntoFinal = ((LineString) geometria).getEndPoint();
                        encontrado = true;

                      } else if (puntoFinal.distance(((LineString) geometria).getEndPoint()) == 0) {
                        for (indice = geometria.getCoordinates().length - 2; indice >= 0; indice--)
                          coordenadas.add(geometria.getCoordinates()[indice]);

                        puntoFinal = ((LineString) geometria).getStartPoint();
                        encontrado = true;
                      }
                    }
                  }
                  if (encontrado) {
                    lstFeatures.remove(feature);
                  }
                }
                Coordinate[] coordenadasParcela = new Coordinate[coordenadas.size()];
                indice = 0;
                for (Iterator coordenada = coordenadas.iterator(); coordenada.hasNext(); ) {
                  coordenadasParcela[indice] = (Coordinate) coordenada.next();
                  indice++;
                }

                if (coordenadasParcela[0].equals3D(
                    coordenadasParcela[coordenadasParcela.length - 1])) {
                  LinearRing lineaParcela =
                      geometriaInicial.getFactory().createLinearRing(coordenadasParcela);
                  Polygon poligonoParcela = null;
                  poligonoParcela = geometriaInicial.getFactory().createPolygon(lineaParcela, null);
                  geometryParcela = poligonoParcela;
                }
              }
            }
          }
        }
      } finally {
        connection.close();
      }
      if (!exceptions.isEmpty()) {
        if (!exceptionsEncountered) {
          context.getIWorkbench().getFrame().getOutputFrame().createNewDocument();
          exceptionsEncountered = true;
        }
        reportExceptions(exceptions, dataSourceQuery, context);
      }
    }
    if (exceptionsEncountered) {
      context
          .getIWorkbench()
          .getGuiComponent()
          .warnUser("Problems were encountered. See Output Window for details.");
    }

    return geometryParcela;
  }