⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shapefiledatastoretest.java

📁 shape file read and write
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
        build.add("g", Date.class);
        build.add("h", Boolean.class);
        build.add("i", Number.class);
        build.add("j", Long.class);
        build.add("k", BigDecimal.class);
        build.add("l", BigInteger.class);

        return build.buildFeatureType();
    }

    public void testAttributesWriting() throws Exception {
        FeatureCollection<SimpleFeatureType, SimpleFeature> features = createFeatureCollection();
        File tmpFile = getTempFile();
        tmpFile.createNewFile();
        ShapefileDataStore s = new ShapefileDataStore(tmpFile.toURL());
        writeFeatures(s, features);
    }

    public void testWriteReadBigNumbers() throws Exception {
        // create feature type
        SimpleFeatureType type = DataUtilities.createType("junk",
                "a:Point,b:java.math.BigDecimal,c:java.math.BigInteger");
        FeatureCollection<SimpleFeatureType, SimpleFeature> features = FeatureCollections.newCollection();

        BigInteger bigInteger = new BigInteger("1234567890123456789");
        BigDecimal bigDecimal = new BigDecimal(bigInteger, 2);

        SimpleFeatureBuilder build = new SimpleFeatureBuilder(type);
        build.add(new GeometryFactory().createPoint(new Coordinate(1, -1)));
        build.add(bigDecimal);
        build.add(bigInteger);

        SimpleFeature feature = build.buildFeature(null);
        features.add(feature);

        // store features
        File tmpFile = getTempFile();
        tmpFile.createNewFile();
        ShapefileDataStore s = new ShapefileDataStore(tmpFile.toURL());
        writeFeatures(s, features);

        // read them back
         FeatureReader<SimpleFeatureType, SimpleFeature> reader = s.getFeatureReader("junk");
        try {
            SimpleFeature f = reader.next();

            assertEquals("big decimal", bigDecimal.doubleValue(), ((Number) f
                    .getAttribute("b")).doubleValue(), 0.00001);
            assertEquals("big integer", bigInteger.longValue(), ((Number) f
                    .getAttribute("c")).longValue(), 0.00001);
        } finally {
            reader.close();
        }
    }

    public void testGeometriesWriting() throws Exception {

        String[] wktResources = new String[] { "point", "multipoint", "line",
                "multiline", "polygon", "multipolygon" };

        for (int i = 0; i < wktResources.length; i++) {
            Geometry geom = readGeometry(wktResources[i]);
            String testName = wktResources[i];
            try {

                runWriteReadTest(geom, false);
                make3D(geom);
                testName += "3d";
                runWriteReadTest(geom, true);
            } catch (Throwable e) {
                e.printStackTrace();
                throw new Exception("Error in " + testName, e);
            }

        }

    }

    private void make3D(Geometry g) {
        Coordinate[] c = g.getCoordinates();
        for (int i = 0, ii = c.length; i < ii; i++) {
            c[i].z = 42 + i;
        }
    }

    private void writeFeatures(ShapefileDataStore s, FeatureCollection<SimpleFeatureType, SimpleFeature> fc)
            throws Exception {
        s.createSchema(fc.features().next().getFeatureType());
        FeatureWriter<SimpleFeatureType, SimpleFeature> fw = s.getFeatureWriter(s.getTypeNames()[0],
                Transaction.AUTO_COMMIT);
        FeatureIterator<SimpleFeature> it = fc.features();
        while (it.hasNext()) {
            SimpleFeature feature = it.next();
            SimpleFeature newFeature = fw.next();
            newFeature.setAttributes(feature.getAttributes());

            fw.write();
        }
        fw.close();
    }

    private void runWriteReadTest(Geometry geom, boolean d3) throws Exception {
        // make features

        SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
        ftb.setName("Junk");
        ftb.add("a", geom.getClass());
        SimpleFeatureType type = ftb.buildFeatureType();

        FeatureCollection<SimpleFeatureType, SimpleFeature> features = FeatureCollections.newCollection();
        SimpleFeatureBuilder build = new SimpleFeatureBuilder(type);
        for (int i = 0, ii = 20; i < ii; i++) {
            build.set(0, (Geometry) geom.clone());
            SimpleFeature feature = build.buildFeature(null);

            features.add(feature);
        }

        // set up file
        File tmpFile = getTempFile();
        tmpFile.delete();

        // write features
        ShapefileDataStore shapeDataStore = new ShapefileDataStore(tmpFile
                .toURL());
        shapeDataStore.createSchema(type);
        writeFeatures(shapeDataStore, features);

        // read features
        shapeDataStore = new ShapefileDataStore(tmpFile.toURL());
        FeatureCollection<SimpleFeatureType, SimpleFeature> fc = loadFeatures(shapeDataStore);
        FeatureIterator<SimpleFeature> fci = fc.features();
        // verify
        while (fci.hasNext()) {
            SimpleFeature f = fci.next();
            Geometry fromShape = (Geometry) f.getDefaultGeometry();

            if (fromShape instanceof GeometryCollection) {
                if (!(geom instanceof GeometryCollection)) {
                    fromShape = ((GeometryCollection) fromShape)
                            .getGeometryN(0);
                }
            }
            try {
                Coordinate[] c1 = geom.getCoordinates();
                Coordinate[] c2 = fromShape.getCoordinates();
                for (int cc = 0, ccc = c1.length; cc < ccc; cc++) {
                    if (d3)
                        assertTrue(c1[cc].equals3D(c2[cc]));
                    else
                        assertTrue(c1[cc].equals2D(c2[cc]));
                }
            } catch (Throwable t) {
                fail("Bogus : " + Arrays.asList(geom.getCoordinates()) + " : "
                        + Arrays.asList(fromShape.getCoordinates()));
            }
        }
        tmpFile.delete();
    }

    public void testGetCount() throws Exception {
        assertTrue(copyShapefiles(STREAM).canRead()); // The following test
                                                        // seems to fail in the
                                                        // URL point into the
                                                        // JAR file.
        ShapefileDataStore store = (ShapefileDataStore) new ShapefileDataStoreFactory()
                .createDataStore(TestData.url(TestCaseSupport.class, STREAM));
        int count = 0;
         FeatureReader<SimpleFeatureType, SimpleFeature> reader = store.getFeatureReader();
        try {
            while (reader.hasNext()) {
                count++;
                reader.next();
            }
            assertEquals(count, store.getCount(Query.ALL));
        } finally {
            reader.close();
        }
    }

    /**
     * Checks if feature reading optimizations still allow to execute the
     * queries or not
     * 
     * @throws Exception
     */
    public void testGetReaderOptimizations() throws Exception {
        URL url = TestData.url(STATE_POP);
        ShapefileDataStore s = new ShapefileDataStore(url);

        // attributes other than geometry can be ignored here
        Query query = new DefaultQuery(s.getSchema().getTypeName(),
                Filter.INCLUDE, new String[] { "the_geom" });
         FeatureReader<SimpleFeatureType, SimpleFeature> reader = s.getFeatureReader(s.getSchema().getTypeName(),
                query);
        assertEquals(1, reader.getFeatureType().getAttributeCount());
        assertEquals("the_geom", reader.getFeatureType().getAttribute(0)
                .getLocalName());

        // here too, the filter is using the geometry only
        GeometryFactory gc = new GeometryFactory();
        LinearRing ring = gc.createLinearRing(new Coordinate[] {
                new Coordinate(0, 0), new Coordinate(10, 0),
                new Coordinate(10, 10), new Coordinate(0, 10),
                new Coordinate(0, 0) });
        Polygon polygon = gc.createPolygon(ring, null);

        ReferencedEnvelope bounds = new ReferencedEnvelope(polygon
                .getEnvelopeInternal(), null);
        Filter gf = ff.bbox(ff.property("the_geom"), bounds);

        query = new DefaultQuery(s.getSchema().getTypeName(), gf,
                new String[] { "the_geom" });

        reader.close();
        reader = s.getFeatureReader(s.getSchema().getTypeName(), query);
        assertEquals(1, reader.getFeatureType().getAttributeCount());
        assertEquals("the_geom", reader.getFeatureType().getAttribute(0)
                .getLocalName());

        reader.close();

        // here not, we need state_name in the feature type, so open the dbf
        // file please
        Filter cf = ff
                .equals(ff.property("STATE_NAME"), ff.literal("Illinois"));
        query = new DefaultQuery(s.getSchema().getTypeName(), cf,
                new String[] { "the_geom" });
        reader = s.getFeatureReader(s.getSchema().getTypeName(), query);
        assertEquals(s.getSchema(), reader.getFeatureType());
        reader.close();
    }

    /**
     * This is useful to dump a UTF16 character to an UT16 escape sequence,
     * basically the only way to represent the chars we don't have on the
     * keyboard (such as chinese ones :))
     * 
     * @param c
     * @return
     */
    static public String charToHex(char c) {
        // Returns hex String representation of char c
        byte hi = (byte) (c >>> 8);
        byte lo = (byte) (c & 0xff);
        return byteToHex(hi) + byteToHex(lo);
    }

    static public String byteToHex(byte b) {
        // Returns hex String representation of byte b
        char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
        return new String(array);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -