提交 352e5b01 authored 作者: jianglw's avatar jianglw

添加组态相关功能

上级 4437cce1
package com.ruoyi.web.controller.topology;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.topology.TopologyData;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.core.websocket.WebSocketServer;
import com.ruoyi.topology.service.ITopologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
/**
* @author jianglw
* @version 1.0
* @date 2021/3/29 10:21
*/
@RestController
@RequestMapping("/topology")
public class IndexController extends BaseController {
@Value(("${ruoyi.profile}"))
private String profile;
@Autowired
private ITopologyService iTopologyService;
@Autowired
private WebSocketServer webSocketServer;
/**
* 保存组态数据
*
* @param topologyData
* @return AjaxResult
*/
@PostMapping("/save")
public AjaxResult save(@RequestBody TopologyData topologyData) throws IOException {
List<TopologyData> list =null;
TopologyData t=null;
if (topologyData.getId() == null) {
//将当前用的ID存入数据库,并返回组态id
topologyData.setUserId( SecurityUtils.getLoginUser().getUser().getUserId() );
iTopologyService.saveUserIdToId(topologyData ) ;
FileUtils.createdFile( topologyData.getId() + ".json", "", profile, JSONObject.toJSONString( topologyData.getData() ) );
return AjaxResult.success( topologyData );
}else{
t =iTopologyService.getTopologyById( topologyData.getId() );
if(t!=null){
FileUtils.createdFile( topologyData.getId() + ".json", "", profile, JSONObject.toJSONString( topologyData.getData() ) );
return AjaxResult.success( topologyData );
}
}
return AjaxResult.error( "保存失败,请检查id是否存在" );
}
@GetMapping("/preview")
public AjaxResult preview() {
TopologyData topologyData = new TopologyData();
topologyData.setUserId( SecurityUtils.getLoginUser().getUser().getUserId() );
List<TopologyData> list = iTopologyService.getTopology( topologyData );
return AjaxResult.success( list );
}
@GetMapping("/getTopology/{id}")
public AjaxResult getTopology(@PathVariable("id") Integer id) throws IOException {
TopologyData topologyData = new TopologyData();
topologyData.setId( id );
List<TopologyData> list = iTopologyService.getTopology( topologyData );
File file = null;
JSONObject json = null;
file = new File( profile + id + ".json" );
if (!file.exists()) {
throw new FileNotFoundException( profile + id + ".json" );
}
json = JSONObject.parseObject( FileUtils.readFileJson( file ) );
for (TopologyData t : list) {
t.setData( json );
}
return AjaxResult.success( list );
}
@DeleteMapping("/deleteTopology/{id}")
public AjaxResult deleteTopology(@PathVariable("id") Integer id) throws IOException {
return AjaxResult.success();
}
@GetMapping("/test")
public void test() throws IOException {
JSONObject jsonObject= JSON.parseObject( "{\n" +
" tag: 'numA', //tag节点\n" +
" fontColor: 'red', //数据颜色\n" +
" text: 'test', //文本内容\n" +
" }" );
webSocketServer.sendInfo(jsonObject.toJSONString() ,"1" );
}
}
package com.ruoyi.web.controller.topology;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/7 10:34
*/
@RestController
@RequestMapping("/params")
public class ParamsController {
}
...@@ -8,7 +8,7 @@ spring: ...@@ -8,7 +8,7 @@ spring:
master: master:
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root username: root
password: password password: root
# 从库数据源 # 从库数据源
slave: slave:
# 从数据源开关/默认关闭 # 从数据源开关/默认关闭
......
...@@ -130,3 +130,4 @@ xss: ...@@ -130,3 +130,4 @@ xss:
excludes: /system/notice/* excludes: /system/notice/*
# 匹配链接 # 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/* urlPatterns: /system/*,/monitor/*,/tool/*
...@@ -100,7 +100,16 @@ ...@@ -100,7 +100,16 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> </dependency>
<!-- websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- mqtt-->
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
<!-- pool 对象池 --> <!-- pool 对象池 -->
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
......
package com.ruoyi.common.core.domain.topology;
/**
* topology数据
* @author jianglw
* @version 1.0
* @date 2021/3/29 14:19
*/
public class TopologyData {
private Integer id;
private String name;
private Long userId;
private Object data;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
...@@ -6,6 +6,7 @@ import java.util.List; ...@@ -6,6 +6,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.HashOperations;
...@@ -18,10 +19,9 @@ import org.springframework.stereotype.Component; ...@@ -18,10 +19,9 @@ import org.springframework.stereotype.Component;
* *
* @author ruoyi * @author ruoyi
**/ **/
@SuppressWarnings(value = { "unchecked", "rawtypes" }) @SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component @Component
public class RedisCache public class RedisCache {
{
@Autowired @Autowired
public RedisTemplate redisTemplate; public RedisTemplate redisTemplate;
...@@ -31,9 +31,8 @@ public class RedisCache ...@@ -31,9 +31,8 @@ public class RedisCache
* @param key 缓存的键值 * @param key 缓存的键值
* @param value 缓存的值 * @param value 缓存的值
*/ */
public <T> void setCacheObject(final String key, final T value) public <T> void setCacheObject(final String key, final T value) {
{ redisTemplate.opsForValue().set( key, value );
redisTemplate.opsForValue().set(key, value);
} }
/** /**
...@@ -44,9 +43,8 @@ public class RedisCache ...@@ -44,9 +43,8 @@ public class RedisCache
* @param timeout 时间 * @param timeout 时间
* @param timeUnit 时间颗粒度 * @param timeUnit 时间颗粒度
*/ */
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
{ redisTemplate.opsForValue().set( key, value, timeout, timeUnit );
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
} }
/** /**
...@@ -56,9 +54,8 @@ public class RedisCache ...@@ -56,9 +54,8 @@ public class RedisCache
* @param timeout 超时时间 * @param timeout 超时时间
* @return true=设置成功;false=设置失败 * @return true=设置成功;false=设置失败
*/ */
public boolean expire(final String key, final long timeout) public boolean expire(final String key, final long timeout) {
{ return expire( key, timeout, TimeUnit.SECONDS );
return expire(key, timeout, TimeUnit.SECONDS);
} }
/** /**
...@@ -69,9 +66,8 @@ public class RedisCache ...@@ -69,9 +66,8 @@ public class RedisCache
* @param unit 时间单位 * @param unit 时间单位
* @return true=设置成功;false=设置失败 * @return true=设置成功;false=设置失败
*/ */
public boolean expire(final String key, final long timeout, final TimeUnit unit) public boolean expire(final String key, final long timeout, final TimeUnit unit) {
{ return redisTemplate.expire( key, timeout, unit );
return redisTemplate.expire(key, timeout, unit);
} }
/** /**
...@@ -80,10 +76,9 @@ public class RedisCache ...@@ -80,10 +76,9 @@ public class RedisCache
* @param key 缓存键值 * @param key 缓存键值
* @return 缓存键值对应的数据 * @return 缓存键值对应的数据
*/ */
public <T> T getCacheObject(final String key) public <T> T getCacheObject(final String key) {
{
ValueOperations<String, T> operation = redisTemplate.opsForValue(); ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key); return operation.get( key );
} }
/** /**
...@@ -91,9 +86,8 @@ public class RedisCache ...@@ -91,9 +86,8 @@ public class RedisCache
* *
* @param key * @param key
*/ */
public boolean deleteObject(final String key) public boolean deleteObject(final String key) {
{ return redisTemplate.delete( key );
return redisTemplate.delete(key);
} }
/** /**
...@@ -102,9 +96,8 @@ public class RedisCache ...@@ -102,9 +96,8 @@ public class RedisCache
* @param collection 多个对象 * @param collection 多个对象
* @return * @return
*/ */
public long deleteObject(final Collection collection) public long deleteObject(final Collection collection) {
{ return redisTemplate.delete( collection );
return redisTemplate.delete(collection);
} }
/** /**
...@@ -114,9 +107,8 @@ public class RedisCache ...@@ -114,9 +107,8 @@ public class RedisCache
* @param dataList 待缓存的List数据 * @param dataList 待缓存的List数据
* @return 缓存的对象 * @return 缓存的对象
*/ */
public <T> long setCacheList(final String key, final List<T> dataList) public <T> long setCacheList(final String key, final List<T> dataList) {
{ Long count = redisTemplate.opsForList().rightPushAll( key, dataList );
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count; return count == null ? 0 : count;
} }
...@@ -126,9 +118,8 @@ public class RedisCache ...@@ -126,9 +118,8 @@ public class RedisCache
* @param key 缓存的键值 * @param key 缓存的键值
* @return 缓存键值对应的数据 * @return 缓存键值对应的数据
*/ */
public <T> List<T> getCacheList(final String key) public <T> List<T> getCacheList(final String key) {
{ return redisTemplate.opsForList().range( key, 0, -1 );
return redisTemplate.opsForList().range(key, 0, -1);
} }
/** /**
...@@ -138,13 +129,11 @@ public class RedisCache ...@@ -138,13 +129,11 @@ public class RedisCache
* @param dataSet 缓存的数据 * @param dataSet 缓存的数据
* @return 缓存数据的对象 * @return 缓存数据的对象
*/ */
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
{ BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps( key );
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator(); Iterator<T> it = dataSet.iterator();
while (it.hasNext()) while (it.hasNext()) {
{ setOperation.add( it.next() );
setOperation.add(it.next());
} }
return setOperation; return setOperation;
} }
...@@ -155,9 +144,8 @@ public class RedisCache ...@@ -155,9 +144,8 @@ public class RedisCache
* @param key * @param key
* @return * @return
*/ */
public <T> Set<T> getCacheSet(final String key) public <T> Set<T> getCacheSet(final String key) {
{ return redisTemplate.opsForSet().members( key );
return redisTemplate.opsForSet().members(key);
} }
/** /**
...@@ -166,10 +154,9 @@ public class RedisCache ...@@ -166,10 +154,9 @@ public class RedisCache
* @param key * @param key
* @param dataMap * @param dataMap
*/ */
public <T> void setCacheMap(final String key, final Map<String, T> dataMap) public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
{
if (dataMap != null) { if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap); redisTemplate.opsForHash().putAll( key, dataMap );
} }
} }
...@@ -179,9 +166,8 @@ public class RedisCache ...@@ -179,9 +166,8 @@ public class RedisCache
* @param key * @param key
* @return * @return
*/ */
public <T> Map<String, T> getCacheMap(final String key) public <T> Map<String, T> getCacheMap(final String key) {
{ return redisTemplate.opsForHash().entries( key );
return redisTemplate.opsForHash().entries(key);
} }
/** /**
...@@ -191,9 +177,8 @@ public class RedisCache ...@@ -191,9 +177,8 @@ public class RedisCache
* @param hKey Hash键 * @param hKey Hash键
* @param value 值 * @param value 值
*/ */
public <T> void setCacheMapValue(final String key, final String hKey, final T value) public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
{ redisTemplate.opsForHash().put( key, hKey, value );
redisTemplate.opsForHash().put(key, hKey, value);
} }
/** /**
...@@ -203,10 +188,9 @@ public class RedisCache ...@@ -203,10 +188,9 @@ public class RedisCache
* @param hKey Hash键 * @param hKey Hash键
* @return Hash中的对象 * @return Hash中的对象
*/ */
public <T> T getCacheMapValue(final String key, final String hKey) public <T> T getCacheMapValue(final String key, final String hKey) {
{
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash(); HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey); return opsForHash.get( key, hKey );
} }
/** /**
...@@ -216,9 +200,8 @@ public class RedisCache ...@@ -216,9 +200,8 @@ public class RedisCache
* @param hKeys Hash键集合 * @param hKeys Hash键集合
* @return Hash对象集合 * @return Hash对象集合
*/ */
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
{ return redisTemplate.opsForHash().multiGet( key, hKeys );
return redisTemplate.opsForHash().multiGet(key, hKeys);
} }
/** /**
...@@ -227,8 +210,7 @@ public class RedisCache ...@@ -227,8 +210,7 @@ public class RedisCache
* @param pattern 字符串前缀 * @param pattern 字符串前缀
* @return 对象列表 * @return 对象列表
*/ */
public Collection<String> keys(final String pattern) public Collection<String> keys(final String pattern) {
{ return redisTemplate.keys( pattern );
return redisTemplate.keys(pattern);
} }
} }
package com.ruoyi.common.core.websocket;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/2 10:03
*/
@ServerEndpoint("/imserver/{topologyId}")
@Component
public class WebSocketServer {
private static final Logger log = LoggerFactory.getLogger( WebSocketServer.class);
/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
private static int onlineCount = 0;
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private Session session;
/**接收topologyId*/
private String topologyId="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("topologyId") String topologyId) {
this.session = session;
this.topologyId=topologyId;
if(webSocketMap.containsKey(topologyId)){
webSocketMap.remove(topologyId);
webSocketMap.put(topologyId,this);
//加入set中
}else{
webSocketMap.put(topologyId,this);
//加入set中
addOnlineCount();
//在线数加1
}
log.info("用户连接:"+topologyId+",当前在线人数为:" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:"+topologyId+",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if(webSocketMap.containsKey(topologyId)){
webSocketMap.remove(topologyId);
//从set中删除
subOnlineCount();
}
log.info("用户退出:"+topologyId+",当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户消息:"+topologyId+",报文:"+message);
//可以群发消息
//消息保存到数据库、redis
if(StringUtils.isNotBlank(message)){
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId",this.topologyId);
String toUserId=jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
}else{
log.error("请求的userId:"+toUserId+"不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
}catch (Exception e){
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.topologyId+",原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送自定义消息
* */
public static void sendInfo(String message,@PathParam("topologyId") String topologyId) throws IOException {
log.info("发送消息到:"+topologyId+",报文:"+message);
if(StringUtils.isNotBlank(topologyId)&&webSocketMap.containsKey(topologyId)){
webSocketMap.get(topologyId).sendMessage(message);
}else{
log.error("用户"+topologyId+",不在线!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
package com.ruoyi.common.enums;
import com.ruoyi.common.handlefile.HandleFile;
import com.ruoyi.common.topology.collect.*;
/**
* 获取topology
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:31
*/
public enum CollectTopology {
/**
* mysql
*/
MYSQL(0,new MysqlType() ),
/**
* redis
*/
REDIS(3,new RedisType() ),
/**
* influxdb
*/
INFLUXDB(2,new InfluxdbType() ),
/**
* shareserver
*/
SHARESERVER(4,new ShareServerType() );
public int i;
public CollectTopologyType collectTopologyType;
CollectTopology(int i, CollectTopologyType collectTopologyType) {
this.i=i;
this.collectTopologyType=collectTopologyType;
}
//匹配
public static CollectTopologyType match(int i){
CollectTopology[] values = CollectTopology.values();
for (CollectTopology value : values) {
if(value.i==i){
return value.collectTopologyType;
}
}
return null;
}
}
package com.ruoyi.common.topology.change;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/10 11:20
*/
public class Change {
public List<Map<String,Object>> assemble(Map<String,Object> map, JSONObject jsonObject){
TopologyChange topologyChange=jsonObject.toJavaObject( TopologyChange.class );
return null;
}
}
package com.ruoyi.common.topology.change;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/10 11:09
*/
public class Handle {
private String type;
private String point;
private Boolean judge;
private String pointValue;
private String changeValue;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoint() {
return point;
}
public void setPoint(String point) {
this.point = point;
}
public Boolean getJudge() {
return judge;
}
public void setJudge(Boolean judge) {
this.judge = judge;
}
public String getPointValue() {
return pointValue;
}
public void setPointValue(String pointValue) {
this.pointValue = pointValue;
}
public String getChangeValue() {
return changeValue;
}
public void setChangeValue(String changeValue) {
this.changeValue = changeValue;
}
}
package com.ruoyi.common.topology.change;
import java.util.List;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/10 11:07
*/
public class TopologyChange {
private String tag;
private Integer type;
private List<Handle> handle;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public List<Handle> getHandle() {
return handle;
}
public void setHandle(List<Handle> handle) {
this.handle = handle;
}
}
package com.ruoyi.common.topology.collect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 9:55
*/
public interface CollectTopologyType {
public Map<String,Object> getData(String param);
}
package com.ruoyi.common.topology.collect;
import com.alibaba.fastjson.JSONArray;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:29
*/
public class InfluxdbType implements CollectTopologyType {
@Override
public Map<String,Object> getData(String param) {
return null;
}
}
package com.ruoyi.common.topology.collect;
import com.alibaba.fastjson.JSONArray;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 9:57
*/
public class MysqlType implements CollectTopologyType {
@Override
public Map<String,Object> getData(String param) {
return null;
}
}
package com.ruoyi.common.topology.collect;
import com.alibaba.fastjson.JSONArray;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 9:57
*/
public class RedisType implements CollectTopologyType {
@Override
public Map<String,Object> getData(String param) {
return null;
}
}
package com.ruoyi.common.topology.collect;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:34
*/
public class ShareServerType implements CollectTopologyType {
@Override
public Map<String,Object> getData(String param) {
return null;
}
}
...@@ -87,4 +87,9 @@ public class SecurityUtils ...@@ -87,4 +87,9 @@ public class SecurityUtils
{ {
return userId != null && 1L == userId; return userId != null && 1L == userId;
} }
public static void main(String[] args) {
System.out.println(SecurityUtils.encryptPassword( "admin123" ));
System.out.println(SecurityUtils.matchesPassword( "admin123","$2a$10$23g1JY0bPoREJxgkO58x6emua2sxEKrdTAnyO9CYCzXJupHqQwbIu" ));
}
} }
...@@ -36,6 +36,18 @@ public class FileUtils extends org.apache.commons.io.FileUtils { ...@@ -36,6 +36,18 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
reader.close(); reader.close();
return sb.toString(); return sb.toString();
} }
public static String readFileJson(File file) throws IOException {
InputStream inputStream =new FileInputStream( file ) ;
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8 );
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
inputStream.close();
reader.close();
return sb.toString();
}
/** /**
* 输出指定文件的byte数组 * 输出指定文件的byte数组
......
...@@ -50,7 +50,7 @@ public class RsaUtils { ...@@ -50,7 +50,7 @@ public class RsaUtils {
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA"); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey); cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] bytesContent = Base64.decodeBase64(text.getBytes()); byte[] bytesContent = Base64.decodeBase64(text.getBytes(StandardCharsets.UTF_8));
int inputLen = bytesContent.length; int inputLen = bytesContent.length;
int offLen = 0; int offLen = 0;
int i = 0; int i = 0;
...@@ -86,7 +86,7 @@ public class RsaUtils { ...@@ -86,7 +86,7 @@ public class RsaUtils {
Cipher cipher = Cipher.getInstance("RSA"); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey); cipher.init(Cipher.ENCRYPT_MODE, privateKey);
//分段加密 //分段加密
byte[] bytesContent = text.getBytes(); byte[] bytesContent = text.getBytes(StandardCharsets.UTF_8);
int inputLen = bytesContent.length; int inputLen = bytesContent.length;
int offLen = 0;//偏移量 int offLen = 0;//偏移量
int i = 0; int i = 0;
...@@ -120,7 +120,7 @@ public class RsaUtils { ...@@ -120,7 +120,7 @@ public class RsaUtils {
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA"); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey); cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytesContent = Base64.decodeBase64(text.getBytes()); byte[] bytesContent = Base64.decodeBase64(text.getBytes(StandardCharsets.UTF_8));
int inputLen = bytesContent.length; int inputLen = bytesContent.length;
int offLen = 0; int offLen = 0;
int i = 0; int i = 0;
...@@ -155,7 +155,7 @@ public class RsaUtils { ...@@ -155,7 +155,7 @@ public class RsaUtils {
Cipher cipher = Cipher.getInstance("RSA"); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey); cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//分段加密 //分段加密
byte[] bytesContent = text.getBytes(); byte[] bytesContent = text.getBytes(StandardCharsets.UTF_8);
int inputLen = bytesContent.length; int inputLen = bytesContent.length;
int offLen = 0;//偏移量 int offLen = 0;//偏移量
int i = 0; int i = 0;
......
...@@ -28,6 +28,8 @@ ...@@ -28,6 +28,8 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId> <artifactId>spring-boot-starter-aop</artifactId>
</dependency> </dependency>
<!-- SpringBoot mail --> <!-- SpringBoot mail -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
......
...@@ -106,6 +106,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter ...@@ -106,6 +106,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
"/**/*.js" "/**/*.js"
).permitAll() ).permitAll()
.antMatchers("/profile/**").anonymous() .antMatchers("/profile/**").anonymous()
.antMatchers( "/topology/**" ).anonymous()
.antMatchers( "/imserver/**" ).anonymous()
.antMatchers( "/sendMqttMessage" ).anonymous()
.antMatchers("/common/download**").anonymous() .antMatchers("/common/download**").anonymous()
.antMatchers("/common/download/resource**").anonymous() .antMatchers("/common/download/resource**").anonymous()
.antMatchers("/swagger-ui.html").anonymous() .antMatchers("/swagger-ui.html").anonymous()
......
package com.ruoyi.framework.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
*
* @author jianglw
* @version 1.0
* @date 2021/4/2 10:00
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.ruoyi.quartz.task;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.websocket.WebSocketServer;
import com.ruoyi.common.enums.CollectTopology;
import com.ruoyi.common.topology.collect.CollectTopologyType;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/8 14:25
*/
@Component("topologyTask")
public class TopologyTask {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
WebSocketServer webSocketServer;
private static final Logger log = LoggerFactory.getLogger( TopologyTask.class );
/**
* 无参
*/
public void topologyParams() {
log.info( "无参" );
}
/**
* 一个参数
*
* @param data
*/
public void topologyParams(String data) {
log.info( "一个参数,{}", data );
if (StringUtils.isNotEmpty( data ) && stringRedisTemplate.hasKey( data )) {
String top = stringRedisTemplate.opsForValue().get( data );
JSONObject jsonObject = JSONObject.parseObject( top );
JSONObject topologyHandle =JSONObject.parseObject( jsonObject.get( "topologyHandle" ).toString() );
Integer dataAcquisition =topologyHandle.getInteger( "dataAcquisitionMode" );
/**
* 获取数据
*/
CollectTopologyType collectTopologyType=CollectTopology.match( dataAcquisition );
assert collectTopologyType != null;
Map<String,Object> stringObjectMap = collectTopologyType.getData( "" );
/**
* 配置数据
*/
/**
* mqtt与socket
*/
if (StringUtils.isNotEmpty( jsonObject.getString( "socket" ) )) {
String webSocket = jsonObject.getString( "socket" );
try {
webSocketServer.sendInfo( "", webSocket.substring( webSocket.lastIndexOf( "/" ), webSocket.length() ) );
} catch (IOException e) {
log.error( "websocket连接失败" );
e.printStackTrace();
}
} else {
}
}
}
/**
* 多个参数
*
* @param data
* @param data1
* @param data2
* @param data3
*/
public void topologyParams(String data, Integer data1, Boolean data2, Double data3) {
log.info( "多个参数,{},{},{},{}", data, data1, data2, data3 );
}
}
package com.ruoyi.topology.mapper;
import com.ruoyi.common.core.domain.topology.TopologyData;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author jianglw
* @version 1.0
* @date 2021/3/29 16:30
*/
public interface TopologyMapper {
void saveUserIdToId(TopologyData topologyData);
List<TopologyData> getTopology(TopologyData topologyData);
TopologyData getTopologyById(Integer id);
}
package com.ruoyi.topology.service;
import com.ruoyi.common.core.domain.topology.TopologyData;
import java.util.List;
/**
* @author jianglw
* @version 1.0
* @date 2021/3/29 15:00
*/
public interface ITopologyService {
void saveUserIdToId(TopologyData topologyData);
List<TopologyData> getTopology(TopologyData topologyData);
TopologyData getTopologyById(Integer id);
}
package com.ruoyi.topology.service.impl;
import com.ruoyi.common.core.domain.topology.TopologyData;
import com.ruoyi.topology.mapper.TopologyMapper;
import com.ruoyi.topology.service.ITopologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author jianglw
* @version 1.0
* @date 2021/3/29 15:01
*/
@Service
public class TopologyService implements ITopologyService {
@Autowired
private TopologyMapper topologyMapper;
@Override
public void saveUserIdToId(TopologyData topologyData) {
topologyMapper.saveUserIdToId(topologyData);
}
@Override
public List<TopologyData> getTopology(TopologyData topologyData) {
return topologyMapper.getTopology(topologyData);
}
@Override
public TopologyData getTopologyById(Integer id) {
return topologyMapper.getTopologyById(id);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.topology.mapper.TopologyMapper">
<insert id="saveUserIdToId" parameterType="com.ruoyi.common.core.domain.topology.TopologyData" useGeneratedKeys="true" keyProperty="id">
insert into topology_user (user_id) values (#{userId})
</insert>
<select id="getTopology" parameterType="com.ruoyi.common.core.domain.topology.TopologyData" resultType="com.ruoyi.common.core.domain.topology.TopologyData">
select id,user_id as userId from topology_user
<where>
<if test="userId !=null and userId!=''">and user_id = #{userId}</if>
<if test="id !=null and id!=''">and id = #{id}</if>
</where>
</select>
<select id="getTopologyById" resultType="com.ruoyi.common.core.domain.topology.TopologyData">
select id,user_id as userId from topology_user where id = #{id}
</select>
</mapper>
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论