<!--上传文件到阿里云服务器 start-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<!--上传文件到阿里云服务器 end-->
<!--geoserver manager-->
<dependency>
<groupId>it.geosolutions</groupId>
<artifactId>geoserver-manager</artifactId>
<version>1.7.0</version>
</dependency>
<!--style 生成-->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.19</version>
</dependency>
1.在pom文件中加入依赖
2.使用阿里云工具类 代码如下 发布时需要使用到阿里云服务器 将tif文件上传到阿里云然后从阿里云获取文件 进行发布 也可以从阿里云进行下载源文件
package com.originspace.geo.utils;
import com.aliyun.oss.*;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.google.common.collect.Lists;
import com.originspace.geo.config.sync.AliyunOssConfig;
import com.originspace.geo.entity.FUploadFile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class AliyunOSSUtil extends AbstractSync {
private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
@Autowired
private AliyunOssConfig aliyunOssConfig;
@Autowired
FileUtil fileUtil;
private final int DOWN_LOAD_VALID_TIME= 60* 60;
private final int UP_LOAD_VALID_TIME = 60*60;
/**
* 获取阿里云文件下载url
* @param fileCompleteName
* @return
*/
public String getDownLoadUrl(String fileCompleteName){
OSS ossClient = getDownloadOssClient();
// 设置签名URL过期时间为60秒(1小时)。
Date expiration = new Date(new Date().getTime() + DOWN_LOAD_VALID_TIME * 1000);
// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
URL url = ossClient.generatePresignedUrl(aliyunOssConfig.getBucketName(), fileCompleteName, expiration);
System.out.println(url);
// 关闭OSSClient。
ossClient.shutdown();
return url.toExternalForm();
}
/**
* 获取阿里云文件上传url
* @param fileName
* @return
*/
public List getUploadToken(List<String> fileName){
if(CollectionUtils.isEmpty(fileName)){
return Lists.newArrayList();
}
OSS ossClient = getDownloadOssClient();
// 设置签名URL过期时间为60秒(1小时)。
Date expiration = new Date(new Date().getTime() + UP_LOAD_VALID_TIME * 1000);
List result = Lists.newArrayList();
fileName.forEach(name ->{
// 生成签名URL。
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(aliyunOssConfig.getBucketName(), name, HttpMethod.PUT);
// 设置过期时间。
request.setExpiration(expiration);
// 设置ContentType。
request.setContentType("multipart/form-data; boundary=----WebKitFormBoundaryAnydWsQ1ajKuGoCd");
// // 添加用户自定义元信息。
// request.addUserMetadata("author", "aliy");
// 通过HTTP PUT请求生成签名URL。
URL signedUrl = ossClient.generatePresignedUrl(request);
result.add(signedUrl.toExternalForm());
});
// 关闭OSSClient。
ossClient.shutdown();
return result;
}
/**
* 在阿里云创建文件夹
* @param directory
* @return
*/
public String createDirectory(String directory){
if(!directory.endsWith("/")){
directory = directory+"/";
}
OSS ossClient = getOssClient();
// 填写字符串。
String content = "";
// 创建PutObjectRequest对象。
// 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssConfig.getBucketName(), directory, new ByteArrayInputStream(content.getBytes()));
// 上传字符串。
ossClient.putObject(putObjectRequest);
// 关闭OSSClient。
ossClient.shutdown();
return directory;
}
/**
* 删除阿里云的文件
* @param fileName
*/
public void fileDelete(String fileName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(),aliyunOssConfig.getAccessKeySecret());
try {
// 删除文件或目录。如果要删除目录,目录必须为空。
ossClient.deleteObject(aliyunOssConfig.getBucketName(), fileName);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
throw new ServiceException("文件删除失败:"+oe.getErrorMessage());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
throw new ServiceException("文件删除失败:"+ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
System.out.println(">>>>>>>>>>>>>>>删除文件:" + fileName+" 成功!");
}
/**
* 批量获取阿里云文件下载url List
* @param fileCompleteName
* @return
*/
public List<String> getDownLoadUrl(List<String> fileCompleteName){
if(CollectionUtils.isEmpty(fileCompleteName)){
return Lists.newArrayList();
}
OSS ossClient = getDownloadOssClient();
// 设置签名URL过期时间为60秒(1小时)。
Date expiration = new Date(new Date().getTime() + DOWN_LOAD_VALID_TIME * 1000);
List<URL> urlList = Lists.newArrayList();
for(int i=0; i< fileCompleteName.size(); i++){
if(StringUtils.isBlank(fileCompleteName.get(i)) ){
continue;
}
URL url = ossClient.generatePresignedUrl(aliyunOssConfig.getBucketName(), fileCompleteName.get(i), expiration);
System.out.println(url);
urlList.add(url);
}
List result = urlList.stream().map(URL::toExternalForm).collect(Collectors.toList());
// 关闭OSSClient。
ossClient.shutdown();
return result ;
}
/**
* 从阿里云下载文件到本地
*/
public String downFileFromAliyun(FUploadFile fUploadFile){
logger.info("-------------------开始从阿里云下载文件------------------------");
// 填写Bucket名称,例如examplebucket。
String bucketName = aliyunOssConfig.getBucketName();
// 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。
String objectName = fUploadFile.getFilePath();
//文件本地保存完整路径
String pathName = aliyunOssConfig.getDownLoadPath()+fUploadFile.getFilePath();
// 创建OSSClient实例。
OSS ossClient = getDownloadOssClient();
try {
//判断路径是否存在 不存在在创建
boolean dirFlag = fileUtil.isExistDir(pathName);
if (!dirFlag){
//创建文件夹失败 发布失败
logger.error("-------------------从阿里云下载失败-----路径错误-------------------"+pathName);
return null;
}
//如果当前路径下已存在同名文件删除
File file = new File(pathName);
if (file.isFile()){
logger.warn("该路径下存在同名文件,删除后再下载");
fileUtil.deleteFile(file);
}
// 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
logger.info("-------------------从阿里云下载文件结束------------------------");
} catch (OSSException oe) {
logger.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
logger.error("Error Message:" + oe.getErrorMessage());
logger.error("Error Code:" + oe.getErrorCode());
logger.error("Request ID:" + oe.getRequestId());
logger.error("Host ID:" + oe.getHostId());
pathName = null;
throw oe;
} catch (ClientException ce) {
logger.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
logger.error("Error Message:" + ce.getMessage());
pathName = null;
throw ce;
} catch (Exception e) {
logger.error("Error FileMonitor");
pathName = null;
throw new RuntimeException(e);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
return pathName;
}
}
}
3.geoserver工具类(自写) 以及style生成工具
style生成
package com.originspace.geo.utils;
import com.originspace.geo.api.bo.*;
import com.originspace.geo.config.sync.XtreamConfig;
import com.originspace.geo.entity.GColorInfo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class XtreamUtil extends AbstractSync {
private static final Logger logger = LoggerFactory.getLogger(XtreamUtil.class);
@Autowired
XtreamConfig xtreamConfig;
/**
* xstream初始化
*/
private final XStream XSTREAM = new XStream(new DomDriver());
/**
* 将xml字符串转为styledLayerDescriptor对象
*
* @param xmlString xml字符串
*/
public StyledLayerDescriptor xmlToKml(String xmlString) {
String PACKET = xtreamConfig.getPacket();
XSTREAM.allowTypesByWildcard(new String[]{PACKET});
XSTREAM.processAnnotations(StyledLayerDescriptor.class);
return (StyledLayerDescriptor) XSTREAM.fromXML(xmlString);
}
/**
* 根据数据拼接sld格式
* @param req
* @return
*/
public String CreateXmlByDB(UploadGeoEntity req) {
String PACKET = xtreamConfig.getPacket();
XStream XSTREAM = new XStream(new DomDriver());
XSTREAM.allowTypesByWildcard(new String[]{PACKET});
XSTREAM.autodetectAnnotations(true);
StyledLayerDescriptor styledLayerDescriptor = new StyledLayerDescriptor();
NamedLayer namedLayer = new NamedLayer();
namedLayer.setName(req.getStyleName());
UserStyle userStyle = new UserStyle();
userStyle.setName(req.getStyleName());
userStyle.setTitle(req.getStyleName());
FeatureTypeStyle featureTypeStyle = new FeatureTypeStyle();
Rule rule = new Rule();
List<GColorInfo> colorInfoList = req.getColorInfoList();
RasterSymbolizer rasterSymbolizer = new RasterSymbolizer();
rasterSymbolizer.setOpacity(xtreamConfig.getOpacity());
ColorMap colorMap = new ColorMap();
List<ColorMapEntry> list = new ArrayList<>();
for (GColorInfo color:colorInfoList) {
ColorMapEntry colorMapEntry = new ColorMapEntry();
colorMapEntry.setColor(color.getColor());
colorMapEntry.setOpacity(color.getOpacity());
colorMapEntry.setQuantity(String.valueOf(color.getThreshold()));
list.add(colorMapEntry);
}
colorMap.setColorMapEntryList(list);
rasterSymbolizer.setColorMap(colorMap);
rule.setRasterSymbolizer(rasterSymbolizer);
featureTypeStyle.setRule(rule);
userStyle.setFeatureTypeStyle(featureTypeStyle);
namedLayer.setUserStyle(userStyle);
styledLayerDescriptor.setNamedLayer(namedLayer);
String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + XSTREAM.toXML(styledLayerDescriptor);
logger.info("生成sld文件-----"+result);
return result;
}
}
geoserver 工具类
package com.originspace.geo.utils;
import com.alibaba.fastjson.JSONObject;
import com.originspace.geo.api.bo.CoverageStores;
import com.originspace.geo.api.bo.UploadGeoEntity;
import com.originspace.geo.common.enums.FileEnum;
import com.originspace.geo.config.sync.GeoServerConfig;
import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.decoder.*;
import it.geosolutions.geoserver.rest.encoder.datastore.GSShapefileDatastoreEncoder;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStyleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import static it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED;
@Component
public class GeoServerUtil extends AbstractSync {
private static final Logger logger = LoggerFactory.getLogger(GeoServerUtil.class);
@Autowired
private GeoServerConfig geoServerConfig;
@Autowired
private XtreamUtil xtreamUtil;
public GeoServerRESTManager getGeoServerRESTManager() {
try {
GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoServerConfig.getGeoUrl()),geoServerConfig.getUserName(),geoServerConfig.getPassWord());
if (null == manager){
logger.error("连接geoserver服务器失败!! 返回 null ");
return null;
}
logger.info("连接geoserver服务器成功!返回 manager ");
return manager;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private GeoServerRESTStyleManager getGeoServerStyleManager() {
try {
GeoServerRESTStyleManager manager = new GeoServerRESTStyleManager(new URL(geoServerConfig.getGeoUrl()),geoServerConfig.getUserName(),geoServerConfig.getPassWord());
if (null == manager){
logger.error("连接geoserver服务器失败!! 返回 null ");
return null;
}
logger.info("连接geoserver服务器成功!返回 styleManager ");
return manager;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
/**
* 发布文件到geoserver
*/
public boolean publishFileToGeo( UploadGeoEntity req){
boolean publishFlag = false;
GeoServerRESTManager manager = getGeoServerRESTManager();
if (null == manager){
//geoserver连接失败
return false;
}
//工作空间是否存在 不存在则创建工作空间
boolean wsFlag = workspaceValidate(req.getWokeSpaceName());
if (!wsFlag){
logger.error("创建工作空间失败!发布数据到geoserver失败!");
return false;
}
//根据不同文件来发布
if (null != req.getFileType() && !req.getFileType().trim().isEmpty() ){
if (req.getFileType().equals(FileEnum.SHP_FILE_TYPE.getCode())){
//shp文件发布
publishFlag = publishShpFile(req,manager);
}else if(req.getFileType().equals(FileEnum.TIF_FILE_TYPE.getCode())){
//tif文件发布
publishFlag = publishTifFile(req,manager);
}else if(req.getFileType().equals(FileEnum.SLD_FILE_TYPE.getCode())){
//sld文件发布
publishFlag = publishSldFile(req);
}else {
logger.error("该文件不属于可发布文件类型,请检查文件格式重新上传并发布!!!");
}
}else{
logger.error("参数不完整,文件类型为非法值,请检查文件类型数据重新发布!!!");
}
return publishFlag;
}
/**
* tif文件发布 tif文件发布
* @param req
*/
private boolean publishTifFile(UploadGeoEntity req, GeoServerRESTManager manager) {
GeoServerRESTPublisher publisher = manager.getPublisher();
GeoServerRESTReader reader = manager.getReader();
boolean result = false;
logger.info("开始发布--------TIF文件到geoserver------------");
File file = new File(req.getFileLocalPath());
try {
logger.info("校验style是否存在--------发布TIF文件到geoserver------------");
//不是默认style名称 校验该style是否存在 不存在则修改为默认style
if (null == req.getStyleName() || req.getStyleName().trim().isEmpty()){
req.setStyleName(geoServerConfig.getTifStyle());
}
if (!req.getStyleName().equals(geoServerConfig.getTifStyle())){
boolean styleFlag = styleValidate(req,reader);
if (!styleFlag){
//style在工作空间不存在 修改style为默认style
req.setStyleName(geoServerConfig.getTifStyle());
}
}
//store与layer是否存在,不存在则新建并发布数据。
RESTDataStore restStore = reader.getDatastore(req.getWokeSpaceName(), req.getStoreName());
RESTLayer layer = reader.getLayer(req.getWokeSpaceName(), req.getLayerName());
if (null == restStore && null == layer){
logger.info("创建数据存储仓库--------发布TIF文件到geoserver------------");
result = publisher.publishGeoTIFF(req.getWokeSpaceName(),req.getStoreName(),req.getLayerName(),file,geoServerConfig.getSrs(),FORCE_DECLARED,req.getStyleName(),null);
logger.info("TIF数据发布是否成功:"+result);
}else{
logger.error("发布失败!!!该工作空间 "+req.getWokeSpaceName()+" 已存在同名RESTDataStore数据,不能重复发布!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
/**
* 发布shp文件
* @param req
*/
private boolean publishShpFile(UploadGeoEntity req, GeoServerRESTManager manager) {
logger.info(" ------------start-publishShpFile------------");
GeoServerRESTPublisher publisher = manager.getPublisher();
GeoServerRESTReader reader = manager.getReader();
boolean result = false;
File file = new File(req.getFileLocalPath());
if (!file.isFile()){
//文件不存在
logger.error("该路径下文件不存在"+file.getPath());
return result;
}
//shp文件路径不可为空
if (null == req.getShpFilePath() || req.getShpFilePath().trim().isEmpty()){
return result;
}
try {
logger.info("校验style是否存在--------发布SHP文件到geoserver------------");
if (null == req.getStyleName() || req.getStyleName().trim().isEmpty()){
req.setStyleName(geoServerConfig.getShpStyle());
}
//不是默认style名称 校验该style是否存在 不存在则修改为默认style
if (!req.getStyleName().equals(geoServerConfig.getShpStyle())){
boolean styleFlag = styleValidate(req,reader);
if (!styleFlag){
//style在该工作空间下不存在 修改style为默认style
req.setStyleName(geoServerConfig.getShpStyle());
}
}
//判断数据存储(datastore)是否已经存在,不存在则创建
result = ( null == req.getShpFilePath() || req.getShpFilePath().trim().isEmpty());
if (!result){
URL urlShapefilePath = new URL(req.getShpFilePath());
RESTDataStore restStore = reader.getDatastore(req.getWokeSpaceName(), req.getStoreName());
if(null == restStore){
//创建shape文件存储
logger.info("在当前工作空间"+req.getWokeSpaceName()+"下创建shp存储文件--------"+req.getStoreName());
GSShapefileDatastoreEncoder store = new GSShapefileDatastoreEncoder(req.getStoreName(), urlShapefilePath);
result = manager.getStoreManager().create(req.getWokeSpaceName(), store);
} else {
logger.error("该工作空间下已存在同名数据存储----------------,store:" + req.getStoreName());
}
//判断图层是否已经存在,不存在则创建并发布
RESTLayer layer = reader.getLayer(req.getWokeSpaceName(), req.getLayerName());
if(null == layer){
//发布图层
result = publisher.publishShp(req.getWokeSpaceName(), req.getStoreName(), req.getLayerName(), file,geoServerConfig.getSrs() ,req.getStyleName());
logger.info("-------发布SHP文件到geoserver是否成功------------"+result);
}else {
logger.error("发布失败!!!该工作空间 "+req.getWokeSpaceName()+" 已存在同名RESTDataStore数据,不能重复发布!");
}
}else {
logger.error("发布失败!!! shpFilePath 非法值");
}
} catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
/**
* 删除geoserver数据源以及图层
*/
public boolean deleteFile(UploadGeoEntity req, GeoServerRESTManager manager) {
logger.info(" ------------start-deleteFile------------");
GeoServerRESTPublisher publisher = manager.getPublisher();
GeoServerRESTReader reader = manager.getReader();
boolean result = false;
logger.info("校验图层是否存在--------删除图层------------");
//判断图层是否存在
RESTLayer layer = reader.getLayer(req.getWokeSpaceName(), req.getLayerName());
if(null != layer){
result = publisher.removeLayer(req.getWokeSpaceName(), req.getLayerName());
logger.info("-------图层删除是否成功------------"+result);
}
//判断数据源是否存在 分为shp文件和tif文件
//tif文件使用existsCoverageStore方法
if (req.getFileType().equals(FileEnum.TIF_FILE_TYPE.getCode())){
result = reader.existsCoveragestore(req.getWokeSpaceName(), req.getStoreName());
if (result){
result = publisher.removeCoverageStore(req.getWokeSpaceName(),req.getStoreName(),true);
logger.info("-------tif数据源删除是否成功------------"+result);
}
}
//shp文件使用existsDatastore方法
if (req.getFileType().equals(FileEnum.SHP_FILE_TYPE.getCode())){
result = reader.existsDatastore(req.getWokeSpaceName(), req.getStoreName());
if (result){
result = publisher.removeDatastore(req.getWokeSpaceName(),req.getStoreName(),true);
logger.info("-------shp数据源删除是否成功------------"+result);
}
}
//判断工作空间下数据源为空 删除工作空间
RESTCoverageStoreList coverageStores = reader.getCoverageStores(req.getWokeSpaceName());
String s2 = JSONObject.toJSONString(coverageStores);
CoverageStores coverageStores1 = JSONObject.parseObject(s2, CoverageStores.class);
RESTDataStoreList dataStores = reader.getDatastores(req.getWokeSpaceName());
String s3 = JSONObject.toJSONString(dataStores);
CoverageStores coverageStores2 = JSONObject.parseObject(s3, CoverageStores.class);
if (coverageStores1.getEmpty().equals("true")&&coverageStores2.getEmpty().equals("true")){
result = publisher.removeWorkspace(req.getWokeSpaceName(), true);
}
return result;
}
/**
* 校验样式是否存在
* @param req
* @param reader
* @return
*/
private boolean styleValidate(UploadGeoEntity req,GeoServerRESTReader reader) {
if (null == req.getStyleWsName() || req.getStyleWsName().trim().isEmpty()){
//style没有工作空间设置 只有style名称
logger.info("校验style是否存在"+req.getStyleName());
return reader.existsStyle(req.getStyleName());
}else {
//指定 workspace下 校验 是否存在 style
logger.info("校验"+req.getStyleWsName()+"style是否存在"+req.getStyleName());
return reader.existsStyle(req.getStyleWsName(), req.getStyleName());
}
}
/**
* sld文件发布
* @param req
*/
private boolean publishSldFile(UploadGeoEntity req) {
GeoServerRESTManager manager = getGeoServerRESTManager();
GeoServerRESTReader reader = manager.getReader();
GeoServerRESTStyleManager styleManager = getGeoServerStyleManager();
logger.info("开始发布--------SLD文件到geoserver------------");
boolean result = false;
//判断style是否已经存在,不存在则创建
RESTStyle restStyle =reader.getStyle(req.getWokeSpaceName(), req.getStyleName());
if (restStyle == null) {
logger.info("在当前工作空间"+req.getWokeSpaceName()+"下发布sld文件--------");
String sldString = xtreamUtil.CreateXmlByDB(req);
result = styleManager.publishStyleInWorkspace(req.getWokeSpaceName(),sldString,req.getStyleName());
logger.info("发布sld文件--------"+result);
} else {
logger.error("该样式已经存在----------------请勿重复发布-------,store:" + req.getStyleName());
}
return result;
}
public boolean updateSldFile(UploadGeoEntity req) {
GeoServerRESTManager manager = getGeoServerRESTManager();
GeoServerRESTReader reader = manager.getReader();
GeoServerRESTStyleManager styleManager = getGeoServerStyleManager();
logger.info("开始修改-------SLD文件到geoserver------------");
boolean result = false;
//判断style是否已经存在,存在进行修改
RESTStyle restStyle =reader.getStyle(req.getWokeSpaceName(), req.getStyleName());
if (restStyle != null) {
logger.info("在当前工作空间"+req.getWokeSpaceName()+"下修改sld文件--------");
String sldString = xtreamUtil.CreateXmlByDB(req);
result = styleManager.updateStyleInWorkspace(req.getWokeSpaceName(),sldString,req.getStyleName());
logger.info("修改sld文件--------"+result);
} else {
logger.error("该样式不存在,store:" + req.getStyleName());
}
return result;
}
/**
* 工作空间是否存在 不存在则创建工作空间
* @param wokeSpaceName
*/
private boolean workspaceValidate(String wokeSpaceName) {
boolean wsFlag = false;
GeoServerRESTManager manager = getGeoServerRESTManager();
GeoServerRESTPublisher publisher = manager.getPublisher();
GeoServerRESTReader reader = manager.getReader();
wsFlag = reader.existsWorkspace(wokeSpaceName);
//判断工作空间是否存在
if (!wsFlag) {
logger.info("工作空间不存在,创建新的工作空间---"+wokeSpaceName);
//创建一个新的存储空间
wsFlag = publisher.createWorkspace(wokeSpaceName);
logger.info("创建工作空间是否成功"+wsFlag);
return wsFlag;
} else {
logger.info("工作空间已存在,请继续下一步流程");
}
return wsFlag;
}
/**
* 根据工作空间 图层名称 获取图层数据
* @param wsName
* @param layerName
* @return
*/
public String queryLayerUrl(String wsName, String layerName,String dbStyle) {
GeoServerRESTManager manager = getGeoServerRESTManager();
GeoServerRESTReader reader = manager.getReader();
logger.info("获取图层信息------------"+wsName+":"+layerName);
RESTLayer layer = reader.getLayer(wsName,layerName);
double minx = 0;
double maxy = 0;
double maxx = 0;
double miny = 0;
String crs="";
if (null == layer){
return null;
}
if (!dbStyle.equals(FileEnum.TIF_FILE_TYPE.getCode()) && !dbStyle.equals(FileEnum.SHP_FILE_TYPE.getCode())){
return null;
}
//根据shp 或者tif来获取不同数据 TIF
if (dbStyle.equals(FileEnum.TIF_FILE_TYPE.getCode())){
logger.info("获取RESTWms------------");
RESTWms restWms = reader.getWms(layer);
if (null == restWms){
return null;
}
minx = restWms.getMinX();
miny = restWms.getMinY();
maxx = restWms.getMaxX();
maxy = restWms.getMaxY();
crs = restWms.getCRS();
}else if (dbStyle.equals(FileEnum.SHP_FILE_TYPE.getCode())){
logger.info("获取RESTFeatureType------------");
RESTFeatureType featureType = reader.getFeatureType(layer);
if (null == featureType){
return null;
}
maxx = featureType.getMaxX();
minx =featureType.getMinX();
maxy =featureType.getMaxY();
miny =featureType.getMinY();
crs = featureType.getCRS();
}
String url = geoServerConfig.getLayerPreViewUrl();
url += "/"+wsName+"/wms?service=WMS&version="+geoServerConfig.getVersion()+"&request=GetMap&layers="+wsName+"%3A"+layerName+"&bbox="+
minx+"%2C"+ miny+"%2C"+ maxx+"%2C"+ maxy+"&width="+geoServerConfig.getWidth()+"&height="+geoServerConfig.getHeight()+"&srs="+ crs+
"&styles=&format=image%2Fpng";
logger.info("======图层预览地址为:"+url);
return url;
}
/**
* 删除指定style信息
* @param req
* @return
*/
public boolean deleteStyle(UploadGeoEntity req) {
GeoServerRESTManager manager = getGeoServerRESTManager();
GeoServerRESTPublisher publisher = manager.getPublisher();
GeoServerRESTReader reader = manager.getReader();
if (null == req.getWokeSpaceName() || req.getWokeSpaceName().trim().isEmpty()){
if (null == req.getStyleName() || req.getStyleName().trim().isEmpty()){
logger.error("图层名称为null 请检查参数!!!");
return false;
}
boolean styleFlag =reader.existsStyle( req.getStyleName());
if (!styleFlag){
logger.error("不存在该style文件,请查看具体信息是否正确"+req.getStyleName());
return false;
}
publisher.removeStyle(req.getStyleName());
}
boolean wsFlag = reader.existsWorkspace(req.getWokeSpaceName());
if (!wsFlag){
logger.error("该工作空间不存在 请检查参数!!!"+req.getWokeSpaceName());
return false;
}
if (null == req.getStyleName() || req.getStyleName().trim().isEmpty()){
logger.error("图层名称不存在 请检查参数!!!");
return false;
}
boolean styleFlag =reader.existsStyle(req.getWokeSpaceName(), req.getStyleName());
if (!styleFlag) {
logger.error("该工作空间下不存在该style文件,请查看具体信息是否正确"+req.getStyleName());
return false;
}
return publisher.removeStyleInWorkspace(req.getWokeSpaceName(),req.getStyleName());
}
}
4.在ynl文件中进行配置
aliyunoss:
bucketName:
# yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
endpoint:
internalEndpoint:
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
accessKeyId:
accessKeySecret:
# 不能以"/"开头
targetFilePath:
#限速M
uploadLimit: 0.5
#文件下载到本地保存路径
downLoadPath:
geoserver:
# geoserver发布数据地址 修改为当前geoserver服务地址
geoUrl:
# geoserver预览图层地址 修改为当前geoserver地址
layerPreViewUrl:
userName:
passWord:
# 默认坐标
srs: "EPSG:4326"
# 默认 tif文件style
tifStyle: "raster"
# 默认shp文件style
shpStyle: "polygon"
# 默认shp文件读取路径
shpFilePath: "file:data"
# 默认工作空间名称
defaultWs: "temp-ws"
# 默认geoserver版本号
version: "1.1.0"
# 默认图层预览宽
width: "722"
# 默认图层预览高
height: "768"
# 边界文件默认style
boundaryStyle: "shp_line"
#生成style文件设置默认透明度值
xtream:
packet: "com.originspace.geo.api.bo.**"
opacity: "1.0"
创建对应实体类 然后读取配置文件中的数据即可 连接阿里云和geoserver
5.上传到阿里云服务器需要保存其路径 存在数据库中进行使用 需要的数据还有图例,图层名称等保证其不一致
6.此处只支持坐标系为4326坐标进行上传发布 其他坐标暂不可 shp文件需要压缩为zip文件进行上传