public MapContext buildContext() {
    RandomStyleFactory RANDOM_STYLE_FACTORY = new RandomStyleFactory();

    MapContext context = null;
    MapLayer layer;

    try {
      context = new DefaultMapContext(DefaultGeographicCRS.WGS84);
      DataStore store =
          DataStoreFinder.getDataStore(
              new SingletonMap(
                  "url",
                  Demo_ContextTree.class.getResource(
                      "/org/geotools/gui/swing/demo/shape/test_polygon.shp")));
      FeatureSource<SimpleFeatureType, SimpleFeature> fs =
          store.getFeatureSource(store.getTypeNames()[0]);
      Style style = RANDOM_STYLE_FACTORY.createRandomVectorStyle(fs);
      layer = new DefaultMapLayer(fs, style);
      layer.setTitle("demo_polygon.shp");
      context.addLayer(layer);

      store =
          DataStoreFinder.getDataStore(
              new SingletonMap(
                  "url",
                  Demo_ContextTree.class.getResource(
                      "/org/geotools/gui/swing/demo/shape/test_ligne.shp")));
      fs = store.getFeatureSource(store.getTypeNames()[0]);
      style = RANDOM_STYLE_FACTORY.createRandomVectorStyle(fs);
      layer = new DefaultMapLayer(fs, style);
      layer.setTitle("demo_line.shp");
      context.addLayer(layer);

      store =
          DataStoreFinder.getDataStore(
              new SingletonMap(
                  "url",
                  Demo_ContextTree.class.getResource(
                      "/org/geotools/gui/swing/demo/shape/test_point.shp")));
      fs = store.getFeatureSource(store.getTypeNames()[0]);
      style = RANDOM_STYLE_FACTORY.createRandomVectorStyle(fs);
      layer = new DefaultMapLayer(fs, style);
      layer.setTitle("demo_point.shp");
      context.addLayer(layer);
      context.setTitle("DemoContext");
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return context;
  }
  @Test
  public void testModifyIssue() throws Exception {
    String newDescription = "new modified description"; // $NON-NLS-1$

    list.clear();
    list.add(IssuesListTestHelper.createFeatureIssue("test")); // $NON-NLS-1$

    list.refresh();
    assertEquals(1, list.size());

    IIssue issue = list.get(0);
    issue.setDescription(newDescription);
    ((IRemoteIssuesList) list).save(issue);
    FilterFactory factory = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());

    Expression expr2 = factory.literal(issue.getId());
    Expression expr1 = factory.property(IssuesListTestHelper.ISSUE_ID_ATTR);
    Filter filter = factory.equals(expr1, expr2);

    SimpleFeature next =
        store
            .getFeatureSource(featureType.getName().getLocalPart())
            .getFeatures(filter)
            .features()
            .next();
    assertEquals(newDescription, next.getAttribute(IssuesListTestHelper.DESCRIPTION_ATTR));
  }
Exemple #3
0
  private void save() throws Exception {
    FeatureStore fs = (FeatureStore) ds.getFeatureSource("poly_county");
    FeatureType ft = fs.getSchema();

    MemoryDataStore memorystore = new MemoryDataStore();

    ArrayList polys = new ArrayList(resultPolygon);

    Geometry gfinal = null;
    if (polys.size() == 1) {
      gfinal = (Polygon) polys.get(0); // POLYGON
    } else {
      GeometryFactory gf = ((Polygon) polys.get(0)).getFactory();
      gfinal = new MultiPolygon((Polygon[]) polys.toArray(new Polygon[polys.size()]), gf);
    }

    gfinal = gfinal.buffer(0); // for topologic problems.

    Object[] values = new Object[5];
    values[ft.find("module")] = MODULE;
    values[ft.find("gen_full")] = gfinal;

    values[ft.find("gen_1")] = generalize(gfinal, tolerance1);
    ;
    values[ft.find("gen_2")] = generalize(gfinal, tolerance1);
    ;
    values[ft.find("gen_3")] = generalize(gfinal, tolerance1);
    ;

    Feature f = ft.create(values);
    memorystore.addFeature(f);

    fs.addFeatures(memorystore.getFeatureReader("poly_county"));
  }
Exemple #4
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  private FeatureSource getFeatureSource(String typeName) {

    FeatureSource featureSource;
    try {
      featureSource = dataStore.getFeatureSource(typeName);
    } catch (Exception e) {
      throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_FEATURES);
    }

    return new ForwardingFeatureSource(featureSource) {

      @Override
      public FeatureCollection getFeatures(Query query) throws IOException {

        final FeatureCollection features = super.getFeatures(query);
        return new ForwardingFeatureCollection(features) {

          @Override
          public FeatureIterator features() {

            final FeatureType featureType = getSchema();
            final String fidPrefix = featureType.getName().getLocalPart() + ".";

            FeatureIterator iterator = delegate.features();
            return new FidPrefixRemovingIterator(iterator, fidPrefix);
          }
        };
      }
    };
  }
Exemple #5
0
 /**
  * Creates the source datastore reader.
  *
  * @param sourceDataStore
  * @param transaction
  * @param query
  * @return
  * @throws IOException
  */
 protected FeatureStore<SimpleFeatureType, SimpleFeature> createSourceReader(
     DataStore sourceDataStore, final Transaction transaction, Query query) throws IOException {
   FeatureStore<SimpleFeatureType, SimpleFeature> featureReader =
       (FeatureStore<SimpleFeatureType, SimpleFeature>)
           sourceDataStore.getFeatureSource(query.getTypeName());
   featureReader.setTransaction(transaction);
   return featureReader;
 }
 @SuppressWarnings("unchecked")
 private SimpleFeatureSource getFeatureSource(final URL shpfile) throws IOException {
   Map params = new HashMap<String, String>();
   params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, "false");
   params.put(ShapefileDataStoreFactory.URLP.key, shpfile);
   DataStore ds = DataStoreFinder.getDataStore(params);
   return ds.getFeatureSource(ds.getTypeNames()[0]);
 }
  @Override
  protected void setUpInternal(SystemTestData data) throws Exception {
    // run all the tests against a store that can do native paging (h2) and one that
    // can't (property)
    Catalog cat = getCatalog();
    DataStoreInfo ds = cat.getFactory().createDataStore();
    ds.setName("foo");
    ds.setWorkspace(cat.getDefaultWorkspace());

    Map params = ds.getConnectionParameters();
    params.put("dbtype", "h2");
    params.put("database", getTestData().getDataDirectoryRoot().getAbsolutePath());
    cat.add(ds);

    FeatureSource fs1 = getFeatureSource(SystemTestData.FIFTEEN);
    FeatureSource fs2 = getFeatureSource(SystemTestData.SEVEN);

    DataStore store = (DataStore) ds.getDataStore(null);
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();

    tb.init((SimpleFeatureType) fs1.getSchema());
    tb.add("num", Integer.class);
    tb.remove("boundedBy");
    store.createSchema(tb.buildFeatureType());

    tb.init((SimpleFeatureType) fs2.getSchema());
    tb.add("num", Integer.class);
    tb.remove("boundedBy");
    store.createSchema(tb.buildFeatureType());

    CatalogBuilder cb = new CatalogBuilder(cat);
    cb.setStore(ds);

    FeatureStore fs = (FeatureStore) store.getFeatureSource("Fifteen");
    addFeatures(fs, fs1.getFeatures());

    FeatureTypeInfo ft = cb.buildFeatureType(fs);
    cat.add(ft);

    fs = (FeatureStore) store.getFeatureSource("Seven");
    addFeatures(fs, fs2.getFeatures());

    ft = cb.buildFeatureType(fs);
    cat.add(ft);
  }
 @Test
 public void testInitialLoad() throws Exception {
   assertEquals(4, list.size());
   assertEquals("0", list.get(0).getId()); // $NON-NLS-1$
   assertEquals("1", list.get(1).getId()); // $NON-NLS-1$
   assertEquals("2", list.get(2).getId()); // $NON-NLS-1$
   assertEquals("3", list.get(3).getId()); // $NON-NLS-1$
   assertEquals(
       4, store.getFeatureSource(featureType.getName().getLocalPart()).getCount(Query.ALL));
 }
 @Test
 public void testRemoveInt() throws Exception {
   list.remove(1);
   assertEquals(3, list.size());
   assertEquals("0", list.get(0).getId()); // $NON-NLS-1$
   assertEquals("2", list.get(1).getId()); // $NON-NLS-1$
   assertEquals("3", list.get(2).getId()); // $NON-NLS-1$
   assertEquals(
       3, store.getFeatureSource(featureType.getName().getLocalPart()).getCount(Query.ALL));
 }
 private SimpleFeatureSource getLatLonFeatureSource() {
   try {
     DataStore ds = LATLON == null ? null : LATLON.get();
     if (ds == null) {
       ds = createLatLonDataStore();
       LATLON = new WeakReference<DataStore>(ds);
     }
     return ds.getFeatureSource("latlon");
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 @Test
 public void testAddIIssue() throws Exception {
   FeatureIssue issue = IssuesListTestHelper.createFeatureIssue("new"); // $NON-NLS-1$
   list.add(issue);
   assertEquals(5, list.size());
   assertEquals("new", list.get(4).getId()); // $NON-NLS-1$
   list.refresh();
   assertEquals(5, list.size());
   assertEquals("new", list.get(4).getId()); // $NON-NLS-1$
   assertEquals("groupID", list.get(4).getGroupId()); // $NON-NLS-1$
   assertEquals("test description", list.get(4).getDescription()); // $NON-NLS-1$
   assertEquals(
       5, store.getFeatureSource(featureType.getName().getLocalPart()).getCount(Query.ALL));
 }
  @Test
  @Ignore
  // this test is skipped, it checks something that formally is what we should expect,
  // but for the moment this breaks big time the shapefile renderer optimizations
  // until we get rid of the latter let's be a little lax on this one...
  public void testFeatureSource() throws Exception {
    File file = copyShapefiles("shapes/archsites.shp");
    tempDir = file.getParentFile();

    DataStore dds = new DirectoryDataStore(tempDir, getFileStoreFactory());
    FeatureSource fs = dds.getFeatureSource("archsites");
    assertNotNull(fs);
    assertSame(dds, fs.getDataStore());
    dds.dispose();
  }
  public void update(Object updatedObject) {
    if (updatedObject instanceof List) {
      String text = null;
      List layers = (List) updatedObject;
      for (Object layer : layers) {
        if (layer instanceof JGrassMapGeoResource) {
          JGrassMapGeoResource rasterMapResource = (JGrassMapGeoResource) layer;
          try {
            text = rasterMapResource.getInfo(null).getName();

            JGrassRegion fileWindow = rasterMapResource.getFileWindow();
            if (fileWindow != null) {
              setWidgetsToWindow(fileWindow);
            }
          } catch (IOException e1) {
            return;
          }
        } else if (layer instanceof DataStore || layer instanceof UDIGFeatureStore) {
          try {
            DataStore store = ((DataStore) layer);
            FeatureSource featureStore = store.getFeatureSource(store.getTypeNames()[0]);
            Envelope envelope = featureStore.getBounds();

            ActiveRegionStyle style = getActiveRegionStyle();
            JGrassRegion activeWindow =
                new JGrassRegion(
                    style.west, style.east, style.south, style.north, style.rows, style.cols);
            JGrassRegion newWindow =
                JGrassRegion.adaptActiveRegionToEnvelope(envelope, activeWindow);
            northText.setText(String.valueOf(newWindow.getNorth()));
            southText.setText(String.valueOf(newWindow.getSouth()));
            eastText.setText(String.valueOf(newWindow.getEast()));
            westText.setText(String.valueOf(newWindow.getWest()));
            textModified(bound_type);
          } catch (IOException e1) {
            e1.printStackTrace();
            return;
          }

        } else {
          return;
        }
      }
      if (text == null) {
        return;
      }
    }
  }
  @Test
  public void testFeatureReaderWithFilterBBoxPOST()
      throws NoSuchElementException, IllegalAttributeException, IOException, SAXException,
          IllegalFilterException {
    if (url == null) return;

    Map m = new HashMap();
    m.put(WFSDataStoreFactory.URL.key, url);
    m.put(WFSDataStoreFactory.TIMEOUT.key, new Integer(100000));
    DataStore post = (WFS_1_0_0_DataStore) (new WFSDataStoreFactory()).createDataStore(m);

    String typeName = post.getTypeNames()[0];
    Envelope bbox = post.getFeatureSource(typeName).getBounds();

    WFSDataStoreReadTest.doFeatureReaderWithBBox(url, true, false, 0, bbox);
  }
  @Override
  public <T> T resolve(Class<T> adaptee, IProgressMonitor monitor) throws IOException {
    if (null == adaptee) {
      return null;
    }

    if (adaptee.isAssignableFrom(FeatureSource.class)) {
      DataStore ds = this.service.resolve(DataStore.class, monitor);
      String[] a = ds.getTypeNames();
      String featureName = a[0];

      FeatureSource<SimpleFeatureType, SimpleFeature> fs = ds.getFeatureSource(featureName);

      return adaptee.cast(fs);
    }

    return super.resolve(adaptee, monitor);
  }
 @Test
 public void testBackendRemovedIssue() throws Exception {
   FeatureStore<SimpleFeatureType, SimpleFeature> fs =
       (FeatureStore<SimpleFeatureType, SimpleFeature>)
           store.getFeatureSource(featureType.getName().getLocalPart());
   FilterFactory factory = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
   Expression expr2 = factory.literal("1");
   Expression expr1 = factory.property(IssuesListTestHelper.ISSUE_ID_ATTR);
   Filter filter = factory.equals(expr1, expr2);
   fs.removeFeatures(filter);
   list.refresh();
   for (IIssue issue : list) {
     System.out.println(issue.getId());
   }
   assertEquals(3, list.size());
   assertEquals("0", list.get(0).getId()); // $NON-NLS-1$
   assertEquals("2", list.get(1).getId()); // $NON-NLS-1$
   assertEquals("3", list.get(2).getId()); // $NON-NLS-1$
 }
  /**
   * This test is made with mock objects because the property data store does not generate fids in
   * the <type>.<id> form
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testAppend() throws Exception {
    SimpleFeatureType type =
        DataUtilities.createType("trees", "the_geom:Point,FID:String,NAME:String");

    SimpleFeatureStore fs = createMock(SimpleFeatureStore.class);
    expect(fs.addFeatures(isA(FeatureCollection.class)))
        .andReturn(Collections.singletonList((FeatureId) (new FeatureIdImpl("trees.105"))));
    replay(fs);

    DataStore ds = createMock(DataStore.class);
    expect(ds.getTypeNames()).andReturn(new String[] {"trees"}).anyTimes();
    expect(ds.getSchema("trees")).andReturn(type).anyTimes();
    expect(ds.getFeatureSource("trees")).andReturn(fs);
    replay(ds);

    RetypingDataStore rts =
        new RetypingDataStore(ds) {
          @Override
          protected String transformFeatureTypeName(String originalName) {
            return "oaks";
          }
        };

    SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(type);
    WKTReader reader = new WKTReader();
    sfb.set("the_geom", reader.read("POINT (0.002 0.0008)"));
    sfb.set("FID", "023");
    sfb.set("NAME", "Old oak");
    SimpleFeature feature = sfb.buildFeature(null);
    SimpleFeatureCollection fc = DataUtilities.collection(feature);

    SimpleFeatureStore store = (SimpleFeatureStore) rts.getFeatureSource("oaks");
    List<FeatureId> ids = store.addFeatures(fc);
    assertEquals(1, ids.size());
    String id = ((FeatureId) ids.iterator().next()).getID();
    assertTrue("Id does not start with " + "oaks" + " it's " + id, id.startsWith("oaks"));
  }
Exemple #18
0
 /**
  * Builds a FeatureStore for the output Feature.
  *
  * @param store
  * @param schema
  * @return
  * @throws IOException
  */
 protected FeatureStore<SimpleFeatureType, SimpleFeature> createOutputWriter(
     DataStore store, SimpleFeatureType schema, Transaction transaction) throws IOException {
   String destTypeName = schema.getTypeName();
   boolean createSchema = true;
   for (String typeName : store.getTypeNames()) {
     if (typeName.equalsIgnoreCase(destTypeName)) {
       createSchema = false;
       destTypeName = typeName;
     }
   }
   // check for case changing in typeName
   if (createSchema) {
     store.createSchema(schema);
     for (String typeName : store.getTypeNames()) {
       if (!typeName.equals(destTypeName) && typeName.equalsIgnoreCase(destTypeName)) {
         destTypeName = typeName;
       }
     }
   }
   FeatureStore<SimpleFeatureType, SimpleFeature> result =
       (FeatureStore<SimpleFeatureType, SimpleFeature>) store.getFeatureSource(destTypeName);
   result.setTransaction(transaction);
   return result;
 }
  /**
   * Writing test that only engages against a remote geoserver.
   *
   * <p>Makes reference to the standard featureTypes that geoserver ships with. NOTE: Ignoring this
   * test for now because it edits topp:states and GeoServer doesn't return the correct Feature IDs
   * on transactions against shapefiles
   */
  @Test
  @Ignore
  public void testWrite()
      throws NoSuchElementException, IllegalFilterException, IOException,
          IllegalAttributeException {
    if (url == null) return;

    Map m = new HashMap();
    m.put(WFSDataStoreFactory.URL.key, url);
    m.put(WFSDataStoreFactory.TIMEOUT.key, new Integer(10000000));
    DataStore post = (WFS_1_0_0_DataStore) (new WFSDataStoreFactory()).createDataStore(m);
    String typename = TO_EDIT_TYPE;
    SimpleFeatureType ft = post.getSchema(typename);
    SimpleFeatureSource fs = post.getFeatureSource(typename);
    class Watcher implements FeatureListener {
      public int count = 0;

      public void changed(FeatureEvent featureEvent) {
        System.out.println("Event " + featureEvent);
        count++;
      }
    }
    Watcher watcher = new Watcher();
    fs.addFeatureListener(watcher);

    Id startingFeatures = createFidFilter(fs);
    FilterFactory2 filterFac = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
    try {
      GeometryFactory gf = new GeometryFactory();
      MultiPolygon mp =
          gf.createMultiPolygon(
              new Polygon[] {
                gf.createPolygon(
                    gf.createLinearRing(
                        new Coordinate[] {
                          new Coordinate(-88.071564, 37.51099),
                          new Coordinate(-88.467644, 37.400757),
                          new Coordinate(-90.638329, 42.509361),
                          new Coordinate(-89.834618, 42.50346),
                          new Coordinate(-88.071564, 37.51099)
                        }),
                    new LinearRing[] {})
              });
      mp.setUserData("http://www.opengis.net/gml/srs/epsg.xml#" + EPSG_CODE);

      PropertyName geometryAttributeExpression =
          filterFac.property(ft.getGeometryDescriptor().getLocalName());
      PropertyIsNull geomNullCheck = filterFac.isNull(geometryAttributeExpression);
      Query query = new Query(typename, filterFac.not(geomNullCheck), 1, Query.ALL_NAMES, null);
      SimpleFeatureIterator inStore = fs.getFeatures(query).features();

      SimpleFeature f, f2;
      try {
        SimpleFeature feature = inStore.next();

        SimpleFeature copy = SimpleFeatureBuilder.deep(feature);
        SimpleFeature copy2 = SimpleFeatureBuilder.deep(feature);

        f = SimpleFeatureBuilder.build(ft, copy.getAttributes(), null);
        f2 = SimpleFeatureBuilder.build(ft, copy2.getAttributes(), null);
        assertFalse("Max Feature failed", inStore.hasNext());
      } finally {
        inStore.close();
      }

      org.geotools.util.logging.Logging.getLogger("org.geotools.data.wfs").setLevel(Level.FINE);
      SimpleFeatureCollection inserts = DataUtilities.collection(new SimpleFeature[] {f, f2});
      Id fp = WFSDataStoreWriteOnlineTest.doInsert(post, ft, inserts);

      // / okay now count ...
      FeatureReader<SimpleFeatureType, SimpleFeature> count =
          post.getFeatureReader(new Query(ft.getTypeName()), Transaction.AUTO_COMMIT);
      int i = 0;
      while (count.hasNext() && i < 3) {
        f = count.next();
        i++;
      }
      count.close();

      WFSDataStoreWriteOnlineTest.doDelete(post, ft, fp);
      WFSDataStoreWriteOnlineTest.doUpdate(post, ft, ATTRIBUTE_TO_EDIT, NEW_EDIT_VALUE);
      // assertFalse("events not fired", watcher.count == 0);
    } finally {
      try {
        ((SimpleFeatureStore) fs).removeFeatures(filterFac.not(startingFeatures));
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
 private SimpleFeatureIterator getIterator() throws Exception {
   String typeName = dataStore.getTypeNames()[0];
   SimpleFeatureCollection collection = dataStore.getFeatureSource(typeName).getFeatures();
   return collection.features();
 }
  public static IGlobeFeatureCollection<
          IVector2, ? extends IBoundedGeometry2D<? extends IFinite2DBounds<?>>>
      readFeatures(final DataStore dataStore, final String layerName, final GProjection projection)
          throws Exception {

    final SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);

    final SimpleFeatureCollection featuresCollection = featureSource.getFeatures();

    final GIntHolder validCounter = new GIntHolder(0);
    // final GIntHolder polygonsWithHolesCounter = new GIntHolder(0);
    final GIntHolder invalidCounter = new GIntHolder(0);
    //      final GIntHolder validVerticesCounter = new GIntHolder(0);
    final GIntHolder polygonsCounter = new GIntHolder(0);
    final GIntHolder linesCounter = new GIntHolder(0);
    final GIntHolder pointsCounter = new GIntHolder(0);

    final int featuresCount = featuresCollection.size();
    final ArrayList<IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>
        euclidFeatures =
            new ArrayList<
                IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>(
                featuresCount);

    final GProgress progress =
        new GProgress(featuresCount) {
          @Override
          public void informProgress(
              final double percent, final long elapsed, final long estimatedMsToFinish) {
            //            System.out.println("Loading \"" + fileName.buildPath() + "\" "
            //                               + progressString(percent, elapsed,
            // estimatedMsToFinish));
            System.out.println(
                "Loading data from data storage: "
                    + layerName
                    + " "
                    + progressString(percent, elapsed, estimatedMsToFinish));
          }
        };

    final FeatureIterator<SimpleFeature> iterator = featuresCollection.features();

    while (iterator.hasNext()) {
      final SimpleFeature feature = iterator.next();

      final GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty();

      final GeometryType type = geometryAttribute.getType();

      if (type.getBinding() == com.vividsolutions.jts.geom.MultiPolygon.class) {

        polygonsCounter.increment();

        final com.vividsolutions.jts.geom.MultiPolygon multipolygon =
            (com.vividsolutions.jts.geom.MultiPolygon) geometryAttribute.getValue();
        final int geometriesCount = multipolygon.getNumGeometries();

        final List<IPolygon2D> polygons = new ArrayList<IPolygon2D>(geometriesCount);
        for (int i = 0; i < geometriesCount; i++) {
          final com.vividsolutions.jts.geom.Polygon jtsPolygon =
              (com.vividsolutions.jts.geom.Polygon) multipolygon.getGeometryN(i);

          try {
            final IPolygon2D euclidPolygon = createEuclidPolygon(projection, jtsPolygon);

            if (euclidPolygon != null) {
              //                     euclidFeatures.add(createFeature(euclidPolygon, feature));
              polygons.add(euclidPolygon);
              validCounter.increment();
            }
          } catch (final IllegalArgumentException e) {
            //                     System.err.println(e.getMessage());
          }
        }

        if (!polygons.isEmpty()) {
          if (polygons.size() == 1) {
            euclidFeatures.add(createFeature(polygons.get(0), feature));
          } else {
            euclidFeatures.add(createFeature(new GMultiGeometry2D<IPolygon2D>(polygons), feature));
          }
        }

      } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiLineString.class) {

        linesCounter.increment();

        final com.vividsolutions.jts.geom.MultiLineString multiline =
            (com.vividsolutions.jts.geom.MultiLineString) geometryAttribute.getValue();
        final int geometriesCount = multiline.getNumGeometries();

        final List<IPolygonalChain2D> lines = new ArrayList<IPolygonalChain2D>(geometriesCount);
        for (int i = 0; i < geometriesCount; i++) {
          final com.vividsolutions.jts.geom.LineString jtsLine =
              (com.vividsolutions.jts.geom.LineString) multiline.getGeometryN(i);

          try {
            final IPolygonalChain2D euclidLine = createLine(jtsLine.getCoordinates(), projection);

            // euclidFeatures.add(createFeature(euclidLines, feature));
            lines.add(euclidLine);
          } catch (final IllegalArgumentException e) {
            //                     System.err.println(e.getMessage());
          }
        }

        if (!lines.isEmpty()) {
          if (lines.size() == 1) {
            euclidFeatures.add(createFeature(lines.get(0), feature));
          } else {
            euclidFeatures.add(
                createFeature(new GMultiGeometry2D<IPolygonalChain2D>(lines), feature));
          }
        }

        validCounter.increment();
      } else if (type.getBinding() == com.vividsolutions.jts.geom.Point.class) {

        pointsCounter.increment();

        final IVector2 euclidPoint =
            createPoint(
                ((com.vividsolutions.jts.geom.Point) geometryAttribute.getValue()).getCoordinate(),
                projection);
        euclidFeatures.add(createFeature(euclidPoint, feature));

        validCounter.increment();
      } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiPoint.class) {
        final IBoundedGeometry2D<? extends IFinite2DBounds<?>> euclidMultipoint =
            createEuclidMultiPoint(geometryAttribute, projection);
        euclidFeatures.add(createFeature(euclidMultipoint, feature));

        validCounter.increment();
      } else {
        invalidCounter.increment();
        System.out.println("invalid type: " + type);
      }

      progress.stepDone();
    }

    dataStore.dispose();

    euclidFeatures.trimToSize();

    System.out.println();
    System.out.println("Features: " + featuresCount);

    System.out.println();
    System.out.println("Read " + validCounter.get() + " valid geometries");

    System.out.println("  => " + polygonsCounter.get() + " valid polygons");
    System.out.println("  => " + linesCounter.get() + " valid lines");
    System.out.println("  => " + pointsCounter.get() + " valid points");
    System.out.println();

    if (invalidCounter.get() > 0) {
      System.out.println("Ignored " + invalidCounter.get() + " invalid geometries");
    }

    System.out.println();

    final SimpleFeatureType schema = featureSource.getSchema();
    final int fieldsCount = schema.getAttributeCount();
    final List<GField> fields = new ArrayList<GField>(fieldsCount);
    System.out.println("Fields count: " + fieldsCount);
    for (int i = 0; i < fieldsCount; i++) {
      final String fieldName = schema.getType(i).getName().getLocalPart();
      System.out.println("Fieldname: " + fieldName);
      final Class<?> fieldType = schema.getType(i).getBinding();

      fields.add(new GField(fieldName, fieldType));
    }

    return new GListFeatureCollection<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>(
        GProjection.EPSG_4326, fields, euclidFeatures, "uniqueId_000");
  }
  private SimpleFeatureType importDataIntoStore(
      SimpleFeatureCollection features, String name, DataStoreInfo storeInfo)
      throws IOException, ProcessException {
    SimpleFeatureType targetType;
    // grab the data store
    DataStore ds = (DataStore) storeInfo.getDataStore(null);

    // decide on the target ft name
    SimpleFeatureType sourceType = features.getSchema();
    if (name != null) {
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.init(sourceType);
      tb.setName(name);
      sourceType = tb.buildFeatureType();
    }

    // create the schema
    ds.createSchema(sourceType);

    // try to get the target feature type (might have slightly different
    // name and structure)
    targetType = ds.getSchema(sourceType.getTypeName());
    if (targetType == null) {
      // ouch, the name was changed... we can only guess now...
      // try with the typical Oracle mangling
      targetType = ds.getSchema(sourceType.getTypeName().toUpperCase());
    }

    if (targetType == null) {
      throw new WPSException(
          "The target schema was created, but with a name "
              + "that we cannot relate to the one we provided the data store. Cannot proceeed further");
    } else {
      // check the layer is not already there
      String newLayerName = storeInfo.getWorkspace().getName() + ":" + targetType.getTypeName();
      LayerInfo layer = catalog.getLayerByName(newLayerName);
      // todo: we should not really reach here and know beforehand what the targetType
      // name is, but if we do we should at least get a way to drop it
      if (layer != null) {
        throw new ProcessException(
            "Target layer " + newLayerName + " already exists in the catalog");
      }
    }

    // try to establish a mapping with old and new attributes. This is again
    // just guesswork until we have a geotools api that will give us the
    // exact mapping to be performed
    Map<String, String> mapping = buildAttributeMapping(sourceType, targetType);

    // start a transaction and fill the target with the input features
    Transaction t = new DefaultTransaction();
    SimpleFeatureStore fstore = (SimpleFeatureStore) ds.getFeatureSource(targetType.getTypeName());
    fstore.setTransaction(t);
    SimpleFeatureIterator fi = features.features();
    SimpleFeatureBuilder fb = new SimpleFeatureBuilder(targetType);
    while (fi.hasNext()) {
      SimpleFeature source = fi.next();
      fb.reset();
      for (String sname : mapping.keySet()) {
        fb.set(mapping.get(sname), source.getAttribute(sname));
      }
      SimpleFeature target = fb.buildFeature(null);
      fstore.addFeatures(DataUtilities.collection(target));
    }
    t.commit();
    t.close();

    return targetType;
  }
Exemple #23
0
  /** Executes the export command using the provided options. */
  @Override
  protected final void runInternal(GeogigCLI cli) throws IOException {
    if (args.isEmpty()) {
      printUsage(cli);
      throw new CommandFailedException();
    }

    String path = args.get(0);
    String tableName = args.get(1);

    checkParameter(tableName != null && !tableName.isEmpty(), "No table name specified");

    DataStore dataStore = getDataStore();

    ObjectId featureTypeId = null;
    if (!Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
      SimpleFeatureType outputFeatureType;
      if (sFeatureTypeId != null) {
        // Check the feature type id string is a correct id
        Optional<ObjectId> id =
            cli.getGeogig().command(RevParse.class).setRefSpec(sFeatureTypeId).call();
        checkParameter(id.isPresent(), "Invalid feature type reference", sFeatureTypeId);
        TYPE type = cli.getGeogig().command(ResolveObjectType.class).setObjectId(id.get()).call();
        checkParameter(
            type.equals(TYPE.FEATURETYPE),
            "Provided reference does not resolve to a feature type: ",
            sFeatureTypeId);
        outputFeatureType =
            (SimpleFeatureType)
                cli.getGeogig()
                    .command(RevObjectParse.class)
                    .setObjectId(id.get())
                    .call(RevFeatureType.class)
                    .get()
                    .type();
        featureTypeId = id.get();
      } else {
        try {
          SimpleFeatureType sft = getFeatureType(path, cli);
          outputFeatureType =
              new SimpleFeatureTypeImpl(
                  new NameImpl(tableName),
                  sft.getAttributeDescriptors(),
                  sft.getGeometryDescriptor(),
                  sft.isAbstract(),
                  sft.getRestrictions(),
                  sft.getSuper(),
                  sft.getDescription());
        } catch (GeoToolsOpException e) {
          throw new CommandFailedException("No features to export.", e);
        }
      }
      try {
        dataStore.createSchema(outputFeatureType);
      } catch (IOException e) {
        throw new CommandFailedException("Cannot create new table in database", e);
      }
    } else {
      if (!overwrite) {
        throw new CommandFailedException("The selected table already exists. Use -o to overwrite");
      }
    }

    SimpleFeatureSource featureSource = dataStore.getFeatureSource(tableName);
    if (!(featureSource instanceof SimpleFeatureStore)) {
      throw new CommandFailedException("Can't write to the selected table");
    }
    SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    if (overwrite) {
      try {
        featureStore.removeFeatures(Filter.INCLUDE);
      } catch (IOException e) {
        throw new CommandFailedException("Error truncating table: " + e.getMessage(), e);
      }
    }
    ExportOp op =
        cli.getGeogig()
            .command(ExportOp.class)
            .setFeatureStore(featureStore)
            .setPath(path)
            .setFilterFeatureTypeId(featureTypeId)
            .setAlter(alter);
    if (defaultType) {
      op.exportDefaultFeatureType();
    }
    try {
      op.setProgressListener(cli.getProgressListener()).call();
    } catch (IllegalArgumentException iae) {
      throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
      switch (e.statusCode) {
        case MIXED_FEATURE_TYPES:
          throw new CommandFailedException(
              "The selected tree contains mixed feature types. Use --defaulttype or --featuretype <feature_type_ref> to export.",
              e);
        default:
          throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
      }
    }

    cli.getConsole().println(path + " exported successfully to " + tableName);
  }
  /**
   * Extract the data as defined in the request object.
   *
   * @return the directory that contains the extracted file
   */
  public File extract(ExtractorLayerRequest request)
      throws IOException, TransformException, FactoryException {
    if (request._owsType != OWSType.WFS) {
      throw new IllegalArgumentException(request._owsType + "must be WFS for the WfsExtractor");
    }

    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(WFSDataStoreFactory.URL.key, request.capabilitiesURL("WFS", "1.0.0"));
    params.put(WFSDataStoreFactory.LENIENT.key, true);
    params.put(WFSDataStoreFactory.PROTOCOL.key, true);
    params.put(WFSDataStoreFactory.TIMEOUT.key, Integer.valueOf(60000));
    params.put(WFSDataStoreFactory.MAXFEATURES.key, Integer.valueOf(0));

    // HACK  I want unrestricted access to layers.
    // Security check takes place in ExtractorThread
    if (_secureHost.equalsIgnoreCase(request._url.getHost())
        || "127.0.0.1".equalsIgnoreCase(request._url.getHost())
        || "localhost".equalsIgnoreCase(request._url.getHost())) {
      LOG.debug(
          "WfsExtractor.extract - Secured Server: Adding extractionUserName to connection params");
      if (_adminUsername != null) params.put(WFSDataStoreFactory.USERNAME.key, _adminUsername);
      if (_adminPassword != null) params.put(WFSDataStoreFactory.PASSWORD.key, _adminPassword);
    } else {
      LOG.debug("WfsExtractor.extract - Non Secured Server");
    }

    DataStore sourceDs = DataStoreFinder.getDataStore(params);
    // WFS-ng: we need to convert the schema name

    String typeName = request.getWFSName();
    SimpleFeatureType sourceSchema = null;
    // prefixed typeName
    if (typeName.contains(":")) {
      typeName = typeName.replaceFirst(":", "_");
      sourceSchema = sourceDs.getSchema(typeName);
    }
    // Not prefixed one (mapserver ?)
    else {
      // Recreating the datastore forcing wfs 1.1.0, so that (presuming
      // the remote server is actually powered by MapServer), we would
      // have a typename prefixed with the same convention as before.
      params.put(WFSDataStoreFactory.URL.key, request.capabilitiesURL("WFS", "1.1.0"));
      // params.put(WFSDataStoreFactory.WFS_STRATEGY.key, "mapserver");
      sourceDs = DataStoreFinder.getDataStore(params);
      String[] typeNames = sourceDs.getTypeNames();
      for (String s : typeNames) {
        if (s.contains(typeName)) {
          typeName = s;
          sourceSchema = sourceDs.getSchema(s);
          // replace the expected typename in the request
          break;
        }
      }
      if (sourceSchema == null) {
        throw new IOException("Unable to find the remote layer " + typeName);
      }
    }

    Query query = createQuery(request, sourceSchema);
    SimpleFeatureCollection features = sourceDs.getFeatureSource(typeName).getFeatures(query);

    ProgressListener progressListener =
        new NullProgressListener() {
          @Override
          public void exceptionOccurred(Throwable exception) {
            throw new RuntimeException(exception);
          }
        };
    File basedir = request.createContainingDir(_basedir);

    basedir.mkdirs();

    FeatureWriterStrategy featuresWriter;
    BBoxWriter bboxWriter;
    LOG.debug("Number of features returned : " + features.size());
    if ("shp".equalsIgnoreCase(request._format)) {
      featuresWriter = new ShpFeatureWriter(progressListener, sourceSchema, basedir, features);
      bboxWriter =
          new BBoxWriter(
              request._bbox,
              basedir,
              OGRFeatureWriter.FileFormat.shp,
              request._projection,
              progressListener);
    } else if ("mif".equalsIgnoreCase(request._format)) {
      // featuresWriter = new MifFeatureWriter(progressListener, sourceSchema, basedir, features);
      featuresWriter =
          new OGRFeatureWriter(
              progressListener, sourceSchema, basedir, OGRFeatureWriter.FileFormat.mif, features);
      bboxWriter =
          new BBoxWriter(
              request._bbox,
              basedir,
              OGRFeatureWriter.FileFormat.mif,
              request._projection,
              progressListener);
    } else if ("tab".equalsIgnoreCase(request._format)) {
      featuresWriter =
          new OGRFeatureWriter(
              progressListener, sourceSchema, basedir, OGRFeatureWriter.FileFormat.tab, features);
      bboxWriter =
          new BBoxWriter(
              request._bbox,
              basedir,
              OGRFeatureWriter.FileFormat.tab,
              request._projection,
              progressListener);
    } else if ("kml".equalsIgnoreCase(request._format)) {
      featuresWriter =
          new OGRFeatureWriter(
              progressListener, sourceSchema, basedir, OGRFeatureWriter.FileFormat.kml, features);
      bboxWriter =
          new BBoxWriter(
              request._bbox,
              basedir,
              OGRFeatureWriter.FileFormat.kml,
              request._projection,
              progressListener);
    } else {
      throw new IllegalArgumentException(request._format + " is not a recognized vector format");
    }
    // generates the feature files and bbox file
    featuresWriter.generateFiles();

    bboxWriter.generateFiles();

    return basedir;
  }