GeoServer-Manager GitHub 网址

https://github.com/geosolutions-it/geoserver-manager/wiki

GeoServer-Manager 官方示例 GitHub 网址

https://github.com/geosolutions-it/geoserver-manager/wiki/Various-Examples

在IDEA创建一个Maven工程

依赖如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>

  <artifactId>geoServer-manager</artifactId>

  <version>2.0</version>

  <build>

    <plugins>

      <plugin>

        <groupId>org.apache.maven.plugins</groupId>

        <artifactId>maven-compiler-plugin</artifactId>

        <configuration>

          <source>8</source>

          <target>8</target>

        </configuration>

      </plugin>

    </plugins>

  </build>

  <properties>

    <slf4j.version>1.7.25</slf4j.version>

  </properties>

  <repositories>

    <repository>

      <id>GeoSolutions</id>

      <url>http://maven.geo-solutions.it/</url>

    </repository>

  </repositories>

  <dependencies>

    <dependency>

      <groupId>it.geosolutions</groupId>

      <artifactId>geoserver-manager</artifactId>

      <version>1.7.0</version>

    </dependency>

    <dependency>

      <groupId>org.slf4j</groupId>

      <artifactId>slf4j-log4j12</artifactId>

      <version>${slf4j.version}</version>

    </dependency>

    <dependency>

      <groupId>org.slf4j</groupId>

      <artifactId>slf4j-api</artifactId>

      <version>${slf4j.version}</version>

    </dependency>

    <dependency>

      <groupId>org.slf4j</groupId>

      <artifactId>jcl-over-slf4j</artifactId>

      <version>${slf4j.version}</version>

    </dependency>

  </dependencies>

</project>

注意:在这里务必指定下载源:

<repositories>

    <repository>

        <id>GeoSolutions</id>

        <url>http://maven.geo-solutions.it/</url>

    </repository>

</repositories>

自定义类

ImproveGeoServerPublisher

在发布Style服务时,由于要自己提交curl 请求,为了获取到用户名密码等,通过继承 GeoServerRESTPublisher 构建了一个增强 GeoServerRESTPublisher —— ImproveGeoServerPublisher。

package com.myz.geoManager.Improve;

import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;

public class ImproveGeoServerPublisher extends GeoServerRESTPublisher {

  private String restURL;

  private String username;

  private String password;

  public ImproveGeoServerPublisher(String restURL, String username, String password) {

    super(restURL, username, password);

    this.restURL = restURL;

    this.username = username;

    this.password = password;

  }

  public String getRestURL() {

    return restURL;

  }

  public void setRestURL(String restURL) {

    this.restURL = restURL;

  }

  public String getUsername() {

    return username;

  }

  public void setUsername(String username) {

    this.username = username;

  }

  public String getPassword() {

    return password;

  }

  public void setPassword(String password) {

    this.password = password;

  }

}

ImprovePostGISDatastore

PostGIS 数据源加强类,帮助构建PostGIS数据源

package com.myz.geoManager.Improve;

import it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder;

public class ImprovePostGISDatastore {

  private String dataStoreName;

  private String host;

  private int port = 5432;

  private String user = "postgres";

  private String password;

  private String database;

  public ImprovePostGISDatastore(String dataStoreName, String host, String password, String database) {

    this.dataStoreName = dataStoreName;

    this.host = host;

    this.password = password;

    this.database = database;

  }

  public ImprovePostGISDatastore(String dataStoreName, String host, int port, String user, String password, String database) {

    this.dataStoreName = dataStoreName;

    this.host = host;

    this.port = port;

    this.user = user;

    this.password = password;

    this.database = database;

  }

  /**

   * 构建 GSPostGISDatastoreEncoder 对象,并将其返回

   * @return GSPostGISDatastoreEncoder 对象

   */

  public GSPostGISDatastoreEncoder builder () {

    GSPostGISDatastoreEncoder build = new GSPostGISDatastoreEncoder(dataStoreName);

    build.setHost(host);

    build.setPort(port);

    build.setUser(user);

    build.setPassword(password);

    build.setDatabase(database);

    build.setExposePrimaryKeys(true);

    return build;

  }

}

ComTools

公共工具类,用来获取文件内容、提交 curl请求等

package com.myz.geoManager.utils;

import java.io.*;

public class ComTools {

  /**

   * 读取文件内容

   *

   * @param file File对象

   * @return 返回文件内容

   * @throws IOException IO 错误

   */

  public static String readFile(File file) throws IOException {

    BufferedReader in = new BufferedReader(new FileReader(file));

    String str;

    StringBuilder stringBuffer = new StringBuilder();

    while ((str = in.readLine()) != null) {

      stringBuffer.append(str);

    }

    return stringBuffer.toString();

  }

  /**

   * 提供curl post 请求方法

   * @param cmds curl 命令行 String 数组

   * @return 执行curl命令返回值 JSON

   * @throws IOException 获取输入输出流不存在

   */

  public static String curlPost(String[] cmds) throws IOException {

    ProcessBuilder processBuilder = new ProcessBuilder(cmds);

    Process start = processBuilder.start();

    InputStream inputStream = start.getInputStream();

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder stringBuilder = new StringBuilder();

    bufferedReader.lines().forEach(stringBuilder::append);

    return stringBuilder.toString();

  }

  /**

   * 提供curl put 请求方法

   * @param cmds curl 命令行 String 数组

   * @return 执行curl命令返回值 JSON

   * @throws IOException 获取输入输出流不存在

   */

  public static String curlPUT(String[] cmds) throws IOException {

    ProcessBuilder processBuilder = new ProcessBuilder(cmds);

    Process start = processBuilder.start();

    InputStream inputStream = start.getInputStream();

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder stringBuilder = new StringBuilder();

    bufferedReader.lines().forEach(stringBuilder::append);

    return stringBuilder.toString();

  }

}

常量类(http请求方式、accept、Content-type)

package com.myz.geoManager.constant;

public class HttpConstant {

  /**

   * HTTP 方法为 GET

   */

  public static final String GET = "GET";

  /**

   * HTTP 方法为 POST

   */

  public static final String POST = "POST";

  /**

   * HTTP 方法为 PUT

   */

  public static final String PUT = "PUT";

  /**

   * HTTP 方法为 DELETE

   */

  public static final String DELETE = "DELETE";

}

package com.myz.geoManager.constant;

public class AcceptType {

  /**

   * 返回格式为 XML

   */

  public static final String XML = "accept: application/xml";

  /**

   * 返回格式为 JSON

   */

  public static final String JSON = "accept: application/json";

}

package com.myz.geoManager.constant;

public class ContentType {

  /**

   * 提交格式为 XML

   */

  public static final String XML = "Content-type: application/xml";

  /**

   * 提交格式为 JSON

   */

  public static final String JSON = "Content-type: application/json";

  /**

   * 提交格式为 HTML

   */

  public static final String HTML = "Content-type: application/html";

  /**

   * 提交式为 SLD

   */

  public static final String SLD = "Content-type: application/vnd.ogc.sld+xml;charset=utf-8";

  /**

   * 提交式为 ZIP

   */

  public static final String ZIP = "Content-type: application/zip";

}

创建错误类

由于错误类比较多,我直接合并在一起写啦

error包下

public class ExistedException extends Exception {

  public ExistedException(String message) {

    super(message + "已存在");

  }

}

/*

* 一般错误信息

* */

public class ErrorException extends Exception{

  public ErrorException(String message) {

    super(message);

  }

}

error.ogc包下

/*

* 栅格数据源不存在

* */

public class CoverageStoreNotFoundException extends Exception {

  public CoverageStoreNotFoundException(String coverageStoreName) {

    super(String.format("矢量数据源:%s不存在", coverageStoreName));

  }

}

/**

 * 矢量数据源不存在错误

 */

public class DataSourceNotFoundException extends Exception{

  public DataSourceNotFoundException(String datasourceName) {

    super(String.format("栅格数据源:%s不存在", datasourceName));

  }

}

/*

* 图层组不存在

* */

public class LayerGroupNotFoundException extends Exception{

  public LayerGroupNotFoundException(String layerGroupName) {

    super(String.format("图层组:%s不存在", layerGroupName));

  }

}

/*

* 图层不存在

* */

public class LayerNotFoundException extends Exception{

  public LayerNotFoundException(String coverageStoreName) {

    super(String.format("图层:%s不存在", coverageStoreName));

  }

}

/*

* 样式服务不存在

* */

public class StyleServiceNotFoundException extends Exception{

  public StyleServiceNotFoundException(String styleName) {

    super(String.format("样式服务:%s不存在", styleName));

  }

}

/*

* 工作空间不存在

* */

public class WorkSpaceNotFoundException extends Exception{

  public WorkSpaceNotFoundException(String workspaceName) {

    super(String.format("工作空间:%s不存在", workspaceName));

  }

}

创建一个GeoServerManager类

首先定义全局变量:

//  加强geoserver publisher

private final ImproveGeoServerPublisher geoServerRESTPublisher;

//  geoserver REST 管理者

private final GeoServerRESTManager geoServerRESTManager;

//  geoserver REST 阅读者

private final GeoServerReader reader;

在这里我直接下载了GeoServer的 war包,扔在Tomcat的webapps下。下载连接如下:

https://download.csdn.net/download/qq_41731732/130544

也可以到GeoServer 官网下载最新的GeoServer

http://geoserver.org/

定义GeoServerManager构造函数

/**

   * 直接提供 geoserver 地址,用户名,密码为默认的: admin/geoserver

   *

   * @param restUrl geoserver 服务地址

   * @throws MalformedURLException 服务地址错误

   */

public GeoServerManager(String restUrl) throws MalformedURLException {

    this(restUrl, "admin", "geoserver");

}

/**

   * 提供 geoserver 服务地址和用户名、密码

   *

   * @param restUrl  geoserver 服务地址

   * @param userName geoserver登录用户名

   * @param password geoserver 密码

   * @throws MalformedURLException 服务地址或登录失败错误

   */

public GeoServerManager(String restUrl, String userName, String password) throws MalformedURLException {

    geoServerRESTPublisher = new ImproveGeoServerPublisher(restUrl, userName, password);

    geoServerRESTManager = new GeoServerRESTManager(new URL(restUrl), userName, password);

    reader = new GeoServerReader(restUrl, userName, password);

}

工作空间部分

/**

   * 创建工作空间

   *

   * @param workspaceName 工作空间名称

   * @return 是否创建成功

   * @throws ExistedException 工作空间已存在

   */

public Boolean createWorkspace(String workspaceName) throws ExistedException {

    if (reader.existsWorkspace(workspaceName)) {

        throw new ExistedException("工作空间;" + workspaceName);

    }

    return geoServerRESTPublisher.createWorkspace(workspaceName);

}

/**

   * 通过名称 和 URI 创建工作空间

   *

   * @param workspaceName 工作空间名称

   * @param uri           URI名称

   * @return 是否创建成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws URISyntaxException URI 格式或链接错误

   */

public Boolean createWorkspace(String workspaceName, String uri) throws WorkSpaceNotFoundException, URISyntaxException {

    if (!reader.existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTPublisher.createWorkspace(workspaceName, new URI(uri));

}

/**

   * 删除工作空间

   *

   * @param workspaceName 要删除的工作空间名称

   * @return 删除工作空间是否成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   */

public Boolean removeWorkspace(String workspaceName) throws WorkSpaceNotFoundException {

    if (!reader.existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTPublisher.removeWorkspace(workspaceName, true);

}

Style 服务部分

/**

   * 创建 Style 服务

   * 不能将同一 SLD 文件创建多个style 服务,这将会导致删除异常

   *

   * @param sldFile sld文件对象

   * @return 返回是否创建成功

   * @throws StyleServiceNotFoundException style 样式服务不存在

   * @throws IOException 读取 SLD 文件错误

   */

public Boolean createStyle(File sldFile) throws StyleServiceNotFoundException, IOException {

    String sldFileName = sldFile.getName();

    String[] split = sldFileName.split(".sld");

    String styleName = split[0];

    reader.existsStyle(styleName);

    return this.createStyle(sldFile, styleName);

}

/**

   * 创建 Style 服务,并提供style 服务名称

   * 不能将同一 SLD 文件创建多个style 服务,这将会导致删除异常

   *

   * @param sldFile   sld 文件对象

   * @param styleName style 服务名称

   * @return 返回是否创建成功

   * @throws StyleServiceNotFoundException style 样式服务不存在

   * @throws IOException 读取 SLD 文件错误

   */

public Boolean createStyle(File sldFile, String styleName) throws StyleServiceNotFoundException, IOException {

    if (!reader.existsStyle(styleName)) {

        throw new StyleServiceNotFoundException(styleName);

    }

    //     请求路径

    String url = String.format("%s/rest/styles?name=%s&raw=true", geoServerRESTPublisher.getRestURL(), styleName);

    //     登录名、密码字符串

    String logInStr = geoServerRESTPublisher.getLogInStr();

    //     获取sld文件内容

    String file = ComTools.readFile(sldFile);

    //     格式化 sld xml 文件

    String sldInfo = file.replaceAll(" {4}", "").replaceAll(" {2}", "").replaceAll("\"", "\\\\\"");

    String[] cmds = {

        "curl", "-u", logInStr,

        "-X", HttpConstant.POST, url,

        "-H", AcceptType.JSON,

        "-H", ContentType.SLD,

        "-d", "\"" + sldInfo + "\""

    };

    String curlPostResult = ComTools.curlPost(cmds);

    /*

     * ================================================ 创建完需要put一下

     * */

    //     请求路径

    String urlPUT = String.format("%s/rest/styles/%s?raw=true", geoServerRESTPublisher.getRestURL(), styleName);

    String[] cmdsPUT = {

        "curl", "-u", logInStr,

        "-X", HttpConstant.PUT, urlPUT,

        "-H", AcceptType.JSON,

        "-H", ContentType.SLD,

        "-d", "\"" + sldInfo + "\""

    };

    ComTools.curlPUT(cmdsPUT);

    return Objects.equals(curlPostResult, styleName);

}

/**

   * 删除style服务

   *

   * @param styleName 要删除的style 名称

   * @return 是否删除成功

   * @throws StyleServiceNotFoundException 样式服务不存在

   */

public Boolean removeStyle(String styleName) throws StyleServiceNotFoundException {

    if (!reader.existsStyle(styleName)) {

        throw new StyleServiceNotFoundException(styleName);

    }

    return geoServerRESTPublisher.removeStyle(styleName, true);

}

/**

   * 创建 Style 服务到指定的工作空间下

   * 不能将同一 SLD 文件创建多个style 服务,这将会导致删除异常

   *

   * @param workspaceName 工作空间名称

   * @param sldFile       sld文件对象

   * @return 返回是否创建成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws ExistedException           style服务已存在

   * @throws IOException                文件错误

   */

public Boolean createStyleToWorkspace(String workspaceName, File sldFile) throws WorkSpaceNotFoundException, ExistedException, IOException {

    reader.existsWorkspace(workspaceName);

    String sldFileName = sldFile.getName();

    String styleName = sldFileName.split(".sld")[0];

    return this.createStyleToWorkspace(workspaceName, sldFile, styleName);

}

/**

   * 创建 Style 服务到指定的工作空间下,并提供style 服务名称

   * 不能将同一 SLD 文件创建多个style 服务,这将会导致删除异常

   *

   * @param workspaceName 工作空间名称

   * @param sldFile       sld 文件对象

   * @param styleName     style 服务名称

   * @return 返回是否创建成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws ExistedException           style样式服务已存在

   * @throws IOException                文件错误

   */

public Boolean createStyleToWorkspace(String workspaceName, File sldFile, String styleName) throws WorkSpaceNotFoundException, ExistedException, IOException {

    if (reader.existsStyleFromWorkspace(workspaceName, styleName)) {

        throw new ExistedException("style 样式服务:" + styleName);

    }

    //     请求路径

    String url = String.format("%s/rest/workspaces/%s/styles?name=%s&raw=true", geoServerRESTPublisher.getRestURL(), workspaceName, styleName);

    //     登录名、密码字符串

    String logInStr = geoServerRESTPublisher.getLogInStr();

    //     获取sld文件内容

    String file = ComTools.readFile(sldFile);

    //     格式化 sld xml 文件

    String sldInfo = file.replaceAll(" {4}", "").replaceAll(" {2}", "").replaceAll("\"", "\\\\\"");

    String[] cmds = {

        "curl", "-u", logInStr,

        "-X", HttpConstant.POST, url,

        "-H", AcceptType.JSON,

        "-H", ContentType.SLD,

        "-d", "\"" + sldInfo + "\""

    };

    String curlPostResult = ComTools.curlPost(cmds);

    /*

     * ================================================ 创建完需要put一下

     * */

    //     请求路径

    String urlPUT = String.format("%s/rest/workspaces/%s/styles/%s?raw=true", geoServerRESTPublisher.getRestURL(), workspaceName, styleName);

    String[] cmdsPUT = {

        "curl", "-u", logInStr,

        "-X", HttpConstant.PUT, urlPUT,

        "-H", AcceptType.JSON,

        "-H", ContentType.SLD,

        "-d", "\"" + sldInfo + "\""

    };

    ComTools.curlPUT(cmdsPUT);

    return Objects.equals(curlPostResult, styleName);

}

/**

   * 删除工作空间下的style服务

   *

   * @param workspaceName 工作空间名称

   * @param styleName     要删除的style 名称

   * @return 是否删除成功

   * @throws WorkSpaceNotFoundException    工作空间不存在

   * @throws StyleServiceNotFoundException 样式服务不存在

   */

public Boolean removeStyleFromWorkspace(String workspaceName, String styleName) throws WorkSpaceNotFoundException, StyleServiceNotFoundException {

    if (!reader.existsStyleFromWorkspace(workspaceName, styleName)) {

        throw new StyleServiceNotFoundException(styleName);

    }

    return geoServerRESTPublisher.removeStyleInWorkspace(workspaceName, styleName, true);

}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

在发布 style 样式服务的时候,务必需要更新一下样式服务,否则发布的服务不会生效。并且不能将同一 SLD 文件创建多个style 服务,这将会导致删除异常。

发布Shp图层

/**

   * 创建shp 图层,shp文件名则为数据源、图层名

   *

   * @param workspaceName 工作空间

   * @param shpFile       shp Zip 文件对象

   * @param crsCode       坐标系代码

   * @return shp图层是否创建成功

   * @throws FileNotFoundException 文件不存在错误

   * @throws FileNotFoundException         文件不存在错误

   * @throws ErrorException                shp源必须为 zip

   * @throws WorkSpaceNotFoundException    工作空间不存在

   * @throws ExistedException              图层名称已存在

   */

public Boolean createShpLayer(String workspaceName, File shpFile, int crsCode) throws FileNotFoundException, WorkSpaceNotFoundException, ErrorException, ExistedException {

    //    获取shp 名称

    String shpFileName = shpFile.getName();

    //    获取shp 文件名切割数组

    String[] splitList = shpFileName.split("\\.");

    //    如果后缀名不是 zip 则直接报错

    if (!Objects.equals(splitList[1], "zip")) {

        throw new ErrorException("shp 源文件必须为 zip 压缩包文件");

    }

    String crsName = "EPSG:" + crsCode;

    //    定义数据源名和图层名

    String storeName, layerName;

    storeName = layerName = splitList[0];

    if (reader.existsLayer(workspaceName, layerName)) {

        throw new ExistedException("图层名称:" + layerName);

    }

    return geoServerRESTPublisher.publishShp(workspaceName, storeName, layerName, shpFile, crsName);

}

/**

   * 创建shp 图层,shp文件名则为数据源、图层名,并指定样式

   *

   * @param workspaceName 工作空间

   * @param shpFile       shp Zip 文件对象

   * @param crsCode       坐标系代码

   * @param styleName     样式名称

   * @return 是否shp 图层是否成功

   * @throws FileNotFoundException         文件不存在错误

   * @throws ErrorException                shp源必须为 zip

   * @throws WorkSpaceNotFoundException    工作空间不存在

   * @throws ExistedException              图层名称已存在

   * @throws StyleServiceNotFoundException style 样式服务不存在

   */

public Boolean createShpLayer(

    String workspaceName,

    File shpFile,

    int crsCode,

    String styleName

) throws FileNotFoundException, ErrorException, WorkSpaceNotFoundException, ExistedException, StyleServiceNotFoundException {

    //    获取shp 名称

    String shpFileName = shpFile.getName();

    //    获取shp 文件名切割数组

    String[] splitList = shpFileName.split("\\.");

    //    如果后缀名不是 zip 则直接报错

    if (!Objects.equals(splitList[1], "zip")) {

        throw new ErrorException("shp 源文件必须为 zip 压缩包文件");

    }

    String crsName = "EPSG:" + crsCode;

    //    定义数据源名和图层名

    String storeName, layerName;

    storeName = layerName = splitList[0];

    if (reader.existsLayer(workspaceName, layerName)) {

        throw new ExistedException("图层名称:%s" + layerName);

    }

    if (!reader.existsStyle(styleName)) {

        throw new StyleServiceNotFoundException(styleName);

    }

    return geoServerRESTPublisher.publishShp(workspaceName, storeName, layerName, shpFile, crsName, styleName);

}

/**

   * 创建shp 图层,shp文件名则为数据源、图层名,并指定在某工作空间下的样式服务

   *

   * @param workspaceName      工作空间

   * @param shpFile            shp Zip 文件对象

   * @param crsCode            坐标系代码

   * @param styleWorkspaceName 样式服务所在工作空间名称

   * @param styleName          样式名称

   * @return 创建shp 图层是否成功

   * @throws FileNotFoundException         文件不存在错误

   * @throws ErrorException                shp源文件必须为zip

   * @throws WorkSpaceNotFoundException    工作空间不存在

   * @throws ExistedException              图层名称已存在

   * @throws StyleServiceNotFoundException style样式服务不存在

   */

public Boolean createShpLayer(

    String workspaceName,

    File shpFile,

    int crsCode,

    String styleWorkspaceName,

    String styleName

) throws FileNotFoundException, ErrorException, WorkSpaceNotFoundException, ExistedException, StyleServiceNotFoundException {

    //    获取shp 名称

    String shpFileName = shpFile.getName();

    //    获取shp 文件名切割数组

    String[] splitList = shpFileName.split("\\.");

    //    如果后缀名不是 zip 则直接报错

    if (!Objects.equals(splitList[1], "zip")) {

        throw new ErrorException("shp 源文件必须为 zip 压缩包文件");

    }

    String crsName = "EPSG:" + crsCode;

    //    定义数据源名和图层名

    String storeName, layerName;

    storeName = layerName = splitList[0];

    if (reader.existsLayer(workspaceName, layerName)) {

        throw new ExistedException("图层名称:%s" + layerName);

    }

    if (!reader.existsStyle(styleName)) {

        throw new StyleServiceNotFoundException(styleName);

    }

    String shpStyle = styleWorkspaceName + ":" + styleName;

    return geoServerRESTPublisher.publishShp(workspaceName, storeName, layerName, shpFile, crsName, shpStyle);

}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

需要注意的是,图层名务必需要与shp文件名一致,否则只能创建数据存储,并不能发布图层。

在定义数据存储对象的时候,可以为shp定义字符集。在这里我们定义为 UTF-8。

发布PostGIS 中存在的表

/**

   * 发布PostGIS 中存在的表图层

   *

   * @param gsPostGISDatastoreEncoder PostGIS DataStore 配置对象

   * @param workspaceName             工作空间名称

   * @param tableName                 要发布的表名

   * @param crsCode                   坐标系代码

   * @return 是否发布成功

   * @throws WorkSpaceNotFoundException 工作空间不存

   * @throws ExistedException           数据源已存在、图层已存在

   * @throws ErrorException             数据源发布失败

   */

public Boolean createPostGISLayer(

    GSPostGISDatastoreEncoder gsPostGISDatastoreEncoder,

    String workspaceName,

    String tableName,

    int crsCode

) throws ExistedException, WorkSpaceNotFoundException, ErrorException {

    GSLayerEncoder gsLayerEncoder = new GSLayerEncoder();

    return createPostGISLayer(gsPostGISDatastoreEncoder, workspaceName, tableName, crsCode, gsLayerEncoder);

}

/**

   * 发布PostGIS 中存在的表图层

   *

   * @param gsPostGISDatastoreEncoder PostGIS DataStore 配置对象

   * @param workspaceName             工作空间名称

   * @param tableName                 要发布的表名

   * @param crsCode                   坐标系代码

   * @param styleName                 style 样式服务名称

   * @return 是否发布成功

   * @throws WorkSpaceNotFoundException 工作空间不存

   * @throws ExistedException           数据源已存在、图层已存在

   * @throws ErrorException             数据源发布失败

   */

public Boolean createPostGISLayer(

    GSPostGISDatastoreEncoder gsPostGISDatastoreEncoder,

    String workspaceName,

    String tableName,

    int crsCode,

    String styleName

) throws ExistedException, WorkSpaceNotFoundException, ErrorException {

    GSLayerEncoder gsLayerEncoder = new GSLayerEncoder();

    gsLayerEncoder.setDefaultStyle(styleName);

    return createPostGISLayer(gsPostGISDatastoreEncoder, workspaceName, tableName, crsCode, gsLayerEncoder);

}

/**

   * 发布PostGIS 中存在的表图层,指定在工作空间中的样式服务

   *

   * @param gsPostGISDatastoreEncoder PostGIS DataStore 配置对象

   * @param workspaceName             工作空间名称

   * @param tableName                 要发布的表名

   * @param crsCode                   坐标系代码

   * @param styleWorkspace            style 样式服务工作空间名称

   * @param styleName                 style 样式服务名称

   * @return 是否发布成功

   * @throws WorkSpaceNotFoundException    工作空间不存

   * @throws StyleServiceNotFoundException 样式服务不存在

   * @throws ExistedException              数据源已存在、图层已存在

   * @throws ErrorException                数据源发布失败

   */

public Boolean createPostGISLayer(

    GSPostGISDatastoreEncoder gsPostGISDatastoreEncoder,

    String workspaceName,

    String tableName,

    int crsCode,

    String styleWorkspace,

    String styleName

) throws WorkSpaceNotFoundException, StyleServiceNotFoundException, ExistedException, ErrorException {

    GSLayerEncoder gsLayerEncoder = new GSLayerEncoder();

    if (!reader.existsStyleFromWorkspace(styleWorkspace, styleName)) {

        throw new StyleServiceNotFoundException(styleName);

    }

    gsLayerEncoder.setDefaultStyle(styleWorkspace + ":" + styleName);

    return createPostGISLayer(gsPostGISDatastoreEncoder, workspaceName, tableName, crsCode, gsLayerEncoder);

}

/**

   * 发布PostGIS 中存在的表,并指定style样式

   *

   * @param gsPostGISDatastoreEncoder PostGIS DataStore 配置对象

   * @param workspaceName             工作空间名称

   * @param tableName                 要发布的表名

   * @param crsCode                   坐标系代码

   * @param gsLayerEncoder            图层配置对象

   * @return 是否发布成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws ExistedException           数据源已存在、图层已存在

   * @throws ErrorException             数据源创建失败

   */

private Boolean createPostGISLayer(

    GSPostGISDatastoreEncoder gsPostGISDatastoreEncoder,

    String workspaceName,

    String tableName,

    int crsCode,

    GSLayerEncoder gsLayerEncoder

) throws WorkSpaceNotFoundException, ExistedException, ErrorException {

    if (reader.existsDataStore(workspaceName, tableName)) {

        throw new ExistedException("数据源:" + tableName);

    }

    if (reader.existsLayer(workspaceName, tableName)) {

        throw new ExistedException("图层:" + tableName);

    }

    //    创建一个datastore

    boolean postGISDataStoreResult = geoServerRESTManager.getStoreManager().create(workspaceName, gsPostGISDatastoreEncoder);

    //    获取 datastore 名称

    String storeName = gsPostGISDatastoreEncoder.getName();

    boolean publishDBLayerResult = false;

    if (postGISDataStoreResult) {

        GSFeatureTypeEncoder gsFeatureTypeEncoder = new GSFeatureTypeEncoder();

        gsFeatureTypeEncoder.setTitle(tableName);

        gsFeatureTypeEncoder.setNativeName(tableName);

        gsFeatureTypeEncoder.setName(tableName);

        gsFeatureTypeEncoder.setSRS("EPSG:" + crsCode);

        publishDBLayerResult = geoServerRESTPublisher.publishDBLayer(workspaceName, storeName, gsFeatureTypeEncoder, gsLayerEncoder);

    } else {

        throw new ErrorException(String.format("创建 datastore:%s 失败", storeName));

    }

    return publishDBLayerResult;

}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

发布GeoTIFF图层

/**

   * 发布Tiff 服务(wms)

   *

   * @param workspaceName 工作空间名称

   * @param layerName     图层名称

   * @param tifFile       tif 文件对象

   * @return 是否发布成功

   * @throws FileNotFoundException      没有找到文件

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws ExistedException           图层已存在

   */

public Boolean createGeoTIFFLayer(String workspaceName, String layerName, File tifFile) throws FileNotFoundException, WorkSpaceNotFoundException, ExistedException {

    if (reader.existsLayer(workspaceName, layerName)) {

        throw new ExistedException("图层:" + layerName);

    }

    return geoServerRESTPublisher.publishGeoTIFF(workspaceName, layerName, tifFile);

}

创建图层组部分

/**

   * 在指定工作空间下创建图层组

   *

   * @param workspaceName  工作空间民称

   * @param layerGroupName 图层组名称

   * @param layersList     图层名称列表

   * @return 图层组是否创建成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws LayerNotFoundException     图层不存在

   * @throws ExistedException           图层组已存在

   */

public Boolean createLayerGroup(String workspaceName, String layerGroupName, ArrayList<String> layersList) throws WorkSpaceNotFoundException, LayerNotFoundException, ExistedException {

    if (reader.existsLayerGroup(workspaceName, layerGroupName)) {

        throw new ExistedException("图层组:" + layerGroupName);

    }

    GSLayerGroupEncoder gsLayerGroupEncoder = new GSLayerGroupEncoder();

    gsLayerGroupEncoder.setWorkspace(workspaceName);

    gsLayerGroupEncoder.setName(layerGroupName);

    for (String layer : layersList) {

        String[] split = layer.split(":");

        String layerWorkspaceName = split[0];

        String layerName = split[1];

        if (!reader.existsLayer(layerWorkspaceName, layerName)) {

            throw new LayerNotFoundException(layerName);

        }

        gsLayerGroupEncoder.addLayer(layer);

    }

    return geoServerRESTPublisher.createLayerGroup(workspaceName, layerGroupName, gsLayerGroupEncoder);

}

删除 数据源、图层、图层组部分

/**

   * 删除矢量数据源

   *

   * @param workspaceName 要删除的矢量数据源所在的工作空间名称

   * @param dataStoreName 要删除的矢量数据源名称

   * @return 是否删除成功

   * @throws DataSourceNotFoundException 数据源不存在

   * @throws WorkSpaceNotFoundException  工作空间不存在

   */

public Boolean removeDataStore(String workspaceName, String dataStoreName) throws DataSourceNotFoundException, WorkSpaceNotFoundException {

    if (!reader.existsDataStore(workspaceName, dataStoreName)) {

        throw new DataSourceNotFoundException(dataStoreName);

    }

    return geoServerRESTPublisher.removeDatastore(workspaceName, dataStoreName, true);

}

/**

   * 删除栅格数据源

   *

   * @param workspaceName      要删除的栅格数据源所在的工作空间名称

   * @param coverageStoresName 要删除的栅格数据源名称

   * @return 栅格数据源是否删除成功

   * @throws WorkSpaceNotFoundException     工作空间不存在

   * @throws CoverageStoreNotFoundException 栅格数据源不存在

   */

public Boolean removeCoverageStores(String workspaceName, String coverageStoresName) throws WorkSpaceNotFoundException, CoverageStoreNotFoundException {

    if (!reader.existsCoverageStore(workspaceName, coverageStoresName)) {

        throw new CoverageStoreNotFoundException(coverageStoresName);

    }

    return geoServerRESTPublisher.removeCoverageStore(workspaceName, coverageStoresName, true);

}

/**

   * 删除图层

   *

   * @param workspaceName 删除图层所在的工作空间名称

   * @param layerName     删除的图层的名称

   * @return 是否删除成功

   * @throws WorkSpaceNotFoundException 工作空间不存在

   * @throws LayerNotFoundException     图层不存在

   */

public Boolean removeLayer(String workspaceName, String layerName) throws WorkSpaceNotFoundException, LayerNotFoundException {

    if (!reader.existsLayer(workspaceName, layerName)) {

        throw new LayerNotFoundException(layerName);

    }

    return geoServerRESTPublisher.removeLayer(workspaceName, layerName);

}

/**

   * 删除图层组

   *

   * @param workspaceName  删除图层组所在的工作空间

   * @param layerGroupName 图层组名称

   * @return 是否删除成功

   * @throws WorkSpaceNotFoundException  工作空间不存在

   * @throws LayerGroupNotFoundException 图层组不存在

   */

public Boolean removeLayerGroup(String workspaceName, String layerGroupName) throws WorkSpaceNotFoundException, LayerGroupNotFoundException {

    if (!reader.existsLayerGroup(workspaceName, layerGroupName)) {

        throw new LayerGroupNotFoundException(layerGroupName);

    }

    return geoServerRESTPublisher.removeLayerGroup(workspaceName, layerGroupName);

}

创建一个GeoServerReader类

本类用来处理GeoServer 是否存在和列表查询,构造函数和全局变量定义如下:

private final GeoServerRESTReader geoServerRESTReader;

public GeoServerReader(String restUrl) throws MalformedURLException {

    this(restUrl, "admin", "geoserver");

}

public GeoServerReader(String restUrl, String userName, String password) throws MalformedURLException {

    GeoServerRESTManager geoServerRESTManager = new GeoServerRESTManager(new URL(restUrl), userName, password);

    geoServerRESTReader = geoServerRESTManager.getReader();

}

工作空间部分

/**

   * 判断工作空间是否存在

   *

   * @param workspaceName 工作空间名称

   * @return 判断工作空间是否存在

   */

public Boolean existsWorkspace(String workspaceName) {

    return geoServerRESTReader.existsWorkspace(workspaceName);

}

/**

   * 获取工作空间列表

   *

   * @return 工作空间列表

   */

public ArrayList<String> getWorkspaces() {

    RESTWorkspaceList workspaces = geoServerRESTReader.getWorkspaces();

    ArrayList<String> workspacesList = new ArrayList<>();

    workspaces.forEach(restShortWorkspace -> {

        String name = restShortWorkspace.getName();

        workspacesList.add(name);

    });

    return workspacesList;

}

矢量数据源部分

/**

   * 判断某个工作空间下的矢量数据源是否存在

   *

   * @param workspaceName 工作空间名称

   * @param datastoreName 数据源名称

   * @return 数据源是否存在

   * @throws WorkSpaceNotFoundException  工作空间不存在

   */

public Boolean existsDataStore(String workspaceName, String datastoreName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTReader.existsDatastore(workspaceName, datastoreName);

}

/**

   * 获取数据源列表

   *

   * @param workspaceName 工作空间民称

   * @return 数据集名称列表

   * @throws WorkSpaceNotFoundException 工作空间不存在

   */

public ArrayList<String> getDataStores(String workspaceName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    RESTDataStoreList dataStores = geoServerRESTReader.getDatastores(workspaceName);

    ArrayList<String> dataStoresList = new ArrayList<>();

    dataStores.forEach(restShortWorkspace -> {

        String name = restShortWorkspace.getName();

        dataStoresList.add(name);

    });

    return dataStoresList;

}

栅格数据源部分

/**

   * 判断栅格数据源是否存在

   *

   * @param workspaceName     工作空间名称

   * @param coverageStoreName 栅格数据源名称

   * @return 栅格数据源是否存在

   * @throws WorkSpaceNotFoundException     工作空间不存在

   */

public Boolean existsCoverageStore(String workspaceName, String coverageStoreName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTReader.existsCoveragestore(workspaceName, coverageStoreName);

}

/**

   * 获取栅格数据源列表

   *

   * @param workspaceName 工作空间名称

   * @return 栅格数据源列表数组

   * @throws WorkSpaceNotFoundException 工作空间不存在

   */

public ArrayList<String> getCoverageStores(String workspaceName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    RESTCoverageStoreList coverageStores = geoServerRESTReader.getCoverageStores(workspaceName);

    ArrayList<String> coverageStoresList = new ArrayList<>();

    coverageStores.forEach(restShortWorkspace -> {

        String name = restShortWorkspace.getName();

        coverageStoresList.add(name);

    });

    return coverageStoresList;

}

图层部分

/**

   * 判断某个工作空间下的图层是否存在

   *

   * @param workspaceName 工作空间名称

   * @param layerName     图层名称

   * @return 图层是否存在

   * @throws WorkSpaceNotFoundException 工作空间不存在

   */

public Boolean existsLayer(String workspaceName, String layerName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTReader.existsLayer(workspaceName, layerName);

}

/**

   * 获取所有图层名称列表

   *

   * @return 图层名称列表

   */

public ArrayList<String> getLayersList() {

    RESTLayerList layers = geoServerRESTReader.getLayers();

    ArrayList<String> layerList = new ArrayList<>();

    for (NameLinkElem layer : layers) {

        String layerName = layer.getName();

        layerList.add(layerName);

    }

    return layerList;

}

/**

   * 判断图层组是否存在

   *

   * @param workspaceName  工作空间民称

   * @param layerGroupName 图层组名称

   * @return 图层组是否存在

   * @throws WorkSpaceNotFoundException  工作空间不存在

   */

public Boolean existsLayerGroup(String workspaceName, String layerGroupName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTReader.existsLayerGroup(workspaceName, layerGroupName);

}

图层组部分

/**

   * 获取所有图层组名称列表

   *

   * @param workspaceName 工作空间名称

   * @return 图层组名称列表

   */

  public ArrayList<String> getLayerGroups(String workspaceName) {

    RESTLayerGroupList layerGroups = geoServerRESTReader.getLayerGroups(workspaceName);

    ArrayList<String> layerGroupList = new ArrayList<>();

    for (NameLinkElem layerGroup : layerGroups) {

      String layerGroupName = layerGroup.getName();

      layerGroupList.add(layerGroupName);

    }

    return layerGroupList;

  }

style 样式服务部分

/**

   * 判断某工作空间下是否包含 style 服务

   *

   * @param workspaceName 工作空间民称

   * @param styleName     style 服务名称

   * @return 是否包含style服务

   * @throws WorkSpaceNotFoundException    工作空间不存在

   */

public Boolean existsStyleFromWorkspace(String workspaceName, String styleName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    return geoServerRESTReader.existsStyle(workspaceName, styleName);

}

/**

   * 获取所有样式服务

   *

   * @return 样式服务名称列表

   */

public ArrayList<String> getStyles() {

    RESTStyleList styles = geoServerRESTReader.getStyles();

    ArrayList<String> stylesList = new ArrayList<>();

    for (NameLinkElem style : styles) {

        String styleName = style.getName();

        stylesList.add(styleName);

    }

    return stylesList;

}

/**

   * 获取某工作空间下所有样式服务

   *

   * @param workspaceName 工作空间名称

   * @return 样式服务名称列表

   * @throws WorkSpaceNotFoundException 工作空间不存在

   */

public ArrayList<String> getStyles(String workspaceName) throws WorkSpaceNotFoundException {

    if (!existsWorkspace(workspaceName)) {

        throw new WorkSpaceNotFoundException(workspaceName);

    }

    RESTStyleList styles = geoServerRESTReader.getStyles(workspaceName);

    ArrayList<String> stylesList = new ArrayList<>();

    for (NameLinkElem style : styles) {

        String styleName = style.getName();

        stylesList.add(styleName);

    }

    return stylesList;

}

java并不是很熟练,还请各位大佬批评指正!

另外,赠送一个GeoJSON返回值对象

Maven依赖

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>fastjson</artifactId>

</dependency>

Feature类

public class Feature {

  private String type;

  private Object properties;

  private Object geometry;

  public String getType() {

    return type;

  }

  public void setType(String type) {

    this.type = type;

  }

  public Object getProperties() {

    return properties;

  }

  public void setProperties(Object properties) {

    this.properties = properties;

  }

  public Object getGeometry() {

    return geometry;

  }

  public void setGeometry(Object geometry) {

    this.geometry = geometry;

  }

}

GeoJSON类

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

public class GeoJSON<T> {

    private String type;

    private List<Feature> features;

    public GeoJSON(List<T> geoList) {

        this.type = "FeatureCollection";

        this.features = new ArrayList<>();

        this.build(geoList);

    }

    /*

   * 构建 geojson

   * */

    private void build(List<T> geoList) {

        for (T geom : geoList) {

            try {

                Feature feature = this.addFeature(geom);

                this.features.add(feature);

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

    /**

   * 添加图层到geojson中

   * @param geom 泛型类,数据库返回值类型

   */

    private Feature addFeature(T geom) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Class<?> geomClass = geom.getClass();

        Field[] fields = geomClass.getDeclaredFields();

        Feature feature = new Feature();

        JSONObject jsonObject = new JSONObject();

        for (Field field : fields) {

            //         获取变量名

            String fieldName = field.getName();

            //         调用get方法,获取值

            String firstLetter = fieldName.substring(0, 1).toUpperCase();

            String getMethodName = "get" + firstLetter + fieldName.substring(1);

            Method getMethod = geomClass.getMethod(getMethodName);

            Object value = getMethod.invoke(geom);

            //         如果是geoStr 属性,则构建到 geojson中

            if (fieldName.equals("geoStr")) {

                this.addGeometry(feature, value);

            } else {

                jsonObject.put(fieldName, value);

            }

        }

        feature.setProperties(jsonObject);

        return feature;

    }

    private void addGeometry (Feature feature, Object value) {

        Object geometry = JSON.parse(value.toString());

        feature.setType("Feature");

        feature.setGeometry(geometry);

    }

    public String getType() {

        return type;

    }

    public void setType(String type) {

        this.type = type;

    }

    public List<Feature> getFeatures() {

        return features;

    }

    public void setFeatures(List<Feature> features) {

        this.features = features;

    }

    @Override

    public String toString() {

        return "GeoJSON{" +

            "type='" + type + '\'' +

            ", features=" + features +

            '}';

    }

}

原文链接

此处为隐藏内容,请评论后查看隐藏内容,谢谢!


 您阅读本篇文章共花了: