@Test
  public void testCreateSchema() throws Exception {
    File dir = File.createTempFile("foo", "shp", new File("target"));
    dir.delete();
    dir.mkdir();

    DataStore ds = new DirectoryDataStore(dir, getFileStoreFactory());
    assertEquals(0, ds.getTypeNames().length);

    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName("foo");
    tb.add("geom", Polygon.class);
    tb.add("bar", Integer.class);
    ds.createSchema(tb.buildFeatureType());

    SimpleFeatureType ft = ds.getSchema("foo");
    assertNotNull(ft);

    // clean up
    ds.dispose();
    for (File f : dir.listFiles()) {
      f.delete();
    }
    dir.delete();
  }
 @Override
 public String getTypeName(URL url) throws IOException {
   DataStore ds = createDataStore(url);
   String[] names = ds.getTypeNames();
   assert names.length == 1 : "Invalid number of type names for csv file store";
   ds.dispose();
   return names[0];
 }
Example #3
0
 protected void closeResource(DataStore dataStore) {
   if (dataStore != null) {
     try {
       dataStore.dispose();
     } catch (Throwable t) {
       if (LOGGER.isErrorEnabled()) {
         LOGGER.error("Error closing datastore connection");
       }
     }
   }
 }
 @Override
 public void dispose(IProgressMonitor monitor) {
   super.dispose(monitor); // clean up members
   if (dataStore != null) {
     dataStore.dispose();
     dataStore = null;
   }
   if (resources != null) {
     resources = null;
   }
 }
  @Test
  public void testSchema() throws Exception {
    File file = copyShapefiles("shapes/archsites.shp");
    tempDir = file.getParentFile();

    DataStore dds = new DirectoryDataStore(tempDir, getFileStoreFactory());

    assertEquals(1, dds.getTypeNames().length);
    assertEquals("archsites", dds.getTypeNames()[0]);
    dds.dispose();
  }
  @Test
  public void testTypeNames() throws Exception {
    copyShapefiles("shapes/archsites.shp");
    File f = copyShapefiles("shapes/bugsites.shp");
    tempDir = f.getParentFile();

    DataStore store = new DirectoryDataStore(tempDir, getFileStoreFactory());
    List<String> typeNames = Arrays.asList(store.getTypeNames());
    assertEquals(2, typeNames.size());
    assertTrue(typeNames.contains("archsites"));
    assertTrue(typeNames.contains("bugsites"));
    store.dispose();
  }
 @Test
 public void testDispose() throws IOException {
   store.dispose();
   try {
     ((ArcSDEDataStore) store).getSession(Transaction.AUTO_COMMIT);
     fail("Expected IllegalStateException when the datastore has been disposed");
   } catch (IllegalStateException e) {
     assertTrue(true);
   } finally {
     // dispose test data so next test does not fail due to pool being
     // closed
     testData.tearDown(false, true);
     testData = null;
   }
 }
  @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();
  }
 /**
  * Test that a filter query issued.
  *
  * @param filter filter to be passed in the query to determine the subset of features to be
  *     returned, or null for all features
  * @param expectedFeatureIds integer id for returned features, matching the expected row ids
  * @throws Exception
  */
 private void runFilterTest(Filter filter, int[] expectedFeatureIds) throws Exception {
   DataStore datastore = null;
   try {
     datastore = DataStoreFinder.getDataStore(getParams());
     assertNotNull(datastore);
     Query query = new DefaultQuery(TEST_TABLE_NAME, filter);
     FeatureReader<SimpleFeatureType, SimpleFeature> reader = null;
     try {
       /*
        * List of all the integer feature ids seen in the features returned for this query.
        */
       List<Integer> featureIds = new ArrayList<Integer>();
       reader = datastore.getFeatureReader(query, Transaction.AUTO_COMMIT);
       for (SimpleFeature feature = null; reader.hasNext(); ) {
         feature = reader.next();
         /*
          * Convert long feature id of the form test_table_name.1234 to the numeric id
          * used when creating the row. This relies on the behaviour of the postgis fid
          * mapper.
          */
         Integer id = Integer.valueOf(feature.getID().replace(TEST_TABLE_NAME + ".", ""));
         featureIds.add(id);
       }
       /*
        * The query succeeded as expected if and only if the sorted lists of returned and
        * expected ids are equal. The expected ids are converted to a List of Integers to
        * leverage Collections comparison.
        */
       assertEquals(sortedList(expectedFeatureIds), sorted(featureIds));
     } finally {
       if (reader != null) {
         reader.close();
       }
     }
   } finally {
     if (datastore != null) {
       datastore.dispose();
     }
   }
 }
Example #10
0
  /**
   * Executes the describe command using the provided options.
   *
   * @param cli
   * @see
   *     org.geogit.geotools.cli.porcelain.AbstractOracleCommand#runInternal(org.geogit.cli.GeogitCLI)
   */
  @Override
  protected void runInternal(GeogitCLI cli) throws IOException {
    DataStore dataStore = getDataStore();

    try {
      cli.getConsole().println("Fetching table...");

      Optional<Map<String, String>> propertyMap =
          cli.getGeogit().command(DescribeOp.class).setTable(table).setDataStore(dataStore).call();

      if (propertyMap.isPresent()) {
        cli.getConsole().println("Table : " + table);
        cli.getConsole().println("----------------------------------------");
        for (Entry<String, String> entry : propertyMap.get().entrySet()) {
          cli.getConsole().println("\tProperty  : " + entry.getKey());
          cli.getConsole().println("\tType      : " + entry.getValue());
          cli.getConsole().println("----------------------------------------");
        }
      } else {
        throw new CommandFailedException("Could not find the specified table.");
      }
    } catch (GeoToolsOpException e) {
      switch (e.statusCode) {
        case TABLE_NOT_DEFINED:
          throw new CommandFailedException("No table supplied.", e);
        case UNABLE_TO_GET_FEATURES:
          throw new CommandFailedException("Unable to read the feature source.", e);
        case UNABLE_TO_GET_NAMES:
          throw new CommandFailedException("Unable to read feature types.", e);
        default:
          throw new CommandFailedException("Exception: " + e.statusCode.name(), e);
      }

    } finally {
      dataStore.dispose();
      cli.getConsole().flush();
    }
  }
Example #11
0
  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");
  }