关于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 ...
随机推荐
- msp430项目编程10
msp430中项目---电子密码锁 1.扫描键盘工作原理 2.电路原理说明 3.代码(显示部分) 4.代码(功能实现) 5.项目总结 msp430项目编程 msp430入门学习
- HTTP协议详解【转载】
Author :Jeffrey 引言 HTTP是一个属于应用层的面向对象的协议,由于其简捷.快速的方式,适用于分布式超媒体信息系统.它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展.目前 ...
- python之-- socket 基础篇
socket 网络模块 注意事项:在python3中,所有数据的传输必须用bytes类型(bytes只支持ascii码)所以在发送数据的时候要么在发送的字符串前面加 'b',要么使用encode('u ...
- CDN是什么与CDN加速的原理
CDN是什么 CDN全称:Content Delivery Network或Content Ddistribute Network,即内容分发网络 CDN设计思路 避让:尽可能避开互联网上有可能影响数 ...
- java-过滤器(Filter)
在javaweb开发中,项目中都会包含一些过滤器(Filter),主要用于web服务器对资源的管理控制,如静态资源文件.jsp页面访问等.我们可以使用过滤器实现一些特殊的功能,如常见的过滤敏感词汇(替 ...
- Spring中使用Log4j记录日志
以下内容引用自http://wiki.jikexueyuan.com/project/spring/logging-with-log4j.html: 例子: pom.xml: <project ...
- 【python】对象和面向对象
类的定义 python支持多重继承,在类名后面的小括号中,可以列出多个类名,以逗号分割. __init__方法在类的实例创建后被立即调用,注意与c++中构造函数不一样,因为对象在调用__init__时 ...
- Ribbon简介
Ribbon简介
- cocoapods应用第一部分-xcode创建.framework相关
问题的提出: 随着项目的越来越大,可能会出现好几个团队共同维护一个项目的情况,比如:项目组A负责当中的A块,项目组B负责当中的B块.....这几块彼此之间既独立,也相互联系.对于这样的情况,能够採用约 ...
- Android sdcard读写权限问题之中的一个
博主在刚刚在学习过程中发现了一个关于android往sdcard读写的问题, 配置了该配置的提示无读写权限. 在AndroidManifest.xml文件里配置清单例如以下 <manifest ...