GeoServer.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package com.onemap.spotoverlap.utils;
  2. import com.google.gson.Gson;
  3. import org.apache.http.client.methods.*;
  4. import org.apache.http.entity.StringEntity;
  5. import org.apache.http.impl.client.CloseableHttpClient;
  6. import org.apache.http.impl.client.HttpClients;
  7. import org.apache.http.util.EntityUtils;
  8. import org.geotools.data.FileDataStore;
  9. import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  10. import org.geotools.referencing.CRS;
  11. import org.opengis.referencing.crs.CoordinateReferenceSystem;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.nio.charset.StandardCharsets;
  15. import java.util.ArrayList;
  16. import java.util.Base64;
  17. import java.util.List;
  18. import java.util.Map;
  19. public class GeoServer {
  20. public static void main(String[] args) {
  21. try {
  22. List<String> styles = getStyles("http://127.0.0.1:28085/geoserver", "admin", "geoserver", "spot");
  23. System.out.println(styles);
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. /**
  29. * 获取geoserver工作空间下的所有样式
  30. *
  31. * @param geoserverurl
  32. * @param username
  33. * @param password
  34. * @param workspace
  35. * @return
  36. * @throws IOException
  37. */
  38. public static List<String> getStyles(String geoserverurl, String username, String password, String workspace) throws IOException {
  39. CloseableHttpClient client = HttpClients.createDefault();
  40. // TODO 设置 Basic Authentication 头
  41. String auth = username + ":" + password;
  42. String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
  43. HttpGet getRequest = new HttpGet(geoserverurl + "/rest/workspaces/" + workspace + "/styles");
  44. getRequest.setHeader("Authorization", "Basic " + encodedAuth);
  45. List<String> style = new ArrayList<>();
  46. try (CloseableHttpResponse response = client.execute(getRequest)) {
  47. String responseEntity = EntityUtils.toString(response.getEntity());
  48. System.out.println(responseEntity);
  49. Gson gson = new Gson();
  50. // 将 JSON 字符串转换为 Map
  51. Map<String, Object> responseMap = gson.fromJson(responseEntity, Map.class);
  52. Map<String, Object> styles = (Map<String, Object>) responseMap.get("styles");
  53. List<Map> stylelist = (List<Map>) styles.get("style");
  54. System.out.println(stylelist);
  55. for (int i = 0; i < stylelist.size(); i++) {
  56. Map<String, Object> cur = stylelist.get(i);
  57. style.add(workspace + ":" + cur.get("name"));
  58. }
  59. }
  60. return style;
  61. }
  62. /**
  63. * 将本地shp文件发布到geoserver并配置相应样式
  64. *
  65. * @param geoserverurl
  66. * @param username
  67. * @param password
  68. * @param workspace
  69. * @param filepath
  70. * @param stylename
  71. * @throws IOException
  72. */
  73. public static void publishShp(String geoserverurl, String username, String password, String workspace, String filepath, String stylename, String datasource, String charset) throws IOException {
  74. CloseableHttpClient client = HttpClients.createDefault();
  75. // TODO 设置 Basic Authentication 头
  76. String auth = username + ":" + password;
  77. String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
  78. // TODO 创建数据存储时的XML请求体,指定文件路径
  79. String xmlRequest = "<dataStore>" +
  80. "<name>" + datasource + "</name>" +
  81. "<connectionParameters>" +
  82. "<entry key=\"url\">file:" + filepath + "</entry>" +
  83. "<entry key=\"connector\">Shapefile</entry>" +
  84. "<entry key=\"charset\">" + charset + "</entry>" +
  85. "</connectionParameters>" +
  86. "</dataStore>";
  87. HttpPost postRequest = new HttpPost(geoserverurl + "/rest/workspaces/" + workspace + "/datastores");
  88. postRequest.setHeader("Authorization", "Basic " + encodedAuth);
  89. postRequest.setEntity(new StringEntity(xmlRequest));
  90. postRequest.setHeader("Content-Type", "application/xml");
  91. try (CloseableHttpResponse response = client.execute(postRequest)) {
  92. String responseEntity = EntityUtils.toString(response.getEntity());
  93. System.out.println(responseEntity);
  94. }
  95. // TODO 创建发布图层的请求体
  96. String publishRequest = "<featureType>" +
  97. "<title>" + datasource + "</title>" +
  98. "<name>" + datasource + "</name>" +
  99. "</featureType>";
  100. postRequest = new HttpPost(geoserverurl + "/rest/workspaces/" + workspace + "/datastores/" + datasource + "/featuretypes");
  101. postRequest.setEntity(new StringEntity(publishRequest));
  102. postRequest.setHeader("Authorization", "Basic " + encodedAuth);
  103. postRequest.setHeader("Content-Type", "application/xml");
  104. try (CloseableHttpResponse response = client.execute(postRequest)) {
  105. String responseEntity = EntityUtils.toString(response.getEntity());
  106. System.out.println(responseEntity);
  107. }
  108. // TODO 更新符号样式配置
  109. updateStyle(stylename, geoserverurl, username, password, workspace + ":" + datasource);
  110. //TODO wanger 是否发布为WMTS服务 调用切片
  111. client.close();
  112. }
  113. /**
  114. * 更新服务的样式配置
  115. *
  116. * @param stylename
  117. * @param geoserverurl
  118. * @param username
  119. * @param password
  120. * @param datasource
  121. */
  122. public static void updateStyle(String stylename, String geoserverurl, String username, String password, String datasource) {
  123. CloseableHttpClient client = HttpClients.createDefault();
  124. try {
  125. // TODO 创建图层样式的请求体
  126. String styleRequest = "<layer><defaultStyle>" +
  127. "<name>" + stylename + "</name>" +
  128. "</defaultStyle></layer>";
  129. String auth = username + ":" + password;
  130. String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
  131. HttpPut putRequest = new HttpPut(geoserverurl + "/rest/layers/" + datasource);
  132. putRequest.setEntity(new StringEntity(styleRequest));
  133. putRequest.setHeader("Authorization", "Basic " + encodedAuth);
  134. putRequest.setHeader("Content-Type", "application/xml");
  135. try (CloseableHttpResponse response = client.execute(putRequest)) {
  136. String responseEntity = EntityUtils.toString(response.getEntity());
  137. System.out.println(responseEntity);
  138. }
  139. client.close();
  140. } catch (Exception e) {
  141. try {
  142. client.close();
  143. } catch (IOException ioException) {
  144. ioException.printStackTrace();
  145. }
  146. e.printStackTrace();
  147. }
  148. }
  149. /**
  150. * 获取shp文件的epsg编码
  151. *
  152. * @param shpFilePath
  153. * @return
  154. */
  155. public static String getShpEPSG(String shpFilePath) {
  156. try {
  157. File shpFile = new File(shpFilePath);
  158. FileDataStore store = new ShapefileDataStoreFactory().createDataStore(shpFile.toURI().toURL());
  159. CoordinateReferenceSystem crs = store.getSchema().getCoordinateReferenceSystem();
  160. Integer srid = CRS.lookupEpsgCode(crs, false);
  161. return "EPSG:" + srid;
  162. } catch (Exception e) {
  163. e.printStackTrace();
  164. }
  165. return "EPSG:4326";
  166. }
  167. /**
  168. * 创建服务的切片配置
  169. *
  170. * @param geoserverurl
  171. * @param geoserverusername
  172. * @param geoserverpassword
  173. * @param geoserverworkspace
  174. * @param datasource
  175. * @param wmtsgridset
  176. * @param wmtsseedtype
  177. * @param wmtszoomstart
  178. * @param wmtszoomend
  179. */
  180. public static void caching_layer(String geoserverurl,
  181. String geoserverusername,
  182. String geoserverpassword,
  183. String geoserverworkspace,
  184. String datasource,
  185. String wmtsgridset,
  186. String wmtsseedtype,
  187. Integer wmtszoomstart,
  188. Integer wmtszoomend) {
  189. CloseableHttpClient client = HttpClients.createDefault();
  190. try {
  191. String layer_name = geoserverworkspace + ":" + datasource;
  192. String url = String.format("%s/gwc/rest/layers/%s", geoserverurl, layer_name);
  193. // TODO 创建图层样式的请求体
  194. String styleRequest = "<GeoServerLayer>" +
  195. " <enabled>true</enabled>" +
  196. " <inMemoryCached>true</inMemoryCached>" +
  197. " <name>" + layer_name + "</name>" +
  198. " <mimeFormats>" +
  199. " <string>image/png</string>" +
  200. " <string>image/jpeg</string>" +
  201. " </mimeFormats>" +
  202. " <gridSubsets>" +
  203. " <gridSubset>" +
  204. " <gridSetName>" + wmtsgridset + "</gridSetName>" +
  205. " <zoomStart>" + wmtszoomstart + "</zoomStart>" +
  206. " <zoomStop>" + wmtszoomend + "</zoomStop>" +
  207. " <minCachedLevel>" + wmtszoomstart + "</minCachedLevel>" +
  208. " <maxCachedLevel>" + wmtszoomend + "</maxCachedLevel>" +
  209. " </gridSubset>" +
  210. " </gridSubsets>" +
  211. " <metaWidthHeight>" +
  212. " <int>4</int>" +
  213. " <int>4</int>" +
  214. " </metaWidthHeight>" +
  215. " <expireCache>0</expireCache>" +
  216. " <expireClients>0</expireClients>" +
  217. " <parameterFilters>" +
  218. " </parameterFilters>" +
  219. " <gutter>0</gutter>" +
  220. " <autoCacheStyles>true</autoCacheStyles>" +
  221. " </GeoServerLayer>";
  222. String auth = geoserverusername + ":" + geoserverpassword;
  223. String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
  224. HttpPost putRequest = new HttpPost(url);
  225. putRequest.setEntity(new StringEntity(styleRequest));
  226. putRequest.setHeader("Authorization", "Basic " + encodedAuth);
  227. putRequest.setHeader("Content-Type", "application/xml");
  228. try (CloseableHttpResponse response = client.execute(putRequest)) {
  229. String responseEntity = EntityUtils.toString(response.getEntity());
  230. System.out.println(responseEntity);
  231. seed_caching_layer(geoserverurl, geoserverusername, geoserverpassword, geoserverworkspace, datasource, wmtsgridset, wmtsseedtype, wmtszoomstart, wmtszoomend);
  232. }
  233. client.close();
  234. } catch (Exception e) {
  235. try {
  236. client.close();
  237. } catch (IOException ioException) {
  238. ioException.printStackTrace();
  239. }
  240. e.printStackTrace();
  241. }
  242. }
  243. /**
  244. * 发送切片指令 seed
  245. *
  246. * @param geoserverurl
  247. * @param geoserverusername
  248. * @param geoserverpassword
  249. * @param geoserverworkspace
  250. * @param datasource
  251. * @param wmtsgridset
  252. * @param wmtsseedtype
  253. * @param wmtszoomstart
  254. * @param wmtszoomend
  255. */
  256. private static void seed_caching_layer(String geoserverurl,
  257. String geoserverusername,
  258. String geoserverpassword,
  259. String geoserverworkspace,
  260. String datasource,
  261. String wmtsgridset,
  262. String wmtsseedtype,
  263. Integer wmtszoomstart,
  264. Integer wmtszoomend) {
  265. CloseableHttpClient client = HttpClients.createDefault();
  266. try {
  267. String layer_name = geoserverworkspace + ":" + datasource;
  268. String url = String.format("%s/gwc/rest/seed/%s?threadCount=4&" +
  269. "type=%s" +
  270. "&gridSetId=%s" +
  271. "&tileFormat=image/png" +
  272. "&zoomStart=%s" +
  273. "&zoomStop=%s" +
  274. "&parameter_STYLES=" +
  275. "&minX=&minY=&maxX=&maxY=" +
  276. "&tileFailureRetryCount=-1" +
  277. "&tileFailureRetryWaitTime=100" +
  278. "&totalFailuresBeforeAborting=1000", geoserverurl, layer_name, wmtsseedtype, wmtsgridset, wmtszoomstart, wmtszoomend);
  279. String auth = geoserverusername + ":" + geoserverpassword;
  280. String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
  281. HttpPost putRequest = new HttpPost(url);
  282. putRequest.setHeader("Authorization", "Basic " + encodedAuth);
  283. putRequest.setHeader("Content-Type", "application/json");
  284. try (CloseableHttpResponse response = client.execute(putRequest)) {
  285. String responseEntity = EntityUtils.toString(response.getEntity());
  286. System.out.println(responseEntity);
  287. }
  288. client.close();
  289. } catch (Exception e) {
  290. try {
  291. client.close();
  292. } catch (IOException ioException) {
  293. ioException.printStackTrace();
  294. }
  295. e.printStackTrace();
  296. }
  297. }
  298. /**
  299. * 删除指定数据存储
  300. *
  301. * @param geoserverurl
  302. * @param geoserverusername
  303. * @param geoserverpassword
  304. * @param geoserverworkspace
  305. * @param datasource
  306. */
  307. public static void delete_datasource(String geoserverurl,
  308. String geoserverusername,
  309. String geoserverpassword,
  310. String geoserverworkspace,
  311. String datasource) {
  312. CloseableHttpClient client = HttpClients.createDefault();
  313. try {
  314. String url = String.format("%s/rest/workspaces/%s/datastores/%s?recurse=true", geoserverurl, geoserverworkspace, datasource);
  315. String auth = geoserverusername + ":" + geoserverpassword;
  316. String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
  317. HttpDelete putRequest = new HttpDelete(url);
  318. putRequest.setHeader("Authorization", "Basic " + encodedAuth);
  319. try (CloseableHttpResponse response = client.execute(putRequest)) {
  320. String responseEntity = EntityUtils.toString(response.getEntity());
  321. System.out.println(responseEntity);
  322. }
  323. client.close();
  324. } catch (Exception e) {
  325. try {
  326. client.close();
  327. } catch (IOException ioException) {
  328. ioException.printStackTrace();
  329. }
  330. e.printStackTrace();
  331. }
  332. }
  333. }