关于JAVA通过REST接口对arcGis Server数据进行增删改查
一: 添加要素
public void create(BoxVo boxVo) throws Exception {
// 创建HTTP客户端
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(ArcGisConstants.REQUEST_CONFIG).build();
// 创建POST请求
HttpPost httpPost = new HttpPost(ArcGisConstants.baseDataUrl + ArcGisConstants.BOX_ADD_FEATURES);
// 查询当前新增的box在ArcGis中是否存在
Map<String, Object> oldFeature = query(boxVo);
if (oldFeature != null && oldFeature.size() > 0) {
LOGGER.info("当前新增的box已经存在, 执行修改操作");
update(boxVo);
return;
}
// 运行到这里说明该box在ArcGis中不存在, 执行新增操作
// 创建新的空间模型
Map<String, Object> geometry = ArcGisUtils.createNewGeometry(boxVo.getLongitude(), boxVo.getLatitude());
// 创建新的数据模型
Map<String, Object> attributes = ArcGisUtils.createNewBoxAttributes(boxVo, null);
// 创建新的容器模型
List<Map<String, Object>> features = ArcGisUtils.createNewFeatures(geometry, attributes);
// 模型对象转换成json字符串
String jsonStr = JsonUtil.jsonObj2Sting(features);
// 创建POST请求参数, 必须用NameValuePair
List<NameValuePair> params = new ArrayList<>();
// 设置传值参数类型为json
params.add(new BasicNameValuePair("f", "json"));
// 将转换好的字符串添加到参数中
params.add(new BasicNameValuePair(ArcGisConstants.FEATURES, jsonStr));
// 设置POST请求参数,并将参数格式设置为utf-8
HttpEntity entity = new UrlEncodedFormEntity(params, ArcGisConstants.DEFAULT_CHARSET);
httpPost.setEntity(entity);
// 发送请求
HttpResponse response = httpclient.execute(httpPost);
// 处理结果集
if (response.getStatusLine().getStatusCode() == 200) {
// 调用EntityUtils.toString方法最后会自动把inputStream close掉的
String str = EntityUtils.toString(response.getEntity());
LOGGER.info("ArcGis添加box: box: " + jsonStr + " 结果: " + str);
// 释放资源
httpclient.close();
} else {
throw new RuntimeException("ArcGis添加box失败");
}
}
二: 更改要素
public void update(BoxVo boxVo) throws Exception {
// 创建HTTP客户端
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(ArcGisConstants.REQUEST_CONFIG).build();
// 创建post请求
HttpPost httpPost = new HttpPost(ArcGisConstants.baseDataUrl + ArcGisConstants.BOX_UPDATE_FEATURES);
// 查询当前被修改的box在ArcGis中是否存在
Map<String, Object> oldFeature = query(boxVo);
if (oldFeature != null && oldFeature.size() > 0) {
// 得到feature里面的attributes
Map<String, Object> oldAttributes = (Map<String, Object>) oldFeature.get(ArcGisConstants.ATTRIBUTES);
// 得到attributes里面的objectid
Integer objectid = (Integer) oldAttributes.get(ArcGisConstants.OBJECT_ID);
if (objectid != null && objectid != 0) {
// 创建新的空间模型
Map<String, Object> newGeometry = ArcGisUtils.createNewGeometry(boxVo.getLongitude(), boxVo.getLatitude());
// 创建新的数据模型
Map<String, Object> newAttributes = ArcGisUtils.createNewBoxAttributes(boxVo, objectid);
// 创建新的容器模型
List<Map<String, Object>> newFeatures = ArcGisUtils.createNewFeatures(newGeometry, newAttributes);
// 将模型对象转换成json字符串
String jsonStr = JsonUtil.jsonObj2Sting(newFeatures);
// 创建POST请求参数, 必须用NameValuePair
List<NameValuePair> params = new ArrayList<>();
// 设置传值参数类型为json
params.add(new BasicNameValuePair("f", "json"));
// 将转换好的字符串添加到参数中
params.add(new BasicNameValuePair(ArcGisConstants.FEATURES, jsonStr));
// 设置POST请求参数,并将参数格式设置为utf-8
HttpEntity entity = new UrlEncodedFormEntity(params, ArcGisConstants.DEFAULT_CHARSET);
httpPost.setEntity(entity);
// 发送请求
HttpResponse response = httpclient.execute(httpPost);
// 处理结果集
if (response.getStatusLine().getStatusCode() == 200) {
// 调用EntityUtils.toString方法最后会自动把inputStream close掉的
EntityUtils.toString(response.getEntity());
LOGGER.info("ArcGis更改box: mapid = " + boxVo.getMapId());
// 释放资源
httpclient.close();
} else {
throw new RuntimeException("ArcGis更改box失败");
}
} else {
create(boxVo);
}
} else {
// 如果查出来的结果为null,则将该box添加到arcGis中图层
create(boxVo);
}
}
三: 删除要素
public void delete(List<BoxVo> boxVos) throws Exception {
// 创建HTTP客户端
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(ArcGisConstants.REQUEST_CONFIG).build();
// 创建POST请求
HttpPost httpPost = new HttpPost(ArcGisConstants.baseDataUrl + ArcGisConstants.BOX_DELETE_FEATURES);
// 处理请求参数
StringBuffer deleteWhere = new StringBuffer();
// 拼装条件, 按照mapIds进行批量删除
deleteWhere.append("mapid in (");
if (boxVos != null && boxVos.size() > 0) {
for (int i = 0; i <= boxVos.size() - 1; i++) {
deleteWhere.append("'");
deleteWhere.append(boxVos.get(i).getMapId());
deleteWhere.append("'");
if (i != boxVos.size() - 1) {
deleteWhere.append(",");
}
}
}
deleteWhere.append(")");
// 创建POST请求参数, 必须用NameValuePair
List<NameValuePair> params = new ArrayList<>();
// 设置传值参数类型为json
params.add(new BasicNameValuePair("f", "json"));
// 将拼装好的条件添加到参数中
params.add(new BasicNameValuePair("where", deleteWhere.toString()));
// 设置POST请求参数,并将参数格式设置为utf-8
HttpEntity entity = new UrlEncodedFormEntity(params, ArcGisConstants.DEFAULT_CHARSET);
httpPost.setEntity(entity);
// 发送请求
HttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
// 调用EntityUtils.toString方法最后会自动把inputStream close掉的
EntityUtils.toString(response.getEntity());
LOGGER.info("ArcGis批量删除box: " + deleteWhere.toString());
// 释放资源
httpclient.close();
} else {
throw new RuntimeException("ArcGis删除box失败");
}
}
四: 查询要素
public Map<String, Object> query(BoxVo boxVo) throws Exception {
// 创建HTTP客户端
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(ArcGisConstants.REQUEST_CONFIG).build();
// 创建POST请求
HttpPost httpPost = new HttpPost(ArcGisConstants.baseDataUrl + ArcGisConstants.BOX_QUERY_FEATURES);
// 处理请求参数
String where = "mapid=" + "'" + boxVo.getMapId() + "'";
// 创建POST请求参数, 必须用NameValuePair
List<NameValuePair> params = new ArrayList<>();
// 设置传值参数类型为json
params.add(new BasicNameValuePair("f", "json"));
// 将拼装好的条件添加到参数中
params.add(new BasicNameValuePair("where", where));
// 返回所有字段
params.add(new BasicNameValuePair("outFields", "*"));
//设置http Post请求参数
HttpEntity entity = new UrlEncodedFormEntity(params, ArcGisConstants.DEFAULT_CHARSET);
httpPost.setEntity(entity);
// 发送请求
HttpResponse response = httpclient.execute(httpPost);
// 处理结果集
Map<String, Object> oldFeature = new HashMap<>();
if (response.getStatusLine().getStatusCode() == 200) {
// 调用EntityUtils.toString方法最后会自动把inputStream close掉的
String result = EntityUtils.toString(response.getEntity());
LOGGER.info("arcgis查询box: box = " + result);
// 将旧的对象从result解析出来,得到objectid
Map<String, Object> data = new HashMap<>();
data = JsonUtil.jsonString2SimpleObj(result, data.getClass());
// 得到旧的features集合
List<Map<String, Object>> oldFeatures = (List<Map<String, Object>>) data.get(ArcGisConstants.FEATURES);
// 获取第一个数据
if (oldFeatures.size() > 0) {
oldFeature = oldFeatures.get(0);
}
}
// 释放资源
httpclient.close();
return oldFeature;
}
相关常量类
/**
* ArcGis常量类
*
*/
@Component()
public class ArcGisConstants implements InitializingBean {
private static final Logger LOG = java.util.logging.Logger.getLogger(ArcGisConstants.class.getName()); /*
* 设置请求参数:
* setConnectionRequestTimeout: 设置从连接池中取连接的超时时间
* setConnectTimeout: 设置连接超时时间
* setSocketTimeout: 设置请求超时时间
*/
public static final RequestConfig REQUEST_CONFIG = RequestConfig.custom().setConnectionRequestTimeout(1000 * 10).setConnectTimeout(1000 * 10).setSocketTimeout(1000 * 10).build(); /********** 定义通用常量 **********/
public static final String FEATURES = "features"; // features
public static final String GEOMETRY = "geometry"; // 控件模型
public static final String ATTRIBUTES = "attributes"; // 数据模型
public static final String DEFAULT_CHARSET = "UTF-8"; // 请求的编码格式
public static final String DEFAULT_TIME_FORMAT = "yyyy-MM-dd"; // 请求的编码格式
public static final String BOX = "box"; // 配电箱 /********** 定义通用字段 **********/
public static final String BOX_ADD_FEATURES = "/0/addFeatures"; // 添加box的url
public static final String BOX_UPDATE_FEATURES = "/0/updateFeatures"; // 更改box的url
public static final String BOX_DELETE_FEATURES = "/0/deleteFeatures"; // 删除box的url
public static final String BOX_QUERY_FEATURES = "/0/query"; // 查询box的url
public static final String OBJECT_ID = "objectid"; // objectid 主要用于图层要素的更新操作
public static final String BOX_NAME = "boxname"; // box名称
public static final String BOX_NO = "boxno"; // box编号
public static final String CREATE_TIME = "createtime"; // 要素创建时间
public static final String ADDRESS = "address"; // 安装地址
public static final String PHOTO = "photo"; // 照片路径
public static final String LON = "x"; // 经度
public static final String LAT = "y"; // 纬度 /********** 根据租户信息获取到的ArcGis数据图层url, 赋值到baseDataUrl **********/
@Value("${portal.url}")
@Getter
@Setter
private String portalUrl; // 租户url public static String baseDataUrl; // 根据租户信息获取到的ArcGis数据图层url @Override
public void afterPropertiesSet() throws Exception {
//请求path
String path = "/web/tenant/1";
Map<String, String> headers = new HashMap<>();
//(必填)根据期望的Response内容类型设置
headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_JSON);
Request request = new Request(Method.GET, HttpSchema.HTTP + portalUrl, path, null, null, Constants.DEFAULT_TIMEOUT);
request.setHeaders(headers);
//调用服务端
Response response = Client.execute(request);
if (response.getStatusCode() == 200) {
Map<String, Object> param = new HashMap<>();
param = JsonUtil.jsonString2SimpleObj(response.getBody(), param.getClass());
Map<String, Object> data = (Map<String, Object>) param.get("data");
Map<String, Object> applicationProfile = (Map<String, Object>) data.get("applicationProfileVo");
baseDataUrl = (String) applicationProfile.get("mapUrl");
LOG.info("数据图层为: " + baseDataUrl);
} else {
throw new RuntimeException("初始化ArcGis数据链接失败...");
}
}
}
相关工具类
/**
* arcGis工具类
*
*/
public class ArcGisUtils {
/**
* 处理照片路径
*
* @param attachments
* @return
*/
public static StringBuffer processPhotosAddStr(List<Attachment> attachments, String type) {
StringBuffer photoStr = new StringBuffer();
String devType = "";
if (type.equals(ArcGisConstants.BOX)) {
devType = ArcGisConstants.BOX_PHOTOS;
}
if (attachments != null && attachments.size() > 0) {
for (int i = 0; i <= attachments.size() - 1; i++) {
photoStr.append(attachments.get(i).getAddress().split(devType)[1]);
if (i < attachments.size() - 1) {
// 不是最后一张
photoStr.append(",");
}
}
}
return photoStr;
} /**
* 创建新的容器模型
*
* @param geometry
* @param attributes
* @return
*/
public static List<Map<String, Object>> createNewFeatures(Map<String, Object> geometry, Map<String, Object> attributes) {
List<Map<String, Object>> features = new ArrayList<>();
HashMap<String, Object> feature = new HashMap<>();
feature.put(ArcGisConstants.GEOMETRY, geometry);
feature.put(ArcGisConstants.ATTRIBUTES, attributes);
features.add(feature);
return features;
} /**
* 创建新的空间模型: 根据经纬度
*
* @param lon
* @param lat
* @return
*/
public static Map<String, Object> createNewGeometry(BigDecimal lon, BigDecimal lat) {
Map<String, Object> newGeometry = new HashMap<>();
if (lon != null) {
newGeometry.put(ArcGisConstants.LON, lon);
} else {
newGeometry.put(ArcGisConstants.LON, 0);
}
if (lat != null) {
newGeometry.put(ArcGisConstants.LAT, lat);
} else {
newGeometry.put(ArcGisConstants.LAT, 0);
}
return newGeometry;
} /**
* 创建新的box数据模型
*
* @param boxVo
* @param objectid
* @return
*/
public static Map<String, Object> createNewBoxAttributes(BoxVo boxVo, Integer objectid) {
Map<String, Object> newAttributes = new HashMap<>();
if (objectid != null) {
// 对于修改时的objectid必须进行赋值, 这行代码仅针对于修改box时使用
newAttributes.put(ArcGisConstants.OBJECT_ID, objectid);
} else {
// 对于新增时的createtime进行赋值, 这行代码仅针对于新增box时使用
newAttributes.put(ArcGisConstants.CREATE_TIME, new SimpleDateFormat(ArcGisConstants.DEFAULT_TIME_FORMAT).format(new Date()));
}
newAttributes.put(ArcGisConstants.BOX_NAME, boxVo.getName());
newAttributes.put(ArcGisConstants.BOX_NO, boxVo.getChannelNumber());
newAttributes.put(ArcGisConstants.ADDRESS, boxVo.getInstalledAddress());
newAttributes.put(ArcGisConstants.PHOTO, ArcGisUtils.processPhotosAddStr(boxVo.getAttachments(), ArcGisConstants.BOX));
if (boxVo.getLongitude() != null) {
newAttributes.put(ArcGisConstants.LON, boxVo.getLongitude());
} else {
newAttributes.put(ArcGisConstants.LON, 0);
}
if (boxVo.getLatitude() != null) {
newAttributes.put(ArcGisConstants.LAT, boxVo.getLatitude());
} else {
newAttributes.put(ArcGisConstants.LAT, 0);
}
return newAttributes;
}
}
关于JAVA通过REST接口对arcGis Server数据进行增删改查的更多相关文章
- Mybatis学习总结(二)—使用接口实现数据的增删改查
在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num ...
- django学习-12.访问不同url/接口地址实现对指定数据的增删改查功能
1.前言 通过前面博客[django学习-10.django连接mysql数据库和创建数据表]里的操作,我们已经成功在数据库[hongjingsheng_project]里创建了一张数据表[hello ...
- Java数据库连接——JDBC基础知识(操作数据库:增删改查)
一.JDBC简介 JDBC是连接java应用程序和数据库之间的桥梁. 什么是JDBC? Java语言访问数据库的一种规范,是一套API. JDBC (Java Database Connectivit ...
- Java简单示例-用户登录、单个页面的增删改查及简单分页
index.html -登录->stulist.jsp (index.html传递到LoginServlet,进行登录检测及写入session,NO返回index.html界面,OK 跳转到s ...
- Sql Server——数据的增删改
所谓数据的增删改就是在创建好数据库和表后向表中添加数据.删除表中的数据.更改表中的一些数据. 新增数据: 语法一: insert into 表名 values (数据内容) --这里需要 ...
- VS连接SQL Server数据库,增删改查详细教程(C#代码)_转载
工具: 1.Visual Studio (我使用的是vs2013) 2.SQL Server (我使用的是sql server2008) 操作: 1.打开SQL Server,打开后会看到数据库的初 ...
- java使用原生MySQL实现数据的增删改查以及数据库连接池技术
一.工具类及配置文件准备工作 1.1 引入jar包 使用原生MySQL,只需要用到MySQL连接的jar包,maven引用方式如下: <dependency> <groupId> ...
- python连接sql server数据库实现增删改查
简述 python连接微软的sql server数据库用的第三方模块叫做pymssql(document:http://www.pymssql.org/en/stable/index.html).在官 ...
- Mybatis 接口方式对数据的增删改查 一对一关联查询
数据库中有两个表 student 和studentInfo student表中的字段和数据 studentInfo表中的字段 ok数据库说完了,开始建立一个项目,对数据库中的数据进行操作吧 新建jav ...
随机推荐
- Scrapy的log日志功能
Logging Scrapy提供了log功能,可以通过 logging 模块使用 可以修改配置文件settings.py,任意位置添加下面两行 LOG_FILE = "mySpider.lo ...
- PHP错误处理函数set_error_handler()的用法[转载]
定义和用法 set_error_handler() 函数设置用户自定义的错误处理函数. 该函数用于创建运行时期间的用户自己的错误处理方法. 该函数会返回旧的错误处理程序,若失败,则返回 null. 语 ...
- IE下IFrame引用跨域站点页面时,Session失效问题解决
问题场景:在一个应用(集团门户)的某个page中, 通过IFrame的方式嵌入另一个应用(集团实时监管系统)的某个页面. 当两个应用的domain 不一样时, 在被嵌入的页面中Session失效.(s ...
- C#高级编程第9版 第二章 核心C# 读后笔记
System命名空间包含了最常用的.NET类型.对应前面第一章的.NET基类.可以这样理解:.NET类提供了大部分的功能,而C#语言本身是提供了规则. pseudo-code,哈哈,秀逗code.伪代 ...
- linux日志服务器审计客户端history记录
https://blog.csdn.net/yanggd1987/article/details/70255179
- 一个开发的Linux使用心得总结
Liunx介绍 Linux是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX和UNIX的多用户.多任务.支持多线程和多CPU的操作系统.它能运行主要的UNIX工具软件.应用程序和网络协 ...
- Maven创建项目时出现Generating project in Interactive mode就一直卡住的解决方案
使用maven命令在创建项目的时候出现 Generating project in Interactive mode 然后就一直卡住 网上搜做了很多解决方案 有说各种方案的,最后找到了一种.实验成功 ...
- "undefined reference to strptime"之自己定义strptime函数
简单介绍 strptime()函数可以依照特定时间格式将字符串转换为时间类型.简单点说可以将字符串时间转化为时间戳. 这个函数包括在time.h头文件里,在Unix或者类Unix系统中,我们会常常 ...
- Linux 的 Socket IO 模型
前言 之前有看到用很幽默的方式讲解Windows的socket IO模型,借用这个故事,讲解下linux的socket IO模型: 老陈有一个在外地工作的女儿,不能经常回来,老陈和她通过信件联系. 他 ...
- HDU3926Hand in Hand(搜索 或 并查集)
Problem Description In order to get rid of Conan, Kaitou KID disguises himself as a teacher in the k ...