7c93556c9475b43663b557357eb1e5304d3310d9.svn-base 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package org.jeecg.modules.demo.onemap.utils;
  2. import org.apache.commons.io.Charsets;
  3. import org.apache.commons.io.FileUtils;
  4. import org.geotools.data.DataStore;
  5. import org.geotools.data.DataStoreFinder;
  6. import org.geotools.data.FeatureSource;
  7. import org.geotools.data.FeatureWriter;
  8. import org.geotools.data.postgis.PostgisNGDataStoreFactory;
  9. import org.geotools.data.shapefile.ShapefileDataStore;
  10. import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  11. import org.geotools.data.simple.SimpleFeatureIterator;
  12. import org.geotools.data.simple.SimpleFeatureSource;
  13. import org.geotools.data.store.ContentFeatureCollection;
  14. import org.geotools.data.store.ContentFeatureSource;
  15. import org.geotools.feature.FeatureCollection;
  16. import org.geotools.feature.FeatureIterator;
  17. import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
  18. import org.geotools.geojson.feature.FeatureJSON;
  19. import org.geotools.geojson.geom.GeometryJSON;
  20. import org.geotools.referencing.CRS;
  21. import org.geotools.referencing.crs.DefaultGeographicCRS;
  22. import org.opengis.feature.Feature;
  23. import org.opengis.feature.Property;
  24. import org.opengis.feature.simple.SimpleFeature;
  25. import org.opengis.feature.simple.SimpleFeatureType;
  26. import org.opengis.referencing.crs.CoordinateReferenceSystem;
  27. import java.io.*;
  28. import java.nio.charset.Charset;
  29. import java.util.*;
  30. import static org.geotools.data.Transaction.AUTO_COMMIT;
  31. import lombok.extern.slf4j.Slf4j;
  32. /**
  33. * @author wangkang
  34. * @email iwuang@qq.com
  35. * @date 2019/1/24 16:27
  36. */
  37. @Slf4j
  38. public class Geotools {
  39. private static DataStore postgisDatasore;
  40. /**
  41. * @param postgisDatasore 静态PGDatastore获取默认,实例化PGDatastore指定自定义
  42. */
  43. public Geotools(DataStore postgisDatasore) {
  44. if (postgisDatasore == null) {
  45. postgisDatasore = PGDatastore.getDefeaultDatastore();
  46. }
  47. this.postgisDatasore = postgisDatasore;
  48. }
  49. public Geotools() {
  50. postgisDatasore = PGDatastore.getDefeaultDatastore();
  51. }
  52. /**
  53. * 读取文本文件
  54. *
  55. * @param path
  56. * @return
  57. */
  58. public static String readTxtFile(String path) {
  59. StringBuilder stringBuilder = new StringBuilder();
  60. InputStreamReader inputStreamReader = null;
  61. FileInputStream inputStream = null;
  62. try {
  63. inputStream = new FileInputStream(new File(path));
  64. inputStreamReader = new InputStreamReader(inputStream);
  65. BufferedReader br = new BufferedReader(inputStreamReader);
  66. String s = null;
  67. while ((s = br.readLine()) != null) {
  68. stringBuilder.append(s);
  69. }
  70. } catch (Exception e) {
  71. log.error(e.getMessage(), e);
  72. } finally {
  73. if (inputStream != null) {
  74. try {
  75. inputStream.close();
  76. } catch (IOException e) {
  77. log.error(e.getMessage(), e);
  78. }
  79. }
  80. if (inputStreamReader != null) {
  81. try {
  82. inputStreamReader.close();
  83. } catch (IOException e) {
  84. log.error(e.getMessage(), e);
  85. }
  86. }
  87. }
  88. return stringBuilder.toString();
  89. }
  90. /**
  91. * 解析shp坐标系
  92. *
  93. * @param prjFilePath
  94. * @return
  95. */
  96. public static String getShpPrjWkt(String prjFilePath) {
  97. String prjWkt = "";
  98. try {
  99. if (Utility.isEmpty(prjFilePath)) {
  100. log.error("解析shp坐标系参数无效");
  101. return prjWkt;
  102. }
  103. prjWkt = readTxtFile(prjFilePath);
  104. } catch (Exception e) {
  105. log.error("解析shp坐标系文件失败", e);
  106. }
  107. return prjWkt;
  108. }
  109. /**
  110. * 解析shp图形为wkt
  111. *
  112. * @param shpPath
  113. * @return
  114. */
  115. public static String shp2wkt(String shpPath) {
  116. String shpWkt = "";
  117. try {
  118. if (Utility.isEmpty(shpPath)) {
  119. log.error("解析shp为wkt参数无效");
  120. return shpWkt;
  121. }
  122. ShapefileDataStore shapefileDataStore = new ShapefileDataStore(new File(shpPath).toURI().toURL());
  123. shapefileDataStore.setCharset(Charset.forName("Utf-8"));
  124. FeatureCollection featureCollection = shapefileDataStore.getFeatureSource().getFeatures();
  125. FeatureIterator iterator = featureCollection.features();
  126. while (iterator.hasNext()) {
  127. Feature feature = iterator.next();
  128. Collection<Property> properties = feature.getProperties();
  129. Iterator<Property> propertyIterator = properties.iterator();
  130. while (propertyIterator.hasNext()) {
  131. Property property = propertyIterator.next();
  132. if (property.getName().toString().equals("the_geom")) {
  133. shpWkt = property.getValue().toString();
  134. System.out.println("@wkt:" + shpWkt);
  135. break;
  136. }
  137. }
  138. }
  139. iterator.close();
  140. } catch (Exception e) {
  141. log.error("解析shp为wkt失败", e);
  142. }
  143. return shpWkt;
  144. }
  145. /**
  146. * 读取shp文件属性
  147. *
  148. * @param shapePath
  149. * @return
  150. */
  151. public static List<Map<String, Object>> readShpFile(String shapePath) {
  152. List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  153. ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
  154. ShapefileDataStore dataStore = null;
  155. try {
  156. dataStore = (ShapefileDataStore) factory.createDataStore(new File(shapePath).toURI().toURL());
  157. if (dataStore != null) {
  158. // dataStore.setCharset(Charset.forName("UTF-8"));
  159. dataStore.setCharset(ShpCharset.GBK);
  160. }
  161. SimpleFeatureSource featureSource = dataStore.getFeatureSource();
  162. SimpleFeatureIterator itertor = featureSource.getFeatures().features();
  163. while (itertor.hasNext()) {
  164. SimpleFeature feature = itertor.next();
  165. Iterator<Property> itprop = feature.getProperties().iterator();
  166. Map<String, Object> map = new HashMap<String, Object>();
  167. while (itprop.hasNext()) {
  168. Property prop = itprop.next();
  169. map.put(String.valueOf(prop.getName()), String.valueOf(prop.getValue()));
  170. }
  171. list.add(map);
  172. }
  173. itertor.close();
  174. } catch (Exception e) {
  175. log.error("解析shp异常:", e.getMessage());
  176. } finally {
  177. if(dataStore != null) {
  178. dataStore.dispose();
  179. }
  180. }
  181. return list;
  182. }
  183. /**
  184. * 通用,要素集写入postgis
  185. *
  186. * @param featureCollection
  187. * @param pgtableName postgis创建的数据表
  188. * @return
  189. */
  190. public static boolean write2pg(String id, FeatureCollection featureCollection, String pgtableName) {
  191. boolean result = false;
  192. try {
  193. if (Utility.isEmpty(featureCollection) || Utility.isEmpty(pgtableName)) {
  194. log.error("参数无效");
  195. return result;
  196. }
  197. SimpleFeatureType simpleFeatureType = (SimpleFeatureType) featureCollection.getSchema();
  198. // SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  199. // typeBuilder.init(simpleFeatureType);
  200. // typeBuilder.setName(pgtableName);
  201. // SimpleFeatureType newtype = typeBuilder.buildFeatureType();
  202. // postgisDatasore.createSchema(newtype);
  203. System.out.println("simpleFeatureType:" + simpleFeatureType);
  204. FeatureIterator iterator = featureCollection.features();
  205. FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = postgisDatasore.getFeatureWriterAppend(pgtableName, AUTO_COMMIT);
  206. while (iterator.hasNext()) {
  207. Feature feature = iterator.next();
  208. SimpleFeature simpleFeature = featureWriter.next();
  209. Collection<Property> properties = feature.getProperties();
  210. Iterator<Property> propertyIterator = properties.iterator();
  211. while (propertyIterator.hasNext()) {
  212. Property property = propertyIterator.next();
  213. if (property.getName().toString().equals("the_geom")) {
  214. simpleFeature.setAttribute("geom", property.getValue());
  215. System.out.println(property.getValue());
  216. } else if (property.getName().toString().equals("Id")) {
  217. continue;
  218. // simpleFeature.setAttribute("id", property.getValue());
  219. } else
  220. // continue;
  221. simpleFeature.setAttribute(property.getName().toString(), property.getValue());
  222. }
  223. System.out.println(simpleFeature);
  224. // simpleFeature.setAttribute("id", id);
  225. System.out.println(featureWriter);
  226. featureWriter.write();
  227. // simpleFeature.write();
  228. }
  229. iterator.close();
  230. featureWriter.close();
  231. } catch (Exception e) {
  232. log.error("失败", e);
  233. }
  234. return false;
  235. }
  236. /**
  237. * featureCollection写入到shp的datastore
  238. *
  239. * @param featureCollection
  240. * @param shpDataStore
  241. * @param geomFieldName featureCollectio中的矢量字段,postgis可以修改使用不同的表名,默认为geom
  242. * @return
  243. */
  244. public static boolean write2shp(FeatureCollection featureCollection, ShapefileDataStore shpDataStore, String geomFieldName) {
  245. boolean result = false;
  246. if (Utility.isEmpty(geomFieldName)) {
  247. geomFieldName = featureCollection.getSchema().getGeometryDescriptor().getType().getName().toString();
  248. }
  249. try {
  250. FeatureIterator<SimpleFeature> iterator = featureCollection.features();
  251. //shp文件存储写入
  252. FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = shpDataStore.getFeatureWriter(shpDataStore.getTypeNames()[0], AUTO_COMMIT);
  253. while (iterator.hasNext()) {
  254. Feature feature = iterator.next();
  255. SimpleFeature simpleFeature = featureWriter.next();
  256. Collection<Property> properties = feature.getProperties();
  257. Iterator<Property> propertyIterator = properties.iterator();
  258. while (propertyIterator.hasNext()) {
  259. Property property = propertyIterator.next();
  260. if (property.getName().toString().equalsIgnoreCase(geomFieldName)) {
  261. simpleFeature.setAttribute("the_geom", property.getValue());
  262. } else {
  263. simpleFeature.setAttribute(property.getName().toString(), property.getValue());
  264. }
  265. }
  266. featureWriter.write();
  267. }
  268. iterator.close();
  269. featureWriter.close();
  270. shpDataStore.dispose();
  271. } catch (Exception e) {
  272. log.error("失败", e);
  273. }
  274. return false;
  275. }
  276. /**
  277. * 方法重载,默认使用UTF-8的Shp文件
  278. *
  279. * @param geojsonPath
  280. * @param shpfilepath
  281. * @return
  282. */
  283. public boolean geojson2shp(String geojsonPath, String shpfilepath) {
  284. return geojson2shp(geojsonPath, shpfilepath, ShpCharset.UTF_8);
  285. }
  286. /**
  287. * Geojson转成shpfile文件
  288. *
  289. * @param geojsonPath
  290. * @param shpfilepath
  291. * @return
  292. */
  293. public boolean geojson2shp(String geojsonPath, String shpfilepath, Charset shpChart) {
  294. boolean result = false;
  295. try {
  296. Utility.valiFileForRead(geojsonPath);
  297. FeatureJSON featureJSON = new FeatureJSON();
  298. featureJSON.setEncodeNullValues(true);
  299. FeatureCollection featureCollection = featureJSON.readFeatureCollection(new InputStreamReader(new FileInputStream(geojsonPath), "UTF-8"));
  300. File file = new File(shpfilepath);
  301. Map<String, Serializable> params = new HashMap<String, Serializable>();
  302. params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
  303. ShapefileDataStore shpDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
  304. //postgis获取的Featuretype获取坐标系代码
  305. SimpleFeatureType pgfeaturetype = (SimpleFeatureType) featureCollection.getSchema();
  306. SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  307. typeBuilder.init(pgfeaturetype);
  308. typeBuilder.setCRS(DefaultGeographicCRS.WGS84);
  309. pgfeaturetype = typeBuilder.buildFeatureType();
  310. //设置成utf-8编码
  311. shpDataStore.setCharset(shpChart);
  312. shpDataStore.createSchema(pgfeaturetype);
  313. write2shp(featureCollection, shpDataStore, "");
  314. result = true;
  315. } catch (Exception e) {
  316. log.error(e.getMessage(), e);
  317. }
  318. return result;
  319. }
  320. /**
  321. * geojson文件写入到postgis里
  322. *
  323. * @param geojsonPath
  324. * @param pgtableName
  325. * @return
  326. */
  327. public boolean geojson2pgtable(String id, String geojsonPath, String pgtableName) {
  328. boolean result = false;
  329. try {
  330. if (Utility.isEmpty(geojsonPath) || Utility.isEmpty(pgtableName)) {
  331. return result;
  332. }
  333. FeatureJSON featureJSON = new FeatureJSON();
  334. FeatureCollection featureCollection = featureJSON.readFeatureCollection(new FileInputStream(geojsonPath));
  335. write2pg(id, featureCollection, pgtableName);
  336. result = true;
  337. } catch (Exception e) {
  338. log.error(e.getMessage(), e);
  339. }
  340. return result;
  341. }
  342. /**
  343. * 重载方法,默认UTF-8编码SHP文件
  344. *
  345. * @param shpPath
  346. * @param geojsonPath
  347. * @return
  348. */
  349. public boolean shp2geojson(String shpPath, String geojsonPath) {
  350. return shp2geojson(shpPath, geojsonPath, ShpCharset.UTF_8);
  351. }
  352. /**
  353. * shp转成geojson,保留15位小数
  354. *
  355. * @param shpPath shp的路径
  356. * @param geojsonPath geojson的路径
  357. * @return
  358. */
  359. public boolean shp2geojson(String shpPath, String geojsonPath, Charset shpCharset) {
  360. boolean result = false;
  361. try {
  362. if (!Utility.valiFileForRead(shpPath) || Utility.isEmpty(geojsonPath)) {
  363. return result;
  364. }
  365. ShapefileDataStore shapefileDataStore = new ShapefileDataStore(new File(shpPath).toURI().toURL());
  366. shapefileDataStore.setCharset(shpCharset);
  367. ContentFeatureSource featureSource = shapefileDataStore.getFeatureSource();
  368. ContentFeatureCollection contentFeatureCollection = featureSource.getFeatures();
  369. FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(15));
  370. Utility.valiFileForWrite(geojsonPath);
  371. featureJSON.writeFeatureCollection(contentFeatureCollection, new File(geojsonPath));
  372. shapefileDataStore.dispose();
  373. result = true;
  374. } catch (Exception e) {
  375. log.error(e.getMessage(), e);
  376. }
  377. return result;
  378. }
  379. public boolean shp2pgtable(String id, String shpPath, String pgtableName) {
  380. return shp2pgtable(id, shpPath, pgtableName, ShpCharset.GBK);
  381. }
  382. /**
  383. * shpfile文件导入到postgis中
  384. *
  385. * @param shpPath
  386. * @param pgtableName
  387. * @return
  388. */
  389. public boolean shp2pgtable(String id, String shpPath, String pgtableName, Charset shpCharset) {
  390. boolean result = false;
  391. try {
  392. ShapefileDataStore shapefileDataStore = new ShapefileDataStore(new File(shpPath).toURI().toURL());
  393. shapefileDataStore.setCharset(shpCharset);
  394. FeatureCollection featureCollection = shapefileDataStore.getFeatureSource().getFeatures();
  395. write2pg(id, featureCollection, pgtableName);
  396. result = true;
  397. } catch (Exception e) {
  398. log.error(e.getMessage(), e);
  399. }
  400. return result;
  401. }
  402. /**
  403. * postgis数据表导出到成shpfile
  404. *
  405. * @param pgtableName
  406. * @param shpPath
  407. * @param geomField postgis里的字段
  408. * @return
  409. */
  410. public boolean pgtable2shp(String pgtableName, String shpPath, String geomField) {
  411. boolean result = false;
  412. try {
  413. FeatureSource featureSource = postgisDatasore.getFeatureSource(pgtableName);
  414. // 初始化 ShapefileDataStore
  415. File file = new File(shpPath);
  416. Map<String, Serializable> params = new HashMap<String, Serializable>();
  417. params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
  418. ShapefileDataStore shpDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
  419. //postgis获取的Featuretype获取坐标系代码
  420. SimpleFeatureType pgfeaturetype = ((SimpleFeatureSource) featureSource).getSchema();
  421. String srid = pgfeaturetype.getGeometryDescriptor().getUserData().get("nativeSRID").toString();
  422. SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  423. typeBuilder.init(pgfeaturetype);
  424. if (!srid.equals("0")) {
  425. CoordinateReferenceSystem crs = CRS.decode("EPSG:" + srid, true);
  426. typeBuilder.setCRS(crs);
  427. }
  428. pgfeaturetype = typeBuilder.buildFeatureType();
  429. //设置成utf-8编码
  430. shpDataStore.setCharset(Charset.forName("UTF-8"));
  431. shpDataStore.createSchema(pgfeaturetype);
  432. write2shp(featureSource.getFeatures(), shpDataStore, geomField);
  433. result = true;
  434. } catch (Exception e) {
  435. log.error(e.getMessage(), e);
  436. }
  437. return result;
  438. }
  439. /**
  440. * postgis指定的数据表转成geojson文件保留15位小数
  441. *
  442. * @param pgtableName 表名
  443. * @param geojsonpath geojson存放位置
  444. * @return
  445. */
  446. public boolean pgtable2geojson(String pgtableName, String geojsonpath) {
  447. boolean result = false;
  448. try {
  449. FeatureSource featureSource = postgisDatasore.getFeatureSource(pgtableName);
  450. FeatureCollection featureCollection = featureSource.getFeatures();
  451. FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(15));
  452. featureJSON.setEncodeNullValues(true);
  453. String s = featureJSON.toString(featureCollection);
  454. FileUtils.writeStringToFile(new File(geojsonpath), s, Charsets.toCharset("utf-8"), false);
  455. result = true;
  456. } catch (Exception e) {
  457. log.error(e.getMessage(), e);
  458. }
  459. return result;
  460. }
  461. public boolean deletePgtable(String pgtableName) {
  462. boolean result = false;
  463. try {
  464. postgisDatasore.removeSchema(pgtableName);
  465. result = true;
  466. } catch (Exception e) {
  467. log.error(e.getMessage(), e);
  468. }
  469. return result;
  470. }
  471. /*
  472. // 测试调试专用,成功清除所有的sw开头的表(用来存储矢量数据的表)
  473. public boolean clearSWTable() throws Exception {
  474. postgisDatasore.removeSchema();
  475. //relkind char r = 普通表,i = 索 引, S = 序列,v = 视 图, m = 物化视图, c = 组合类型,t = TOAST表, f = 外部 表
  476. String strtables = " select string_agg(relname ,\',\') from pg_class where relname like \'%sw_%\' and relkind=\'r\' ";
  477. List list = postgisDatasore.getSessionFactory().getCurrentSession().createQuery(strtables).list();
  478. list.get(0).toString();
  479. Integer integer = 0;
  480. if (list.size() > 0) {
  481. integer = temp.getSessionFactory().getCurrentSession().createQuery("drop table " + strtables).executeUpdate();
  482. }
  483. // 与表有关联的其他序列自动删除
  484. String sequence = " select string_agg(relname ,\',\') from pg_class where relname like \'%sw_%\' and relkind=\'S\' and relname!=\'txsw_seq\'";
  485. resultSet = st.executeQuery(sequence);
  486. while (resultSet.next()) {
  487. sequence = resultSet.getString(1);
  488. }
  489. System.out.println("所有非txsw_seq的序列:" + sequence);
  490. i = st.executeUpdate("drop SEQUENCE " + strtables);
  491. return integer == 0 ? true : false;
  492. }
  493. */
  494. public static boolean testCreatFeature(String featurePath) {
  495. boolean result = false;
  496. try {
  497. result = true;
  498. } catch (Exception e) {
  499. log.error(e.getMessage(), e);
  500. }
  501. return result;
  502. }
  503. }