diff options
| author | shizhendong <[email protected]> | 2021-01-06 16:40:51 +0800 |
|---|---|---|
| committer | shizhendong <[email protected]> | 2021-01-06 16:40:51 +0800 |
| commit | ec821f483a41532e00b94e0adc20f7fdf99b7b4d (patch) | |
| tree | 9ac57121ac4b3497abf510eb98fd52039afc6dd4 | |
| parent | dc5db6094dbdd1c4c31f838909758ca09a69507c (diff) | |
fix: EAL4: 代码合并
1. EAL4: 代码合并
2. 合并代码产生Bug修复
40 files changed, 319 insertions, 1975 deletions
@@ -330,6 +330,11 @@ <artifactId>snmp4j</artifactId>
<version>2.6.2</version>
</dependency>
+ <dependency>
+ <groupId>cn.hutool</groupId>
+ <artifactId>hutool-all</artifactId>
+ <version>5.5.2</version>
+ </dependency>
</dependencies>
<build>
diff --git a/src/main/java/com/nis/NzConfagentApplication.java b/src/main/java/com/nis/NzConfagentApplication.java index 0237694..4e668e0 100644 --- a/src/main/java/com/nis/NzConfagentApplication.java +++ b/src/main/java/com/nis/NzConfagentApplication.java @@ -1,11 +1,11 @@ package com.nis;
+import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
-import io.micrometer.core.instrument.MeterRegistry;
@SpringBootApplication
public class NzConfagentApplication {
diff --git a/src/main/java/com/nis/controller/HealthyController.java b/src/main/java/com/nis/controller/HealthyController.java index d1bb69e..0a52880 100644 --- a/src/main/java/com/nis/controller/HealthyController.java +++ b/src/main/java/com/nis/controller/HealthyController.java @@ -1,11 +1,11 @@ package com.nis.controller;
-import java.util.HashMap;
-import java.util.Map;
-
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
+import java.util.HashMap;
+import java.util.Map;
+
@RestController
public class HealthyController{
diff --git a/src/main/java/com/nis/controller/MetricsController.java b/src/main/java/com/nis/controller/MetricsController.java index fe17e73..33d5a61 100644 --- a/src/main/java/com/nis/controller/MetricsController.java +++ b/src/main/java/com/nis/controller/MetricsController.java @@ -1,15 +1,13 @@ package com.nis.controller;
+import com.nis.entity.ConfagentMetrics;
+import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
-import com.nis.entity.ConfagentMetrics;
-
-import io.micrometer.core.instrument.MeterRegistry;
-
@RestController
public class MetricsController{
@Autowired
diff --git a/src/main/java/com/nis/controller/TrafficController.java b/src/main/java/com/nis/controller/TrafficController.java index 0b032f8..8529587 100644 --- a/src/main/java/com/nis/controller/TrafficController.java +++ b/src/main/java/com/nis/controller/TrafficController.java @@ -1,7 +1,7 @@ package com.nis.controller; +import cn.hutool.log.Log; import com.nis.service.TrafficService; -import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -13,9 +13,9 @@ import org.springframework.web.bind.annotation.RestController; * @version: 1.0 */ @RestController -@Slf4j +//@Slf4j public class TrafficController { - + private Log log = Log.get(); @Autowired private TrafficService trafficService; diff --git a/src/main/java/com/nis/dao/AlertRuleDao.java b/src/main/java/com/nis/dao/AlertRuleDao.java index 9accd18..8966932 100644 --- a/src/main/java/com/nis/dao/AlertRuleDao.java +++ b/src/main/java/com/nis/dao/AlertRuleDao.java @@ -1,10 +1,9 @@ package com.nis.dao;
-import java.util.List;
-
+import com.nis.entity.AlertRule;
import org.apache.ibatis.annotations.Mapper;
-import com.nis.entity.AlertRule;
+import java.util.List;
@Mapper
public interface AlertRuleDao {
diff --git a/src/main/java/com/nis/dao/EndpointDao.java b/src/main/java/com/nis/dao/EndpointDao.java index 7ef31d7..cdabb87 100644 --- a/src/main/java/com/nis/dao/EndpointDao.java +++ b/src/main/java/com/nis/dao/EndpointDao.java @@ -1,11 +1,10 @@ package com.nis.dao;
-import java.util.List;
-
-import org.apache.ibatis.annotations.Mapper;
-
import com.nis.entity.Endpoint;
import com.nis.entity.MetricsDto;
+import org.apache.ibatis.annotations.Mapper;
+
+import java.util.List;
@Mapper
public interface EndpointDao {
diff --git a/src/main/java/com/nis/dao/PromserverDao.java b/src/main/java/com/nis/dao/PromserverDao.java index 640dd4d..906f072 100644 --- a/src/main/java/com/nis/dao/PromserverDao.java +++ b/src/main/java/com/nis/dao/PromserverDao.java @@ -1,11 +1,10 @@ package com.nis.dao;
-import java.util.List;
-
+import com.nis.entity.Promserver;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
-import com.nis.entity.Promserver;
+import java.util.List;
@Mapper
public interface PromserverDao {
diff --git a/src/main/java/com/nis/dao/SysConfigDao.java b/src/main/java/com/nis/dao/SysConfigDao.java index 2a6dba7..cd3b67c 100644 --- a/src/main/java/com/nis/dao/SysConfigDao.java +++ b/src/main/java/com/nis/dao/SysConfigDao.java @@ -1,10 +1,9 @@ package com.nis.dao;
-import java.util.List;
-
+import com.nis.entity.SysConfig;
import org.apache.ibatis.annotations.Mapper;
-import com.nis.entity.SysConfig;
+import java.util.List;
@Mapper
public interface SysConfigDao {
diff --git a/src/main/java/com/nis/entity/AlertRule.java b/src/main/java/com/nis/entity/AlertRule.java index c510f3e..303997a 100644 --- a/src/main/java/com/nis/entity/AlertRule.java +++ b/src/main/java/com/nis/entity/AlertRule.java @@ -61,52 +61,4 @@ public class AlertRule implements Serializable{ public void setId(Integer id) {
this.id = id;
}
- public String getAlertName() {
- return alertName;
- }
- public void setAlertName(String alertName) {
- this.alertName = alertName;
- }
- public String getExpr() {
- return expr;
- }
- public void setExpr(String expr) {
- this.expr = expr;
- }
- public Integer getLast() {
- return last;
- }
- public void setLast(Integer last) {
- this.last = last;
- }
- public String getSeverity() {
- return severity;
- }
- public void setSeverity(String severity) {
- this.severity = severity;
- }
- public String getSummary() {
- return summary;
- }
- public void setSummary(String summary) {
- this.summary = summary;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public Integer getReceiver() {
- return receiver;
- }
- public void setReceiver(Integer receiver) {
- this.receiver = receiver;
- }
- public Boolean getBuildIn() {
- return buildIn;
- }
- public void setBuildIn(Boolean buildIn) {
- this.buildIn = buildIn;
- }
}
diff --git a/src/main/java/com/nis/entity/ConfagentMetrics.java b/src/main/java/com/nis/entity/ConfagentMetrics.java index 764ff35..e528ca9 100644 --- a/src/main/java/com/nis/entity/ConfagentMetrics.java +++ b/src/main/java/com/nis/entity/ConfagentMetrics.java @@ -1,21 +1,16 @@ package com.nis.entity;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
import com.nis.service.EndpointService;
-
-import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
-import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.binder.MeterBinder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Component
public class ConfagentMetrics implements MeterBinder {
diff --git a/src/main/java/com/nis/entity/TrapMessage.java b/src/main/java/com/nis/entity/TrapMessage.java index b69bd74..223ef75 100644 --- a/src/main/java/com/nis/entity/TrapMessage.java +++ b/src/main/java/com/nis/entity/TrapMessage.java @@ -1,13 +1,14 @@ package com.nis.entity;
+import cn.hutool.core.util.StrUtil;
+import org.snmp4j.PDU;
+import org.snmp4j.smi.Variable;
+
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
-import org.snmp4j.PDU;
-import org.snmp4j.smi.Variable;
-
public class TrapMessage implements Serializable{
private String agentSendIP;
@@ -43,7 +44,7 @@ public class TrapMessage implements Serializable{ for (int i = 0; i < trapPDUOIDs.size(); i++)
{
String s1 = (String)trapPDUOIDs.get(i);
- if (s.equals(s1))
+ if(StrUtil.equals(s,s1))
return (Variable)trapPDUOIDValues.get(i);
}
diff --git a/src/main/java/com/nis/job/ConfagentJob.java b/src/main/java/com/nis/job/ConfagentJob.java index a574639..c9fcc8d 100644 --- a/src/main/java/com/nis/job/ConfagentJob.java +++ b/src/main/java/com/nis/job/ConfagentJob.java @@ -1,5 +1,9 @@ package com.nis.job; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.ReflectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.log.Log; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; @@ -12,19 +16,20 @@ import com.nis.util.YamlUtil; import org.apache.commons.lang3.StringUtils; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; -import java.io.*; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -37,7 +42,7 @@ import java.util.stream.Collectors; */ @DisallowConcurrentExecution public class ConfagentJob extends QuartzJobBean { - private Logger logger = LoggerFactory.getLogger(ConfagentJob.class); + private Log logger = Log.get(); private static Map<String,Integer> confEvents=null; @Autowired private PromserverService promserverService; @@ -83,7 +88,7 @@ public class ConfagentJob extends QuartzJobBean { @SuppressWarnings("unchecked") @Override - protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + protected void executeInternal(JobExecutionContext context) { logger.info("task start"); @@ -134,17 +139,22 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); +// responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); + int port= Integer.parseInt(promServerPort); + String url = new URL("http", ipaddr, port, Constant.API_RELOAD).toString(); + responseEntity = ReflectUtil.invoke(restTemplate, "postForEntity", url, null, String.class, Collections.emptyMap()); } catch (RestClientException e) { logger.error("热加载 global prometheus api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + } catch (MalformedURLException e) { + logger.error(e); } + if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " global prometheus 热加载配置文件成功"); } } } catch (Exception e) { logger.error("yamlHanlde center error", e); - e.printStackTrace(); } } } else if (promserverType.equals(Constant.PromserverType.PER_DATACENTER.getValue())) {// datacenter角色 @@ -160,9 +170,14 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); +// responseEntity = ReflectUtil.invoke(restTemplate,"postForEntity",new UrlBuilder().setScheme("http").setHost(ipaddr).setPort(port).addPath(Constant.API_RELOAD).toString(), null, String.class);; + int port= Integer.parseInt(promServerPort); + String url = new URL("http", ipaddr, port, Constant.API_RELOAD).toString(); + responseEntity = ReflectUtil.invoke(restTemplate, "postForEntity", url, null, String.class, Collections.emptyMap()); } catch (RestClientException e) { logger.error("热加载 per-datacenter prometheus api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + } catch (MalformedURLException e) { + logger.error(e); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " per datacenter prometheus 热加载配置文件成功"); @@ -170,7 +185,6 @@ public class ConfagentJob extends QuartzJobBean { } } catch (Exception e) { logger.error("yamlHanlde sub error", e); - e.printStackTrace(); } } } @@ -198,7 +212,7 @@ public class ConfagentJob extends QuartzJobBean { } } catch (Exception e) { logger.error("prometheus global setting error : ", e); - e.printStackTrace(); + }**/ //prometheus启动项相关修改 每次需要判断是否更改来确定是否执行方法 会关闭prometheus并重启 confagent首次启动不会进行prometheus开关操作 @@ -210,7 +224,6 @@ public class ConfagentJob extends QuartzJobBean { logger.info("prometheus 配置本地保存天数" + (prometheusStartHandle ? "成功" : "失败")); } catch (Exception e) { logger.error("prometheus startup setting error : ", e); - e.printStackTrace(); } } else if (promserverType.equals(Constant.PromserverType.THANOS_RULE.getValue())) { // thanos rule 处理 @@ -226,9 +239,13 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); + int port= Integer.parseInt(promServerPort); + String url = new URL("http", ipaddr, port, Constant.API_RELOAD).toString(); + responseEntity = ReflectUtil.invoke(restTemplate, "postForEntity", url, null, String.class, Collections.emptyMap()); } catch (RestClientException e) { logger.error("热加载 thanos rule api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + } catch (MalformedURLException e) { + logger.error(e); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " thanos rule 热加载配置文件成功"); @@ -271,7 +288,7 @@ public class ConfagentJob extends QuartzJobBean { Integer index=null; if(!subInfos.isEmpty()) { for(int i=0;i<subInfos.size();i++) { - if(subInfos.get(i).getHost().equals(promserver.getHost())) { + if(StrUtil.equals(subInfos.get(i).getHost(),promserver.getHost())) { index=i; } } @@ -293,7 +310,7 @@ public class ConfagentJob extends QuartzJobBean { job.put("job_name", endpointInfos.get(m).getId()); job.put("metrics_path", endpointInfos.get(m).getPath()); List list=new ArrayList(); - if(StringUtils.isNotBlank(type)&&type.equals(ModuleTypeEnum.SNMP.getValue())) { + if(StringUtils.isNotBlank(type)&&StrUtil.equals(type,ModuleTypeEnum.SNMP.getValue())) { list.add(ipaddr+":"+snmpPort); job.put("metrics_path", "/snmp"); }else { @@ -333,7 +350,7 @@ public class ConfagentJob extends QuartzJobBean { job5.put("regex", "job"); job5.put("action", "labeldrop"); // 控制开关 是否保留instance标签 - if(instanceLabel.equals("0")) { + if(StrUtil.equals(instanceLabel,"0")) { Map job6=new LinkedHashMap(); job6.put("regex", "instance"); job6.put("action", "labeldrop"); @@ -345,7 +362,7 @@ public class ConfagentJob extends QuartzJobBean { // 配置metric_relabel_config // 控制开关 是否保留instance标签 - if(instanceLabel.equals("0")) { + if(StrUtil.equals(instanceLabel,"0")) { List list4 =new ArrayList(); Map job7 =new LinkedHashMap(); job7.put("regex", "instance"); @@ -353,7 +370,7 @@ public class ConfagentJob extends QuartzJobBean { list4.add(job7); job.put("metric_relabel_configs", list4); } - if(StringUtils.isNotBlank(type)&&type.equals(ModuleTypeEnum.HTTP.getValue())) { + if(StringUtils.isNotBlank(type)&&StrUtil.equals(type,ModuleTypeEnum.HTTP.getValue())) { //处理endpoint中param字段json串 请求参数 String param = endpointInfos.get(m).getParam(); Map params=null; @@ -369,7 +386,7 @@ public class ConfagentJob extends QuartzJobBean { if(params!=null) { job.put("params",params); } - }else if(StringUtils.isNotBlank(type)&&type.equals(ModuleTypeEnum.SNMP.getValue())) { + }else if(StringUtils.isNotBlank(type)&&StrUtil.equals(type,ModuleTypeEnum.SNMP.getValue())) { Map params=new LinkedHashMap(); List snmpL1=new ArrayList(); snmpL1.add(endpointInfos.get(m).getHost()+":"+endpointInfos.get(m).getPort()); @@ -394,9 +411,14 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, snmpPort, Constant.API_RELOAD), null, String.class); +// responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, snmpPort, Constant.API_RELOAD), null, String.class); + int port = Integer.parseInt(snmpPort); + String url = new URL("http", ipaddr, port, Constant.API_RELOAD).toString(); + responseEntity = ReflectUtil.invoke(restTemplate, "postForEntity", url, null, String.class, Collections.emptyMap()); } catch (RestClientException e) { logger.error("热加载 snmp_exporter api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, snmpPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + } catch (MalformedURLException e) { + logger.error(e); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { logger.info(String.format("http://%s:%s", ipaddr, snmpPort) + " snmp_exporter 热加载配置文件成功"); @@ -540,17 +562,17 @@ public class ConfagentJob extends QuartzJobBean { if(!sysConfigs.isEmpty()) { for(SysConfig sysconfig : sysConfigs) { - if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_API.getValue())) { + if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.ALERT_API.getValue())) { nezhaMetricsList2.add(sysconfig.getParamValue()); - }else if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_PATH_PREFIX.getValue())){ + }else if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.ALERT_PATH_PREFIX.getValue())){ nezhaMetrics.put("metrics_path", sysconfig.getParamValue()+metricsPath); - }else if(sysconfig.getParamKey().equals(AlertManagerEnum.CONFAGENT_PORT.getValue())) { + }else if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.CONFAGENT_PORT.getValue())) { for(String confagentIp : confagentIps) { confagentMetricsList2.add(confagentIp+":"+sysconfig.getParamValue()); } }/*else if(sysconfig.getParamKey().equals(AlertManagerEnum.CONFAGENT_API.getValue())) { confagentMetricsList2.add(sysconfig.getParamValue()); - }*/else if(sysconfig.getParamKey().equals(AlertManagerEnum.CONFAGENT_PATH.getValue())) { + }*/else if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.CONFAGENT_PATH.getValue())) { confagentMetrics.put("metrics_path", sysconfig.getParamValue()+metricsPath); } } @@ -657,7 +679,7 @@ public class ConfagentJob extends QuartzJobBean { //获取配置文件判断是否需要添加endpoint state告警 String endpointAlertPush = sysConfigService.queryValueByParamkey(Constant.ENDPOINT_ALERT_PUSH); - if (ObjectUtils.isNotEmpty(endpointAlertPush) && endpointAlertPush.equals("1")) { + if(ObjectUtils.isNotEmpty(endpointAlertPush) &&StrUtil.equals( endpointAlertPush,"1")) { String endpointAlert = sysConfigService.queryValueByParamkey(Constant.ENDPOINT_ALERT_RULE); Map endpointAlertMap = (Map) JSON.parse(endpointAlert); String alertName = (String) endpointAlertMap.get("alertName"); @@ -701,9 +723,9 @@ public class ConfagentJob extends QuartzJobBean { List alertData = new ArrayList(); if (!sysConfigs.isEmpty()) { for (SysConfig sysconfig : sysConfigs) { - if (sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_API.getValue())) { + if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.ALERT_API.getValue())) { alertData.add(sysconfig.getParamValue()); - } else if (sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_PATH_PREFIX.getValue())) { + } else if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.ALERT_PATH_PREFIX.getValue())) { staticConfigs.put("path_prefix", sysconfig.getParamValue()); } } @@ -787,8 +809,6 @@ public class ConfagentJob extends QuartzJobBean { * 定时任务中将promserver信息储存到redis中 */ public void savePromeserverInfoToRedis(Promserver promserver,List<Endpoint> endpoints) { - HashOperations opsForHash = redisTemplate.opsForHash(); - Set<Object> keys = redisTemplate.opsForHash().keys(Constant.ENDPOINT_PROM); if(endpoints!=null && endpoints.size()>0) { for(Endpoint endpointPromInfo : endpoints) { logger.debug("savePromeserverInfoToRedis"+endpointPromInfo.getId()+"--->"+JSON.toJSONString(promserver)); @@ -832,7 +852,7 @@ public class ConfagentJob extends QuartzJobBean { // 首先获取 启动项 配置文件路径 String startParameterConfigPath = this.startParameterConfigPath(filePath); logger.info("获取到的 prometheus 启动项配置文件地址是:" + startParameterConfigPath); - try (RandomAccessFile raf = new RandomAccessFile(new File(startParameterConfigPath), "rw");) { + try (RandomAccessFile raf = new RandomAccessFile(FileUtil.file(startParameterConfigPath), "rw");) { String readLine = null; long lastPoint = 0; //记住上一次的偏移量 String time=null; @@ -843,7 +863,7 @@ public class ConfagentJob extends QuartzJobBean { Pattern p = Pattern.compile("--storage.tsdb.retention.time=\\d*d"); Matcher m = p.matcher(readLine); while (m.find()) { - if (!"".equals(m.group())) { + if(!StrUtil.equals("",m.group())) { String result = m.group(); String str1=result.substring(0, result.indexOf("=")); String str2 = result.substring(str1.length()+1, result.length()); @@ -857,10 +877,12 @@ public class ConfagentJob extends QuartzJobBean { lastPoint = ponit; } // 判断本地的保存时间与数据库的设置时间是否一致 不一致则更新同步 - if(!time.equals(retentionDays)) { + if(!StrUtil.equals(time,retentionDays)) { logger.error("prometheus going to restart , local time is "+ time); - RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl stop prometheus"}); - RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl start prometheus"}); + /*RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl stop prometheus"}); + RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl start prometheus"});*/ + cn.hutool.core.util.RuntimeUtil.exec("systemctl stop prometheus"); + cn.hutool.core.util.RuntimeUtil.exec("systemctl start prometheus"); } flag=true; } catch (FileNotFoundException e) { @@ -873,7 +895,7 @@ public class ConfagentJob extends QuartzJobBean { private String startParameterConfigPath(String filePath) { String readLine = ""; - try (RandomAccessFile raf = new RandomAccessFile(new File(filePath), "rw");) { + try (RandomAccessFile raf = new RandomAccessFile(FileUtil.file(filePath), "rw");) { while ((readLine = raf.readLine()) != null) { if (readLine.startsWith("EnvironmentFile")) { break; @@ -884,7 +906,6 @@ public class ConfagentJob extends QuartzJobBean { readLine = split[1]; } } catch (FileNotFoundException e) { - e.printStackTrace(); logger.error("获取prometheus.services失败,未找到该文件,路径有误,错误信息是:"+e.getMessage(), e); } catch (IOException e) { logger.error("处理prometheus.service文件失败,错误信息是:"+e.getMessage(), e); diff --git a/src/main/java/com/nis/job/ConfagentJobConfig.java b/src/main/java/com/nis/job/ConfagentJobConfig.java index a338aa9..b4dba69 100644 --- a/src/main/java/com/nis/job/ConfagentJobConfig.java +++ b/src/main/java/com/nis/job/ConfagentJobConfig.java @@ -1,10 +1,6 @@ package com.nis.job;
-import org.quartz.CronScheduleBuilder;
-import org.quartz.JobBuilder;
-import org.quartz.JobDetail;
-import org.quartz.Trigger;
-import org.quartz.TriggerBuilder;
+import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
diff --git a/src/main/java/com/nis/job/ConfagentUptimeJob.java b/src/main/java/com/nis/job/ConfagentUptimeJob.java index fd3c050..e8beb80 100644 --- a/src/main/java/com/nis/job/ConfagentUptimeJob.java +++ b/src/main/java/com/nis/job/ConfagentUptimeJob.java @@ -1,12 +1,11 @@ package com.nis.job;
+import com.nis.entity.ConfagentMetrics;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
-import com.nis.entity.ConfagentMetrics;
-
public class ConfagentUptimeJob extends QuartzJobBean {
@Autowired
private ConfagentMetrics confagentMetrics;
diff --git a/src/main/java/com/nis/server/SNMPTrapServer.java b/src/main/java/com/nis/server/SNMPTrapServer.java index 73199e5..c47dcf4 100644 --- a/src/main/java/com/nis/server/SNMPTrapServer.java +++ b/src/main/java/com/nis/server/SNMPTrapServer.java @@ -1,53 +1,27 @@ package com.nis.server;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.annotation.PostConstruct;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.snmp4j.CommandResponder;
-import org.snmp4j.CommandResponderEvent;
-import org.snmp4j.MessageDispatcherImpl;
-import org.snmp4j.PDU;
-import org.snmp4j.PDUv1;
-import org.snmp4j.Snmp;
-import org.snmp4j.TransportMapping;
+import cn.hutool.core.util.StrUtil;
+import cn.hutool.log.Log;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.nis.entity.*;
+import com.nis.service.AlertRuleService;
+import com.nis.service.SysConfigService;
+import com.nis.util.DateUtil;
+import org.snmp4j.*;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
-import org.snmp4j.security.AuthMD5;
-import org.snmp4j.security.AuthSHA;
-import org.snmp4j.security.PrivAES128;
-import org.snmp4j.security.PrivAES192;
-import org.snmp4j.security.PrivAES256;
-import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
-import org.snmp4j.smi.Address;
-import org.snmp4j.smi.GenericAddress;
-import org.snmp4j.smi.OID;
-import org.snmp4j.smi.OctetString;
-import org.snmp4j.smi.TcpAddress;
-import org.snmp4j.smi.UdpAddress;
-import org.snmp4j.smi.Variable;
-import org.snmp4j.smi.VariableBinding;
+import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
-import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
@@ -56,23 +30,14 @@ import org.springframework.core.annotation.Order; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
-import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import com.nis.entity.AlertManagerEnum;
-import com.nis.entity.AlertRule;
-import com.nis.entity.ConfagentMetrics;
-import com.nis.entity.SysConfig;
-import com.nis.entity.TrapMessage;
-import com.nis.service.AlertRuleService;
-import com.nis.service.SysConfigService;
-import com.nis.util.DateUtil;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.text.SimpleDateFormat;
+import java.util.*;
@@ -91,8 +56,7 @@ import com.nis.util.DateUtil; @Component
@Order(1)
public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// implements CommandResponder, extends Service
- private static Logger logger = LoggerFactory.getLogger(SNMPTrapServer.class);
- private static SNMPTrapServer ts = null;
+ private static Log logger = Log.get();
@Value("${confagent.snmp.trapThredPoolSize}")
private String snmpTrapThredPoolSize;
@Value("${confagent.snmp.trapPort}")
@@ -107,11 +71,11 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp private ConfagentMetrics confagentMetrics;
@Override
- public void run(ApplicationArguments args) throws Exception {
+ public void run(ApplicationArguments args) throws IOException {
initServer();
}
- public void initServer() throws Exception{
+ public void initServer() throws IOException {
logger.info("snmpTrapThredPoolSize is {}",snmpTrapThredPoolSize);
ThreadPool threadPool = ThreadPool.create("Trap", Integer.valueOf(snmpTrapThredPoolSize));
logger.info("snmpTrapThredPoolSize is {}",snmpTrapThredPoolSize);
@@ -139,30 +103,7 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp snmp.addCommandResponder(this);
}
- private OID getAuthProtocol(String auth){
- if (auth.equals("MD5")) {
- return AuthMD5.ID;
- } else if (auth.equals("SHA")) {
- return AuthSHA.ID;
- }else{
- return null;
- }
- }
-
- private OID getPrivProtocol(String priv){
- if (priv.equals("DES")) {
- return PrivDES.ID;
- } else if ((priv.equals("AES128"))
- || (priv.equals("AES"))) {
- return PrivAES128.ID;
- } else if (priv.equals("AES192")) {
- return PrivAES192.ID;
- } else if (priv.equals("AES256")) {
- return PrivAES256.ID;
- }else{
- return null;
- }
- }
+
@@ -183,9 +124,9 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp List<SysConfig> sysConfigs = sysConfigService.queryList();
if(!sysConfigs.isEmpty()) {
for(SysConfig sysconfig : sysConfigs) {
- if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_API.getValue())) {
+ if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.ALERT_API.getValue())) {
alertApi=sysconfig.getParamValue();
- }else if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_PATH_PREFIX.getValue())){
+ }else if(StrUtil.equals(sysconfig.getParamKey(),AlertManagerEnum.ALERT_PATH_PREFIX.getValue())){
alertPathPrefix=sysconfig.getParamValue();
}
}
@@ -217,7 +158,6 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp trapmessageinfo.setTrapVersion(1);
String s1 = pduv1.getEnterprise().toString();
trapmessageinfo.setTrapOID(s1);
- String s2 = pduv1.getAgentAddress().toString();
trapmessageinfo.setPduAgentIP(s);
trapmessageinfo.setTrapV1SpecificType(pduv1.getSpecificTrap());
trapmessageinfo.setTrapV1GenericType(pduv1.getGenericTrap());
@@ -351,7 +291,6 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp // 将告警信息发送到web端处理
RestTemplate restTemplate=new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
- MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity =new HttpEntity(mess,headers);
@@ -375,7 +314,7 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp trapName = allTrapTypeDefine.get(variable1.toString()).toString();
return trapName;
}
-
+
void setOIDList(TrapMessage trapmessageinfo, PDU pdu)
{
Vector vector = pdu.getVariableBindings();
@@ -402,58 +341,10 @@ public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// imp }
- /** */
- /**
- * 解决snmp4j中文乱码问题
- */
- public static String getChinese(String octetString) {
- try {
- String[] temps = octetString.split(":");
- byte[] bs = new byte[temps.length];
- for (int i = 0; i < temps.length; i++)
- bs[i] = (byte) Integer.parseInt(temps[i], 16);
-
- return new String(bs, "GB2312");
- } catch (Exception e) {
- return null;
- }
- }
-
- /*protected static String printVariableBindings(PDU response) {
- String strCom = "";
- for (int i = 0; i < response.size(); i++) {
- VariableBinding vb = response.get(i);
- String[] str = vb.getVariable().toString().toUpperCase().split(":");
-
- String strOut = "";
- int intLength = str.length;
- System.out.println("长度==> " + intLength);
- for (int j = 0; j < intLength; j++) {
- strOut += str[j];
- }
- strCom += vb.getVariable();
- if (str.length != 1) {
- System.out.println("==第行=vb.getVariable()=" + SNMPTrapServer.toStringHex(strOut));//显示中文
- }
- }
- return strCom;
- }*/
-
/**
* 将十进六制转换成为中文
*/
private static String hexString = "0123456789ABCDEF";
- public static String toStringHex(String bytes) {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream(
- bytes.length() / 2);
- //将每2位16进制整数组装成一个字节
- for (int i = 0; i < bytes.length(); i += 2) {
- baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
- .indexOf(bytes.charAt(i + 1))));
- }
- return new String(baos.toByteArray());
- }
}
diff --git a/src/main/java/com/nis/service/AlertRuleService.java b/src/main/java/com/nis/service/AlertRuleService.java index 0c490d8..f361e28 100644 --- a/src/main/java/com/nis/service/AlertRuleService.java +++ b/src/main/java/com/nis/service/AlertRuleService.java @@ -1,10 +1,8 @@ package com.nis.service;
-import java.util.List;
-import java.util.Map;
-
import com.nis.entity.AlertRule;
-import com.nis.entity.ConfEvent;
+
+import java.util.List;
public interface AlertRuleService {
diff --git a/src/main/java/com/nis/service/EndpointService.java b/src/main/java/com/nis/service/EndpointService.java index 438b2a9..c248ce0 100644 --- a/src/main/java/com/nis/service/EndpointService.java +++ b/src/main/java/com/nis/service/EndpointService.java @@ -1,10 +1,9 @@ package com.nis.service;
-import java.util.List;
-
import com.nis.entity.Endpoint;
import com.nis.entity.MetricsDto;
-import com.nis.entity.Promserver;
+
+import java.util.List;
public interface EndpointService {
diff --git a/src/main/java/com/nis/service/PromserverService.java b/src/main/java/com/nis/service/PromserverService.java index 46cb2f7..75cf422 100644 --- a/src/main/java/com/nis/service/PromserverService.java +++ b/src/main/java/com/nis/service/PromserverService.java @@ -1,9 +1,9 @@ package com.nis.service;
-import java.util.List;
-
import com.nis.entity.Promserver;
+import java.util.List;
+
public interface PromserverService {
public List<Promserver> queryList();
diff --git a/src/main/java/com/nis/service/SysConfigService.java b/src/main/java/com/nis/service/SysConfigService.java index 65ee610..449c6a0 100644 --- a/src/main/java/com/nis/service/SysConfigService.java +++ b/src/main/java/com/nis/service/SysConfigService.java @@ -1,8 +1,9 @@ package com.nis.service;
-import java.util.List;
import com.nis.entity.SysConfig;
+import java.util.List;
+
public interface SysConfigService {
public List<SysConfig> queryList();
diff --git a/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java b/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java index c7a87c2..5f9f9d8 100644 --- a/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java +++ b/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java @@ -1,13 +1,12 @@ package com.nis.service.impl;
-import java.util.List;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
import com.nis.dao.AlertRuleDao;
import com.nis.entity.AlertRule;
import com.nis.service.AlertRuleService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
@Service
public class AlertRuleServiceImpl implements AlertRuleService {
diff --git a/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java b/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java index d195aff..9b28289 100644 --- a/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java +++ b/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java @@ -1,16 +1,14 @@ package com.nis.service.impl;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import com.alibaba.fastjson.JSON;
import com.nis.dao.ConfEventDao;
import com.nis.entity.ConfEvent;
import com.nis.service.ConfEventService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Service
public class ConfEventServiceImpl implements ConfEventService {
@@ -46,7 +44,7 @@ public class ConfEventServiceImpl implements ConfEventService { }
List<ConfEvent> datas = confEventDao.selectList();
for(ConfEvent data:datas) {
- if(!(data.getValue().equals(map.get(data.getTable())))) {
+ if(!data.getValue().equals(map.get(data.getTable()))) {
flag = true;
}
}
diff --git a/src/main/java/com/nis/service/impl/EndpointServiceImpl.java b/src/main/java/com/nis/service/impl/EndpointServiceImpl.java index 6542a6d..ed99e84 100644 --- a/src/main/java/com/nis/service/impl/EndpointServiceImpl.java +++ b/src/main/java/com/nis/service/impl/EndpointServiceImpl.java @@ -1,15 +1,13 @@ package com.nis.service.impl;
-import java.util.List;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
import com.nis.dao.EndpointDao;
import com.nis.entity.Endpoint;
import com.nis.entity.MetricsDto;
-import com.nis.entity.Promserver;
import com.nis.service.EndpointService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
@Service
public class EndpointServiceImpl implements EndpointService{
@Autowired
diff --git a/src/main/java/com/nis/service/impl/PromserverServiceImpl.java b/src/main/java/com/nis/service/impl/PromserverServiceImpl.java index a20b2ef..c8cf565 100644 --- a/src/main/java/com/nis/service/impl/PromserverServiceImpl.java +++ b/src/main/java/com/nis/service/impl/PromserverServiceImpl.java @@ -1,5 +1,6 @@ package com.nis.service.impl;
+import cn.hutool.core.util.StrUtil;
import com.nis.dao.PromserverDao;
import com.nis.entity.Promserver;
import com.nis.service.PromserverService;
@@ -47,7 +48,7 @@ public class PromserverServiceImpl implements PromserverService { }
Promserver promserver = promservers.get(0);
- if (promserver.getHost().equals(ipaddr) && promserver.getPort().toString().equals(promServerPort)) {
+ if(StrUtil.equals(promserver.getHost(),ipaddr) && StrUtil.equals(promserver.getPort().toString(),promServerPort)) {
return true;
}
return false;
diff --git a/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java b/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java index 404a558..ccb0994 100644 --- a/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java +++ b/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java @@ -1,13 +1,12 @@ package com.nis.service.impl;
-import java.util.List;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
import com.nis.dao.SysConfigDao;
import com.nis.entity.SysConfig;
import com.nis.service.SysConfigService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
@Service
public class SysConfigServiceImpl implements SysConfigService {
diff --git a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java index 7c26e5e..976a721 100644 --- a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java +++ b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java @@ -1,12 +1,13 @@ package com.nis.service.impl; +import cn.hutool.core.util.StrUtil; +import cn.hutool.log.Log; import com.alibaba.fastjson.JSONObject; import com.nis.dao.TrafficDao; import com.nis.entity.Traffic; import com.nis.service.TrafficService; import com.nis.util.Constant; import com.nis.util.SnmpUtil; -import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -28,9 +29,9 @@ import java.util.stream.Collectors; */ @Service -@Slf4j +//@Slf4j public class TrafficServiceImpl implements TrafficService { - + private Log log = Log.get(); private static ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); @Value("${confagent.snmp.scrapeTimeOut}") @@ -94,7 +95,7 @@ public class TrafficServiceImpl implements TrafficService { continue; } - if (index.equals(traffic.getIfIndex().toString())) { + if(StrUtil.equals(index,traffic.getIfIndex().toString())) { // ifSpecific已过时 if (name.contains("ifSpecific")) continue; if (trafficDirection.contains(Constant.TRAFFIC_RX)) { @@ -110,7 +111,8 @@ public class TrafficServiceImpl implements TrafficService { if (StringUtils.isNotEmpty(trafficTags)) { tagMap = JSONObject.parseObject(trafficTags, Map.class); for (Map.Entry<String, String> tagEntry : tagMap.entrySet()) { - if (tagEntry.getKey().toLowerCase().equals("ifIndex".toLowerCase())) continue; +// if (tagEntry.getKey().toLowerCase().equals("ifIndex".toLowerCase())) continue; + if (StrUtil.equals(tagEntry.getKey().toLowerCase(),"ifIndex".toLowerCase())) continue; tagStr += tagEntry.getKey() + "=" + "\"" + tagEntry.getValue() + "\"" + ","; } } diff --git a/src/main/java/com/nis/util/BufferReaderWrapper.java b/src/main/java/com/nis/util/BufferReaderWrapper.java new file mode 100644 index 0000000..7411101 --- /dev/null +++ b/src/main/java/com/nis/util/BufferReaderWrapper.java @@ -0,0 +1,32 @@ +package com.nis.util; + +import cn.hutool.core.util.StrUtil; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; + +public class BufferReaderWrapper extends BufferedReader +{ + public Reader in; +// public static final int MAX_STR_LEN=1024; + public BufferReaderWrapper(Reader in) { + super(in); + this.in=in; + } + public String load() throws IOException { + StringBuffer sb = new StringBuffer(); + int intC; + while ((intC = in.read()) != -1) { + char c = (char) intC; + if (c == '\n') { + break; + } + /*if (sb.length() >= MAX_STR_LEN) { + throw new IOException("input too long"); + }*/ + sb.append(c); + } + return StrUtil.isEmpty(sb.toString()) ? null : sb.toString(); + } +} diff --git a/src/main/java/com/nis/util/CommonUtils.java b/src/main/java/com/nis/util/CommonUtils.java index f95e596..dbd6ed8 100644 --- a/src/main/java/com/nis/util/CommonUtils.java +++ b/src/main/java/com/nis/util/CommonUtils.java @@ -1,7 +1,11 @@ package com.nis.util; +import cn.hutool.core.util.StrUtil; + import java.io.File; -import java.util.*; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; import java.util.regex.Pattern; /** @@ -36,7 +40,7 @@ public class CommonUtils { } // 字符序列集 - if ((obj instanceof CharSequence) && "".equals(obj.toString().trim())) { + if((obj instanceof CharSequence) && StrUtil.equals( "",obj.toString().trim())) { return true; } // 单列集合 @@ -80,18 +84,6 @@ public class CommonUtils { return false; } - /** - * 空判断 - * - * @param obj 要判断,处理的对象 - * @return Boolean - * @author <a href="mailto:[email protected]">Ben</a> - * @see <b>与非空相反</b> - * @since 1.0 - */ - public static Boolean notEmpty(Object... obj) { - return !isEmpty(obj); - } public static Long toLong(Object val, Long defVal) { if (isEmpty(val)) { @@ -104,127 +96,11 @@ public class CommonUtils { } } - public static Long toLong(Object val) { - return toLong(val, null); - } - public static Integer toInt(Object val, Integer defVal) { - if (isEmpty(val)) { - return defVal; - } - try { - return Integer.parseInt(val.toString()); - } catch (NumberFormatException e) { - return defVal; - } - } - public static float toFloat(Object val, float defVal) { - if (isEmpty(val)) { - return defVal; - } - try { - return Float.parseFloat(val.toString()); - } catch (NumberFormatException e) { - return defVal; - } - } - - public static Boolean toBoolean(String text, Boolean defVal) { - if (isEmpty(text)) { - return false; - } - try { - return Boolean.parseBoolean(text); - } catch (NumberFormatException e) { - return defVal; - } - } - - public static Boolean toBoolean(String text) { - return toBoolean(text, false); - } - - public static Integer toInt(Object val) { - return toInt(val, null); - } - - public static Float toFloat(Object val) { - return toFloat(val, 0f); - } - - - /** - * Check whether the given Collection contains the given element instance. - * <p>Enforces the given instance to be present, rather than returning - * <code>true</code> for an equal element as well. - * - * @param collection the Collection to check - * @param element the element to look for - * @return <code>true</code> if found, <code>false</code> else - */ - public static boolean containsInstance(Collection collection, Object element) { - if (collection != null) { - for (Object candidate : collection) { - if (candidate == element) { - return true; - } - } - } - return false; - } - public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) { - ArrayList<A> elements = new ArrayList<A>(); - while (enumeration.hasMoreElements()) { - elements.add(enumeration.nextElement()); - } - return elements.toArray(array); - } - - /** - * Adapt an enumeration to an iterator. - * - * @param enumeration the enumeration - * @return the iterator - */ - public static <E> Iterator<E> toIterator(Enumeration<E> enumeration) { - @SuppressWarnings("hiding") - class EnumerationIterator<E> implements Iterator<E> { - private Enumeration<E> enumeration; - - public EnumerationIterator(Enumeration<E> enumeration) { - this.enumeration = enumeration; - } - - @Override - public boolean hasNext() { - return this.enumeration.hasMoreElements(); - } - - @Override - public E next() { - if (!this.hasNext()) { - throw new NoSuchElementException(); - } else { - return this.enumeration.nextElement(); - } - } - - @Override - public void remove() throws UnsupportedOperationException { - throw new UnsupportedOperationException("Not supported"); - } - } - return new EnumerationIterator<E>(enumeration); - } - - //获取系统名字 - public static String getOsName() { - return OS; - } public static boolean isLinux(){ return OS.indexOf("linux")>=0; @@ -238,9 +114,6 @@ public class CommonUtils { return OS.indexOf("mac")>=0&&OS.indexOf("os")>0&&OS.indexOf("x")>0; } - public static boolean isWindows(){ - return OS.indexOf("windows")>=0; - } public static boolean isOS2(){ return OS.indexOf("os/2")>=0; @@ -294,114 +167,12 @@ public class CommonUtils { return OS.indexOf("openvms")>=0; } - public static boolean isUnix() { - boolean isUnix = isLinux(); - if (!isUnix) { - isUnix = isMacOS(); - } - if (!isUnix) { - isUnix = isMacOSX(); - } - if (!isUnix) { - isUnix = isLinux(); - } - if (!isUnix) { - isUnix = isDigitalUnix(); - } - if (!isUnix) { - isUnix = isAix(); - } - if (!isUnix) { - isUnix = isFreeBSD(); - } - if (!isUnix) { - isUnix = isHPUX(); - } - if (!isUnix) { - isUnix = isIrix(); - } - if (!isUnix) { - isUnix = isMPEiX(); - } - if (!isUnix) { - isUnix = isNetWare(); - } - if (!isUnix) { - isUnix = isOpenVMS(); - } - if (!isUnix) { - isUnix = isOS2(); - } - if (!isUnix) { - isUnix = isOS390(); - } - if (!isUnix) { - isUnix = isOSF1(); - } - if (!isUnix) { - isUnix = isSunOS(); - } - if (!isUnix) { - isUnix = isSolaris(); - } - return isUnix; - } - /** - * linux内核平台 1 - * window: 2 - * 其他平台 0 - */ - public static int getPlatform(){ - int platform = 0; - if (CommonUtils.isUnix()) { - platform = 1; - } - if (CommonUtils.isWindows()) { - platform = 2; - } - return platform; - } - - - public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map) { - List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); - Collections.sort(list, new Comparator<Map.Entry<K, V>>() { - @Override - public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { - return (o1.getValue()).compareTo(o2.getValue()); - } - }); - Map<K, V> result = new LinkedHashMap<K, V>(); - for (Map.Entry<K, V> entry : list) { - result.put(entry.getKey(), entry.getValue()); - } - return result; - } - public static String uuid() { - return UUID.randomUUID().toString().replaceAll("-", ""); - } - /** - * 生成指定长度的uuid - * - * @param len - * @return - */ - public static String uuid(int len) { - StringBuffer sb = new StringBuffer(); - while (sb.length() < len) { - sb.append(uuid()); - } - return sb.toString().substring(0, len); - } - public static String getSystemCharset(){ - return System.getProperty("file.encoding"); - } - + /** * 端口合法性校验 * @param port @@ -424,44 +195,6 @@ public class CommonUtils { return true; } - public static boolean checkDomain(String domain){ - boolean flag = Pattern.matches(DOMAIN_NAME_STR, domain); - return flag; - } - - /** - * 校验url - * - * @param url - * @return - */ - public static boolean checkUrl(String url) { - Pattern compile = Pattern.compile("(" - + "(" - + "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")?" - + "(?:" + DOMAIN_NAME_STR + ")" - + "(?:" + PORT_NUMBER + ")?" - + ")" - + "(" + PATH_AND_QUERY + ")?" - + WORD_BOUNDARY - + ")"); - return compile.matcher(url).matches(); - } - - public static boolean checkUrlInModel(String url) { - Pattern compile = Pattern.compile("(" - + "(" - + "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")?" - + "(?:" + DOMAIN_NAME_IN_MODEL + ")" - + "(?:" + PORT_NUMBER + ")?" - + ")" - + "(" + PATH_AND_QUERY + ")?" - + WORD_BOUNDARY - + ")"); - return compile.matcher(url).matches(); - } - - private static final String DOMAIN_NAME_IN_MODEL = "(" + "[a-zA-Z0-9.]*" + ")"; private static final String IP_ADDRESS_STRING = "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]" diff --git a/src/main/java/com/nis/util/ConfagentConfig.java b/src/main/java/com/nis/util/ConfagentConfig.java index c074ac4..ea0bd9b 100644 --- a/src/main/java/com/nis/util/ConfagentConfig.java +++ b/src/main/java/com/nis/util/ConfagentConfig.java @@ -13,6 +13,7 @@ import org.apache.ibatis.mapping.VendorDatabaseIdProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + import java.util.Properties; /** diff --git a/src/main/java/com/nis/util/Constant.java b/src/main/java/com/nis/util/Constant.java index ffa4ec7..c63b1c6 100644 --- a/src/main/java/com/nis/util/Constant.java +++ b/src/main/java/com/nis/util/Constant.java @@ -8,12 +8,11 @@ package com.nis.util; +import cn.hutool.log.Log; import org.apache.ibatis.mapping.DatabaseIdProvider; import javax.sql.DataSource; -import java.io.File; import java.sql.SQLException; -import java.util.*; /** * 常量 @@ -21,6 +20,7 @@ import java.util.*; */ public class Constant { + private static final Log logger = Log.get(); /** redis 存储promserver信息 hash key */ public static final String ENDPOINT_PROM="endpoint_prom"; /** 超级管理员ID */ @@ -98,7 +98,7 @@ public class Constant { try { databaseId = databaseIdProvider.getDatabaseId(dataSource); } catch (SQLException e) { - e.printStackTrace(); + logger.debug(e); } DB_TYPE = databaseId; } diff --git a/src/main/java/com/nis/util/DateUtil.java b/src/main/java/com/nis/util/DateUtil.java index 45b1cb7..429121d 100644 --- a/src/main/java/com/nis/util/DateUtil.java +++ b/src/main/java/com/nis/util/DateUtil.java @@ -15,407 +15,17 @@ */ package com.nis.util; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.time.DateFormatUtils; +import cn.hutool.log.Log; -import java.sql.Timestamp; -import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class DateUtil { + private final static Log logger = Log.get(); - /** - * 配置时区 默认为0 - */ - public static int configTimeZone = 0; - - private static final Object lock = new Object(); private static final Map<String, ThreadLocal<SimpleDateFormat>> pool = new HashMap<String, ThreadLocal<SimpleDateFormat>>(); - /** - * 获取YYYY格式 - * - * @return - */ - public static String getYear() { - return formatDate(new Date(), "yyyy"); - } - - /** - * 获取YYYY格式 - * - * @return - */ - public static String getYear(Date date) { - return formatDate(date, "yyyy"); - } - - /** - * 获取YYYY-MM-DD格式 - * - * @return - */ - public static String getDay() { - return formatDate(new Date(), "yyyy-MM-dd"); - } - - /** - * 获取YYYY-MM-DD格式 - * - * @return - */ - public static String getDay(Date date) { - return formatDate(date, "yyyy-MM-dd"); - } - - /** - * 获取YYYYMMDD格式 - * - * @return - */ - public static String getDays() { - return formatDate(new Date(), "yyyyMMdd"); - } - - /** - * 获取YYYYMMDD格式 - * - * @return - */ - public static String getDays(Date date) { - return formatDate(date, "yyyyMMdd"); - } - - /** - * 获取YYYY-MM-DD HH:mm:ss格式 - * - * @return - */ - public static String getTime() { - return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"); - } - - /** - * 获取YYYY-MM-DD HH:mm:ss.SSS格式 - * - * @return - */ - public static String getMsTime() { - return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"); - } - - /** - * 获取YYYYMMDDHHmmss格式 - * - * @return - */ - public static String getAllTime() { - return formatDate(new Date(), "yyyyMMddHHmmss"); - } - - /** - * 获取YYYYMMDDHHmmss格式 - * - * @return - */ - public static String getNowTime() { - return formatDate(new Date(), "yyyyMMddHHmmsss"); - } - - /** - * 获取YYYY-MM-DD HH:mm:ss格式 - * - * @return - */ - public static String getTime(Date date) { - return formatDate(date, "yyyy-MM-dd HH:mm:ss"); - } - - public static String formatDate(Date date, String pattern) { - String formatDate = null; - if (StringUtils.isNotEmpty(pattern)) { - formatDate = DateFormatUtils.format(date, pattern); - } else { - formatDate = DateFormatUtils.format(date, "yyyy-MM-dd"); - } - return formatDate; - } - - /** - * @Title: compareDate - * @Description:(日期比较,如果s>=e 返回true 否则返回false) - * @param s - * @param e - * @return boolean - * @throws - * @author luguosui - */ - public static boolean compareDate(String s, String e) { - if (parseDate(s) == null || parseDate(e) == null) { - return false; - } - return parseDate(s).getTime() >= parseDate(e).getTime(); - } - - /** - * 格式化日期 - * - * @return - */ - public static Date parseDate(String date) { - return parse(date,"yyyy-MM-dd"); - } - - /** - * 格式化日期 - * - * @return - */ - public static Date parseTime(String date) { - return parse(date,"yyyy-MM-dd HH:mm:ss"); - } - - /** - * @Title: compareDate - * @Description:(日期比较,如果s>=e 返回true 否则返回false) - * @param s - * @param e - * @param pattern 格式 - * @return boolean - * @throws - * @author luguosui - */ - public static boolean compareDatePattern(String s, String e,String pattern) { - if (parse(s,pattern) == null || parse(e,pattern) == null) { - return false; - } - return parse(s,pattern).getTime() >= parse(e,pattern).getTime(); - } - - - /** - * @Title: compareDate - * @Description:(日期比较,如果s>e 返回true 否则返回false) - * @param s - * @param e - * @param pattern 格式 - * @return boolean - * @throws - * @author luguosui - */ - public static boolean compareDate(String s, String e,String pattern) { - if (parse(s,pattern) == null || parse(e,pattern) == null) { - return false; - } - return parse(s,pattern).getTime() > parse(e,pattern).getTime(); - } - - - public static boolean compareDated(String s, String e,String pattern) { - if (parse(s,pattern) == null || parse(e,pattern) == null) { - return false; - } - return parse(s,pattern).getTime() >= parse(e,pattern).getTime(); - } - - - /** - * 格式化日期 - * - * @return - */ - public static Date parse(String date, String pattern) { - if (ToolUtil.isNotEmpty(date)) { - if (ToolUtil.isEmpty(pattern)) { - return null; - } - DateFormat format = getDFormat(pattern); - format.setLenient(false); - try { - return format.parse(date); - } catch (ParseException e) { - throw new RuntimeException(e.getMessage()); - } - } - return null; - } - - public static SimpleDateFormat getDFormat(String pattern) { - ThreadLocal<SimpleDateFormat> tl = pool.get(pattern); - if (tl == null) { - synchronized (lock) { - tl = pool.get(pattern); - if (tl == null) { - final String p = pattern; - tl = new ThreadLocal<SimpleDateFormat>() { - @Override - protected synchronized SimpleDateFormat initialValue() { - return new SimpleDateFormat(p); - } - }; - pool.put(p, tl); - } - } - } - return tl.get(); - } - - /** - * 格式化日期 - * - * @return - */ - public static String format(Date date, String pattern) { - return DateFormatUtils.format(date, pattern); - } - - /** - * 把日期转换为Timestamp - * - * @param date - * @return - */ - public static Timestamp format(Date date) { - return new Timestamp(date.getTime()); - } - - /** - * 校验日期是否合法 - * - * @return - */ - public static boolean isValidDate(String s) { - return parse(s, "yyyy-MM-dd HH:mm:ss") != null; - } - - - - - public static int getDiffYear(String startTime, String endTime) { - DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); - try { - int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse( - startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365); - return years; - } catch (Exception e) { - // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对 - return 0; - } - } - - /** - * <li>功能描述:时间相减得到天数 - * - * @param beginDateStr - * @param endDateStr - * @return long - * @author Administrator - */ - public static long getDaySub(String beginDateStr, String endDateStr) { - long day = 0; - SimpleDateFormat format = new SimpleDateFormat( - "yyyy-MM-dd"); - Date beginDate = null; - Date endDate = null; - - try { - beginDate = format.parse(beginDateStr); - endDate = format.parse(endDateStr); - } catch (ParseException e) { - e.printStackTrace(); - } - day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000); - // System.out.println("相隔的天数="+day); - - return day; - } - - /** - * 得到n天之后的日期 - * - * @param days - * @return - */ - public static String getAfterDayDate(String days) { - int daysInt = Integer.parseInt(days); - - Calendar canlendar = Calendar.getInstance(); // java.util包 - canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动 - Date date = canlendar.getTime(); - - SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String dateStr = sdfd.format(date); - - return dateStr; - } - - /** - * 得到n天之后是周几 - * - * @param days - * @return - */ - public static String getAfterDayWeek(String days) { - int daysInt = Integer.parseInt(days); - - Calendar canlendar = Calendar.getInstance(); // java.util包 - canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动 - Date date = canlendar.getTime(); - - SimpleDateFormat sdf = new SimpleDateFormat("E"); - String dateStr = sdf.format(date); - - return dateStr; - } - public static String addtime(String timeStr,String addnumber){ - String str=null; - try{ - DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date date = df.parse(timeStr); - Calendar gc =new GregorianCalendar(); - gc.setTime(date); - gc.add(GregorianCalendar.MINUTE,Integer.parseInt(addnumber)); - str=df.format(gc.getTime()); - }catch (Exception e) { - } - return str; - } - - - /** - * 验证一个日期字符串,是否符合格式 - * - * @param simpleDateFormat - * @param dates - */ - public static void validDate(SimpleDateFormat simpleDateFormat, String... dates) { - try { - for (String date : dates) { - simpleDateFormat.setLenient(false); - simpleDateFormat.parse(date); - } - } catch (Exception ex) { - throw new RuntimeException(ex.getMessage()); - } - } - /** - * 验证一个日期字符串,是否符合格式 - * - * @param simpleDateFormat - * @param dates - */ - public static void validDate(SimpleDateFormat simpleDateFormat, List<String> dates) { - try { - for (String date : dates) { - simpleDateFormat.setLenient(false); - simpleDateFormat.parse(date); - } - } catch (Exception ex) { - throw new RuntimeException(ex.getMessage()); - } - } /** * 获取配置时区 @@ -448,7 +58,7 @@ public class DateUtil { sdf.setTimeZone(TimeZone.getDefault()); parse = sdf.parse(format); } catch (ParseException e) { - e.printStackTrace(); + logger.error(e); } return parse; } diff --git a/src/main/java/com/nis/util/LogPrintUtil.java b/src/main/java/com/nis/util/LogPrintUtil.java new file mode 100644 index 0000000..1289766 --- /dev/null +++ b/src/main/java/com/nis/util/LogPrintUtil.java @@ -0,0 +1,14 @@ +package com.nis.util; + + +import java.io.PrintWriter; +import java.io.StringWriter; + + +public class LogPrintUtil { + public static String print(Throwable t){ + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } +} diff --git a/src/main/java/com/nis/util/MybatisPlusConfig.java b/src/main/java/com/nis/util/MybatisPlusConfig.java index 56d2237..5853006 100644 --- a/src/main/java/com/nis/util/MybatisPlusConfig.java +++ b/src/main/java/com/nis/util/MybatisPlusConfig.java @@ -1,19 +1,17 @@ package com.nis.util; -import java.sql.SQLException; - -import javax.sql.DataSource; - +import cn.hutool.log.Log; +import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator; +import com.baomidou.mybatisplus.core.injector.ISqlInjector; +import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.apache.ibatis.mapping.DatabaseIdProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator; -import com.baomidou.mybatisplus.core.injector.ISqlInjector; -import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import com.nis.util.Constant; +import javax.sql.DataSource; +import java.sql.SQLException; /** * mybatis-plus配置 @@ -22,7 +20,7 @@ import com.nis.util.Constant; */ @Configuration public class MybatisPlusConfig { - + private static final Log logger = Log.get(); /** * 分页插件 */ @@ -58,7 +56,7 @@ public class MybatisPlusConfig { try { databaseId = databaseIdProvider.getDatabaseId(dataSource); } catch (SQLException e) { - e.printStackTrace(); + logger.debug(LogPrintUtil.print(e)); } switch (databaseId){ diff --git a/src/main/java/com/nis/util/PropertyPlaceholder.java b/src/main/java/com/nis/util/PropertyPlaceholder.java index 2404caa..8c66260 100644 --- a/src/main/java/com/nis/util/PropertyPlaceholder.java +++ b/src/main/java/com/nis/util/PropertyPlaceholder.java @@ -1,13 +1,13 @@ package com.nis.util;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {
private static Map<String,String> propertyMap;
@@ -23,9 +23,5 @@ public class PropertyPlaceholder extends PropertyPlaceholderConfigurer { }
}
- //static method for accessing context properties
- public static Object getProperty(String name) {
- return propertyMap.get(name);
- }
}
diff --git a/src/main/java/com/nis/util/RedisConfig.java b/src/main/java/com/nis/util/RedisConfig.java index 0e6046f..1cf8967 100644 --- a/src/main/java/com/nis/util/RedisConfig.java +++ b/src/main/java/com/nis/util/RedisConfig.java @@ -1,5 +1,8 @@ package com.nis.util;
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -7,10 +10,6 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
-import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Configuration
public class RedisConfig {
diff --git a/src/main/java/com/nis/util/RuntimeUtil.java b/src/main/java/com/nis/util/RuntimeUtil.java index 590d019..d89a642 100644 --- a/src/main/java/com/nis/util/RuntimeUtil.java +++ b/src/main/java/com/nis/util/RuntimeUtil.java @@ -1,20 +1,13 @@ package com.nis.util;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.StringReader;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-
+import cn.hutool.core.util.StrUtil;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import java.io.*;
+import java.util.UUID;
+
/**
* Runtime工具类,用于本机执行某些命令
*
@@ -31,35 +24,6 @@ public class RuntimeUtil { private RuntimeUtil() {
}
- /**
- * 以非阻塞模式执行命令
- *
- * @param callback
- * 回调类,当命令全部执行完成后会执行其onExit方法,null表示不进行回调
- * @param envp
- * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
- * @param dir
- * 命令执行的工作目录;null表示继承当前Java进程的工作目录
- * @param startCommand
- * 起始命令
- * @param commands
- * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
- */
- public static void runAsUnblocking(final RuntimeCallback callback, final String[] envp, final File dir,
- final String[] startCommand, final String[]... commands) {
- // 非阻塞的实现就是交给其他函数执行
- new Thread(new Runnable() {
- @Override
- public void run() {
- StringReader result = RuntimeUtil.run(envp, dir, startCommand, commands);
-
- // 如果需要回调的话,调用回调函数
- if (callback != null) {
- callback.onExit(result, envp, dir, startCommand, commands);
- }
- }
- }).start();
- }
/**
* 以阻塞模式执行命令
@@ -77,7 +41,7 @@ public class RuntimeUtil { public static StringReader run(String[] envp, File dir, String[] startCommand, String[]... commands) {
// 生成一个命令id,只是为日志区别用
String commandId = UUID.randomUUID().toString();
- log.info("Command(" + commandId + ") start");
+// log.info("Command(" + commandId + ") start");
StringBuilder result = new StringBuilder();
Process currentProcess = null;
@@ -89,7 +53,7 @@ public class RuntimeUtil { // 用于管道的字节输出流
BufferedOutputStream out = null;
// 用于标准错误输出和最终结果的字符输入流
- BufferedReader reader = null;
+ BufferReaderWrapper reader = null;
// 用于管道的字节输入流
BufferedInputStream in = null;
// 用于管道的IO缓冲
@@ -99,7 +63,7 @@ public class RuntimeUtil { for (String[] command : commands) {
try {
// 获取当前命令的标准错误流
- reader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream()));
+ reader = new BufferReaderWrapper(new InputStreamReader(currentProcess.getErrorStream()));
// 输出错误
for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
@@ -120,7 +84,7 @@ public class RuntimeUtil { // 当前命令全部输出都已经输入到下一条命令中后,将下一条命令作为当前命令
currentProcess = nextProcess;
} finally { // 流关闭操作
- if (out != null) {
+ /*if (out != null) {
out.flush();
out.close();
out = null;
@@ -134,12 +98,13 @@ public class RuntimeUtil { if (reader != null) {
reader.close();
reader = null;
- }
+ }*/
+ IOUtils.closeQuietly(out,in,reader);
}
}
// 获取最终命令的标准错误流,
- reader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream()));
+ reader = new BufferReaderWrapper(new InputStreamReader(currentProcess.getErrorStream()));
// 输出错误
for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
log.warn("Command(" + commandId + ") Error: " + temp);
@@ -149,13 +114,13 @@ public class RuntimeUtil { reader = null;
// 获取最终命令的标准输出流
- reader = new BufferedReader(new InputStreamReader(currentProcess.getInputStream()));
+ reader = new BufferReaderWrapper(new InputStreamReader(currentProcess.getInputStream()));
// 将输出添加到结果缓冲中
- for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
+ for (String temp = reader.load(); temp != null; temp = reader.load()) {
result.append(temp + "\n");
}
} finally { // 流关闭操作
- if (out != null) {
+ /*if (out != null) {BufferReaderWrapper
out.flush();
out.close();
out = null;
@@ -169,10 +134,11 @@ public class RuntimeUtil { if (reader != null) {
reader.close();
reader = null;
- }
+ }*/
+ IOUtils.closeQuietly(out,in,reader);
}
} catch (Exception e) { // 出现异常,尝试把启动的进程都销毁
- log.warn("Command(" + commandId + ") Error", e);
+// log.warn("Command(" + commandId + ") Error", e);
if (currentProcess != null) {
currentProcess.destroy();
@@ -201,10 +167,10 @@ public class RuntimeUtil { */
public static String readStringReader(StringReader stringReader, boolean skipWhiteLine) {
StringBuilder result = new StringBuilder();
- BufferedReader reader = new BufferedReader(stringReader);
+ BufferReaderWrapper reader = new BufferReaderWrapper(stringReader);
for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
- if (skipWhiteLine == false || !temp.trim().equals("")) {
+ if(skipWhiteLine == false || !StrUtil.equals(temp.trim(),"")) {
result.append(temp + "\n");
}
}
@@ -228,7 +194,7 @@ public class RuntimeUtil { * @throws Exception
*/
private static Process run(String commandId, String[] command, String[] envp, File dir) throws Exception {
- log.info("Command(" + commandId + ") exec: " + Arrays.toString(command));
+// log.info("Command(" + commandId + ") exec: " + Arrays.toString(command));
return runtime.exec(command, envp, dir);
}
@@ -261,11 +227,11 @@ public class RuntimeUtil { * 输入流
* @return 基本等同于reader.readLine()的返回值,不过在出现异常时,不会抛出异常而是返回null
*/
- private static String readLine(BufferedReader reader) {
+ private static String readLine(BufferReaderWrapper reader) {
String result = null;
try {
- result = reader.readLine();
+ result = reader.load();
} catch (IOException e) {
result = null;
}
@@ -286,7 +252,7 @@ public class RuntimeUtil { private static void write(OutputStream out, byte[] buffer, int length) {
try {
out.write(buffer, 0, length);
- } catch (IOException e) {
+ } catch (IOException e) {LogPrintUtil.print(e);
}
}
@@ -309,50 +275,6 @@ public class RuntimeUtil { public void onExit(StringReader result, String[] envp, File dir, String[] startCommand, String[]... commands);
}
- public static void main(String[] args) {
-
- System.out.println(readStringReader(run(null, null, new String[] { "c:/promtool", "check", "rules", "d:/test.yml" }), false));
- // 例子 ps -ef (注意用String[]方式来表示命令是不需要做转移的)
- /*System.out.println(readStringReader(run(null, null, new String[] { "ps", "-ef" }), true));
- System.out.println("-----------------------------------------------------------------");
- // 例子 ps -ef | grep -i java
- System.out.println(readStringReader(
- run(null, null, new String[] { "ps", "-ef" }, new String[] { "grep", "-i", "java" }), true));*/
- }
- public static List<String> run(String command) throws IOException {
- List<String> result = new ArrayList<>();
- Scanner input = null;
- //String result = "";
- Process process = null;
- log.info("执行扫描命令===>"+command);
- try {
- process = Runtime.getRuntime().exec(command);
- try {
- //等待命令执行完成
- process.waitFor(10, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- InputStream is = process.getInputStream();
- input = new Scanner(is);
- while (input.hasNextLine()) {
- String[] tmp= input.nextLine().split("::");
- if("IF-MIB".equalsIgnoreCase(tmp[0])
- &&(tmp[1].contains("ifOut")||tmp[1].contains("ifIn"))&&
- !tmp[1].contains("ifIndex")){
- result.add(tmp[1]);
- }
- }
- } finally {
- if (input != null) {
- input.close();
- }
- if (process != null) {
- process.destroy();
- }
- }
- return result;
- }
}
diff --git a/src/main/java/com/nis/util/SnmpUtil.java b/src/main/java/com/nis/util/SnmpUtil.java index 4fcbe6a..561ea35 100644 --- a/src/main/java/com/nis/util/SnmpUtil.java +++ b/src/main/java/com/nis/util/SnmpUtil.java @@ -1,6 +1,7 @@ package com.nis.util; -import lombok.extern.slf4j.Slf4j; +import cn.hutool.core.util.StrUtil; +import cn.hutool.log.Log; import org.apache.commons.lang.StringUtils; import org.snmp4j.*; import org.snmp4j.event.ResponseEvent; @@ -13,15 +14,12 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Component -@Slf4j +//@Slf4j public class SnmpUtil { - + private Log log= Log.get(); @Value("${confagent.snmp.walkTimeOut}") private Integer DEFAULT_TIMEOUT; @@ -30,7 +28,6 @@ public class SnmpUtil { // 默认版本 v2 - private final int DEFAULT_VERSION = SnmpConstants.version2c; private final String DEFAULT_PROTOCOL = "udp"; // 默认团体名 private final String DEFAULT_COMMUNITY = "public"; @@ -41,17 +38,17 @@ public class SnmpUtil { // 添加用户 OID authProtocolOid = null; String authProtocol = auth.get("authProtocol"); - if ("MD5".equals(authProtocol)) { + if(StrUtil.equals("MD5",authProtocol)) { authProtocolOid = AuthMD5.ID; - } else if ("SHA".equals(authProtocol)) { + } else if(StrUtil.equals("SHA",authProtocol)) { authProtocolOid = AuthSHA.ID; } OID privProtocolOid = null; String privProtocol = auth.get("privProtocol"); - if ("DES".equals(privProtocol)) { + if(StrUtil.equals("DES",privProtocol)) { privProtocolOid = PrivDES.ID; - } else if ("AES".equals(privProtocol)) { + } else if(StrUtil.equals("AES",privProtocol)) { privProtocolOid = PrivAES128.ID; } @@ -61,7 +58,7 @@ public class SnmpUtil { octetPrivPassword = new OctetString(privPassword); } - String password = auth.get("password"); + String password = Arrays.toString(auth.get("password").getBytes()); OctetString octetpassword = null; if(StringUtils.isNotEmpty(password)){ octetpassword = new OctetString(password); @@ -191,7 +188,7 @@ public class SnmpUtil { map.put("type", vb.getVariable().getSyntaxString()); // 时间类型值转为long类型 - if("TimeTicks".equals(vb.getVariable().getSyntaxString())){ + if(StrUtil.equals("TimeTicks",vb.getVariable().getSyntaxString())){ TimeTicks variable = (TimeTicks) vb.getVariable(); map.put("value", variable.getValue()); } diff --git a/src/main/java/com/nis/util/SpringContextUtils.java b/src/main/java/com/nis/util/SpringContextUtils.java index 8680dcf..798bf5a 100644 --- a/src/main/java/com/nis/util/SpringContextUtils.java +++ b/src/main/java/com/nis/util/SpringContextUtils.java @@ -28,24 +28,8 @@ public class SpringContextUtils implements ApplicationContextAware { SpringContextUtils.applicationContext = applicationContext; } - public static Object getBean(String name) { - return applicationContext.getBean(name); - } public static <T> T getBean(String name, Class<T> requiredType) { return applicationContext.getBean(name, requiredType); } - - public static boolean containsBean(String name) { - return applicationContext.containsBean(name); - } - - public static boolean isSingleton(String name) { - return applicationContext.isSingleton(name); - } - - public static Class<? extends Object> getType(String name) { - return applicationContext.getType(name); - } - }
\ No newline at end of file diff --git a/src/main/java/com/nis/util/ToolUtil.java b/src/main/java/com/nis/util/ToolUtil.java deleted file mode 100644 index d5f36f8..0000000 --- a/src/main/java/com/nis/util/ToolUtil.java +++ /dev/null @@ -1,718 +0,0 @@ -/** - * Copyright (c) 2015-2016, Chill Zhuang 庄骞 ([email protected]). - * <p> - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * <p> - * http://www.apache.org/licenses/LICENSE-2.0 - * <p> - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.nis.util; - - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.math.BigDecimal; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.util.*; -import java.util.Map.Entry; -import java.util.regex.Pattern; - -/** - * 高频方法集合类 - */ -public class ToolUtil { - - - /** - * 字符连接符 - */ - private static final char SEPARATOR = '_'; - /** - * 默认编码 - */ - private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); - - private static Pattern humpPattern = Pattern.compile("[A-Z]"); - - - - - - /** - * 下划线命名 转 驼峰命名 首字母小写 - * - * @param s the s - * @return String toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world" - */ - public static String toCamelCase(String s) { - if (s == null) { - return null; - } - - String ls = s.toLowerCase(); - - StringBuilder sb = new StringBuilder(ls.length()); - boolean upperCase = false; - for (int i = 0; i < ls.length(); i++) { - char c = ls.charAt(i); - - if (c == SEPARATOR) { - upperCase = true; - } else if (upperCase) { - sb.append(Character.toUpperCase(c)); - upperCase = false; - } else { - sb.append(c); - } - } - - return sb.toString(); - } - - /** - * 下划线命名 转 驼峰命名 首字母大写 - * - * @param s the s - * @return String toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world" - */ - public static String toCapitalizeCamelCase(String s) { - if (s == null) { - return null; - } - String cs = toCamelCase(s); - return cs.substring(0, 1).toUpperCase() + cs.substring(1); - } - - /** - * 驼峰命名 转 下划线命名 - * - * @param s the s - * @return String toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world" - */ - public static String toUnderScoreCase(String s) { - if (s == null) { - return null; - } - - StringBuilder sb = new StringBuilder(); - boolean upperCase = false; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - - boolean nextUpperCase = true; - - if (i < (s.length() - 1)) { - nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); - } - - if ((i > 0) && Character.isUpperCase(c)) { - if (!upperCase || !nextUpperCase) { - sb.append(SEPARATOR); - } - upperCase = true; - } else { - upperCase = false; - } - - sb.append(Character.toLowerCase(c)); - } - - return sb.toString(); - } - - /** - * 获取随机位数的字符串 - * - * @author fengshuonan - * @Date 2017/8/24 14:09 - */ - public static String getRandomString(int length) { - String base = "abcdefghijklmnopqrstuvwxyz0123456789"; - Random random = new Random(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < length; i++) { - int number = random.nextInt(base.length()); - sb.append(base.charAt(number)); - } - return sb.toString(); - } - - /** - * 判断一个对象是否是时间类型 - * - * @author stylefeng - * @Date 2017/4/18 12:55 - */ - public static String dateType(Object o) { - if (o instanceof Date) { - return DateUtil.getDay((Date) o); - } else { - return o.toString(); - } - } - - /** - * 获取异常的具体信息 - * - * @author fengshuonan - * @Date 2017/3/30 9:21 - * @version 2.0 - */ - public static String getExceptionMsg(Exception e) { - StringWriter sw = new StringWriter(); - try { - e.printStackTrace(new PrintWriter(sw)); - } finally { - try { - sw.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - return sw.getBuffer().toString().replaceAll("\\$", "T"); - } - - /** - * 比较两个对象是否相等。<br> - * 相同的条件有两个,满足其一即可:<br> - * 1. obj1 == null && obj2 == null; 2. obj1.equals(obj2) - * - * @param obj1 对象1 - * @param obj2 对象2 - * @return 是否相等 - */ - public static boolean equals(Object obj1, Object obj2) { - return (obj1 != null) ? (obj1.equals(obj2)) : (obj2 == null); - } - - /** - * 计算对象长度,如果是字符串调用其length函数,集合类调用其size函数,数组调用其length属性,其他可遍历对象遍历计算长度 - * - * @param obj 被计算长度的对象 - * @return 长度 - */ - public static int length(Object obj) { - if (obj == null) { - return 0; - } - if (obj instanceof CharSequence) { - return ((CharSequence) obj).length(); - } - if (obj instanceof Collection) { - return ((Collection<?>) obj).size(); - } - if (obj instanceof Map) { - return ((Map<?, ?>) obj).size(); - } - - int count; - if (obj instanceof Iterator) { - Iterator<?> iter = (Iterator<?>) obj; - count = 0; - while (iter.hasNext()) { - count++; - iter.next(); - } - return count; - } - if (obj instanceof Enumeration) { - Enumeration<?> enumeration = (Enumeration<?>) obj; - count = 0; - while (enumeration.hasMoreElements()) { - count++; - enumeration.nextElement(); - } - return count; - } - if (obj.getClass().isArray() == true) { - return Array.getLength(obj); - } - return -1; - } - - /** - * 对象中是否包含元素 - * - * @param obj 对象 - * @param element 元素 - * @return 是否包含 - */ - public static boolean contains(Object obj, Object element) { - if (obj == null) { - return false; - } - if (obj instanceof String) { - if (element == null) { - return false; - } - return ((String) obj).contains(element.toString()); - } - if (obj instanceof Collection) { - return ((Collection<?>) obj).contains(element); - } - if (obj instanceof Map) { - return ((Map<?, ?>) obj).values().contains(element); - } - - if (obj instanceof Iterator) { - Iterator<?> iter = (Iterator<?>) obj; - while (iter.hasNext()) { - Object o = iter.next(); - if (equals(o, element)) { - return true; - } - } - return false; - } - if (obj instanceof Enumeration) { - Enumeration<?> enumeration = (Enumeration<?>) obj; - while (enumeration.hasMoreElements()) { - Object o = enumeration.nextElement(); - if (equals(o, element)) { - return true; - } - } - return false; - } - if (obj.getClass().isArray() == true) { - int len = Array.getLength(obj); - for (int i = 0; i < len; i++) { - Object o = Array.get(obj, i); - if (equals(o, element)) { - return true; - } - } - } - return false; - } - - /** - * 对象是否不为空(新增) - * - * @param o String,List,Map,Object[],int[],long[] - * @return - */ - public static boolean isNotEmpty(Object o) { - return !isEmpty(o); - } - - /** - * 对象是否为空 - * - * @param o String,List,Map,Object[],int[],long[] - * @return - */ - @SuppressWarnings("rawtypes") - public static boolean isEmpty(Object o) { - if (o == null) { - return true; - } - if (o instanceof String) { - if (o.toString().trim().equals("")) { - return true; - } - } else if (o instanceof List) { - if (((List) o).size() == 0) { - return true; - } - } else if (o instanceof Map) { - if (((Map) o).size() == 0) { - return true; - } - } else if (o instanceof Set) { - if (((Set) o).size() == 0) { - return true; - } - } else if (o instanceof Object[]) { - if (((Object[]) o).length == 0) { - return true; - } - } else if (o instanceof int[]) { - if (((int[]) o).length == 0) { - return true; - } - } else if (o instanceof long[]) { - if (((long[]) o).length == 0) { - return true; - } - } - return false; - } - - /** - * 对象组中是否存在 Empty Object - * - * @param os 对象组 - * @return - */ - public static boolean isOneEmpty(Object... os) { - for (Object o : os) { - if (isEmpty(o)) { - return true; - } - } - return false; - } - - /** - * 对象组中是否全是 Empty Object - * - * @param os - * @return - */ - public static boolean isAllEmpty(Object... os) { - for (Object o : os) { - if (!isEmpty(o)) { - return false; - } - } - return true; - } - /** - * 对象组都不是empty - */ - public static boolean isNotAllEmpty(Object... obj){ - for (Object o:obj){ - if (isEmpty(o)){ - return false; - } - } - return true; - } - - /** - * 是否为数字 - * - * @param obj - * @return - */ - public static boolean isNum(Object obj) { - try { - Integer.parseInt(obj.toString()); - } catch (Exception e) { - return false; - } - return true; - } - - /** - * 如果为空, 则调用默认值 - * - * @param str - * @return - */ - public static Object getValue(Object str, Object defaultValue) { - if (isEmpty(str)) { - return defaultValue; - } - return str; - } - - - - /** - * 强转->string,并去掉多余空格 - * - * @param str - * @return - */ - public static String toStr(Object str) { - return toStr(str, ""); - } - - /** - * 强转->string,并去掉多余空格 - * - * @param str - * @param defaultValue - * @return - */ - public static String toStr(Object str, String defaultValue) { - if (null == str) { - return defaultValue; - } - return str.toString().trim(); - } - - /** - * map的key转为小写 - * - * @param map - * @return Map<String,Object> - */ - public static Map<String, Object> caseInsensitiveMap(Map<String, Object> map) { - Map<String, Object> tempMap = new HashMap<>(); - for (String key : map.keySet()) { - tempMap.put(key.toLowerCase(), map.get(key)); - } - return tempMap; - } - - /** - * 获取map中第一个数据值 - * - * @param <K> Key的类型 - * @param <V> Value的类型 - * @param map 数据源 - * @return 返回的值 - */ - public static <K, V> V getFirstOrNull(Map<K, V> map) { - V obj = null; - for (Entry<K, V> entry : map.entrySet()) { - obj = entry.getValue(); - if (obj != null) { - break; - } - } - return obj; - } - - /** - * 创建StringBuilder对象 - * - * @return StringBuilder对象 - */ - public static StringBuilder builder(String... strs) { - final StringBuilder sb = new StringBuilder(); - for (String str : strs) { - sb.append(str); - } - return sb; - } - - /** - * 创建StringBuilder对象 - * - * @return StringBuilder对象 - */ - public static void builder(StringBuilder sb, String... strs) { - for (String str : strs) { - sb.append(str); - } - } - - /** - * 去掉指定后缀 - * - * @param str 字符串 - * @param suffix 后缀 - * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串 - */ - public static String removeSuffix(String str, String suffix) { - if (isEmpty(str) || isEmpty(suffix)) { - return str; - } - - if (str.endsWith(suffix)) { - return str.substring(0, str.length() - suffix.length()); - } - return str; - } - - /** - * 判断是否是windows操作系统 - * - * @author stylefeng - * @Date 2017/5/24 22:34 - */ - public static Boolean isWinOs() { - String os = System.getProperty("os.name"); - if (os.toLowerCase().startsWith("win")) { - return true; - } else { - return false; - } - } - - /** - * 获取临时目录 - * - * @author stylefeng - * @Date 2017/5/24 22:35 - */ - public static String getTempPath() { - return System.getProperty("java.io.tmpdir"); - } - - /** - * 把一个数转化为int - * - * @author fengshuonan - * @Date 2017/11/15 下午11:10 - */ - public static Integer toInt(Object val) { - if (val instanceof Double) { - BigDecimal bigDecimal = new BigDecimal((Double) val); - return bigDecimal.intValue(); - } else { - return Integer.valueOf(val.toString()); - } - - } - - /** - * 获取项目路径 - */ - public static String getWebRootPath(String filePath) { - try { - String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath(); - path = path.replace("/WEB-INF/classes/", ""); - path = path.replace("/target/classes/", ""); - path = path.replace("file:/", ""); - if (ToolUtil.isEmpty(filePath)) { - return path; - } else { - return path + "/" + filePath; - } - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - /** - * 字符串是否包含不可见字符 - * 包含:true - * 不包含:false - * @param content - * @return Boolean - */ - public static Boolean containsInvisibleChar(String content) { - if (content != null && content.length() > 0) { - char[] contentCharArr = content.toCharArray(); - for (int i = 0; i < contentCharArr.length; i++) { - if ((contentCharArr[i] <= 0x1F) || contentCharArr[i] == 0x7F) { - return true; - } - } - return false; - } - return false; - } - - /** - * 获取客户端ip - * @param req - * @return - */ - public static String getRealIp(HttpServletRequest req) { - String ip = req.getHeader("x-forwarded-for"); - - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { - ip = req.getHeader("Proxy-Client-IP"); - } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { - ip = req.getHeader("WL-Proxy-Client-IP"); - } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { - ip = req.getRemoteAddr(); - } - if (ip == null || ip.length() == 0 || "0:0:0:0:0:0:0:1".equals(ip)) { - ip = "127.0.0.1"; - } - return ip; - } - - /** - * 判断开始时间是否在结束时间之前 - * @param opStartTime - * @param opEndTime - */ - public static void validateOpTime(String opStartTime,String opEndTime){ - Date startTime = DateUtil.parseTime(opStartTime); - Date endTime = DateUtil.parseTime(opEndTime); - if (ToolUtil.isNotAllEmpty(opStartTime,opEndTime)){ - if (startTime.after(endTime)){ - throw new RuntimeException("Incorrect Date Format"); - } - } - - } - - /** - * 验证开始时间和结束时间:格式 开始时间不能大于结束时间 - * @param startTime - * @param endTime - * @return - */ - public static Boolean validateStartAndEndDateFormat(String startTime,String endTime){ - Boolean result = true; - try { - Date start = ToolUtil.isNotEmpty(startTime)?DateUtil.parseTime(startTime):null; - Date end = ToolUtil.isNotEmpty(endTime)?DateUtil.parseTime(endTime):null; - if (ToolUtil.isNotEmpty(start)&&ToolUtil.isNotEmpty(end)&&start.after(end)){ - result = false; - } - }catch (Exception e){ - result = false; - } - return result; - } - - /** - * 获取Annotation 中 memberValues的值 - * - * @param object - * @param property - * @param <T> - * @return - */ - public static <T> Object getFieldValue(T object, String property) { - if (object != null && property != null) { - Class<T> currClass = (Class<T>) object.getClass(); - try { - Field field = currClass.getDeclaredField(property); - field.setAccessible(true); - return field.get(object); - } catch (Exception e) { - e.printStackTrace(); - } - } - return null; - } - /** - * //递归获取cls实体对象及父级对象的属性 wx:修改,子类覆盖父类的同名方法 - * - * @param list - * @param cls - */ - public static void getFields(List<Field> list, Class<?> cls) { - Field[] fields = cls.getDeclaredFields(); - if (fields != null && fields.length > 0) { - List<Field> tempList = new ArrayList<>(); - for (Field field : fields) { - if (list.size() == 0) { - tempList.add(field); - } else { - boolean has = false; - for (Field checkF : list) { - if (checkF.getName().equals(field.getName())) { - has = true; - break; - } - } - if (!has) { - tempList.add(field); - } - } - } - list.addAll(tempList); - } - if (cls.getSuperclass() != null) { - getFields(list, cls.getSuperclass()); - } - } -} diff --git a/src/main/java/com/nis/util/YamlUtil.java b/src/main/java/com/nis/util/YamlUtil.java index 8e16863..93ab6cd 100644 --- a/src/main/java/com/nis/util/YamlUtil.java +++ b/src/main/java/com/nis/util/YamlUtil.java @@ -1,23 +1,23 @@ package com.nis.util;
+import cn.hutool.core.io.FileUtil;
+import cn.hutool.core.util.RuntimeUtil;
+import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.commons.io.IOUtils;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
import java.util.Set;
public class YamlUtil {
- private static Logger logger = LoggerFactory.getLogger(YamlUtil.class);
+ private static Log logger = Log.get();
/**
* snmp配置相关
* @param param
@@ -34,7 +34,7 @@ public class YamlUtil { OutputStream out = null;
OutputStreamWriter osw = null;
try {
- File file = new File(ymlPath);
+ File file = FileUtil.file(ymlPath);
out=new FileOutputStream(file);
osw=new OutputStreamWriter(out, "UTF-8");
for(String s : param) {
@@ -42,25 +42,16 @@ public class YamlUtil { y.dump(load,osw);
}
flag = true;
- } catch (Exception e) {
+ } catch (FileNotFoundException e) {
+ logger.error("snmpYmlHandle error : "+e.getMessage(),e);
+ } catch (UnsupportedEncodingException e) {
logger.error("snmpYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
} finally {
if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- logger.error("snmpYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(out);
}
if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- logger.error("snmpYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(osw);
}
}
}
@@ -84,7 +75,7 @@ public class YamlUtil { OutputStream out = null;
OutputStreamWriter osw = null;
try {
- File file = new File(ymlPath);
+ File file = FileUtil.file(ymlPath);
/**fileInputStream = new FileInputStream(file);
Map<String,Object> map = y.loadAs(fileInputStream, Map.class);
if(map==null) {
@@ -93,7 +84,7 @@ public class YamlUtil { map.remove("rule_files");
map.put("scrape_configs", param);**/
//修改 rule.yml配置文件
- File ruleYmlfile = new File(ruleYmlPath);
+ File ruleYmlfile = FileUtil.file(ruleYmlPath);
if(ruleYmlfile.exists()){
// 文件存在则删除文件信息
ruleYmlfile.delete();
@@ -104,33 +95,19 @@ public class YamlUtil { y.dump(param,osw);
flag = true;
- } catch (Exception e) {
+ } catch (FileNotFoundException e) {
+ logger.error("subYmlHandle error : "+e.getMessage(),e);
+ } catch (UnsupportedEncodingException e) {
logger.error("subYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
} finally {
if(fileInputStream!=null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- logger.error("subYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(fileInputStream);
}
if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- logger.error("subYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(out);
}
if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- logger.error("subYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(osw);
}
}
}
@@ -159,7 +136,7 @@ public class YamlUtil { OutputStreamWriter osw2 = null;
try {
//修改 rule.yml配置文件
- File ruleYmlfile = new File(ruleYmlPath);
+ File ruleYmlfile = FileUtil.file(ruleYmlPath);
if(!ruleYmlfile.exists()){
// 文件不存在 创建文件
ruleYmlfile.createNewFile();
@@ -176,7 +153,7 @@ public class YamlUtil { //去除告警规则相关内容
param.remove("groups");
// 修改prometheus.yml配置文件
- File ymlfile = new File(ymlPath);
+ File ymlfile = FileUtil.file(ymlPath);
/**fileInputStream = new FileInputStream(ymlfile);
Map<String,Object> map = y.loadAs(fileInputStream, Map.class);
if(map==null) {
@@ -192,57 +169,30 @@ public class YamlUtil { flag = true;
- } catch (Exception e) {
+ } catch (UnsupportedEncodingException e) {
+ logger.error("centerYmlHandle error : "+e.getMessage(),e);
+ } catch (FileNotFoundException e) {
+ logger.error("centerYmlHandle error : "+e.getMessage(),e);
+ } catch (IOException e) {
logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
} finally {
if(fileInputStream!=null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(fileInputStream);
}
if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(out);
}
if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(osw);
}
if(fileInputStream2!=null) {
- try {
- fileInputStream2.close();
- } catch (IOException e) {
- logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(fileInputStream2);
}
if(out2!=null) {
- try {
- out.close();
- } catch (IOException e) {
- logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(out2);
}
if(osw2!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- logger.error("centerYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(osw2);
}
}
}
@@ -267,7 +217,7 @@ public class YamlUtil { OutputStream out = null;
try {
// 修改 rule.yml配置文件
- File ruleYmlfile = new File(ruleYmlPath);
+ File ruleYmlfile = FileUtil.file(ruleYmlPath);
if (!ruleYmlfile.exists()) {
// 文件不存在 创建文件
ruleYmlfile.createNewFile();
@@ -282,25 +232,18 @@ public class YamlUtil { OutputStreamWriter osw2 = new OutputStreamWriter(out2, "UTF-8");
y.dump(map2, osw2);
flag = true;
- } catch (Exception e) {
+ } catch (UnsupportedEncodingException e) {
+ logger.error("thanosRuleYmlHandle error : "+e.getMessage(),e);
+ } catch (FileNotFoundException e) {
+ logger.error("thanosRuleYmlHandle error : "+e.getMessage(),e);
+ } catch (IOException e) {
logger.error("thanosRuleYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
} finally {
if (fileInputStream != null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- logger.error("thanosRuleYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(fileInputStream);
}
if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- logger.error("thanosRuleYmlHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(out);
}
}
}
@@ -320,7 +263,7 @@ public class YamlUtil { boolean flag=false;
RandomAccessFile raf = null;
try {
- raf = new RandomAccessFile(new File(filePath), "rw");
+ raf = new RandomAccessFile(FileUtil.file(filePath), "rw");
String readLine = null;
long lastPoint = 0; //记住上一次的偏移量
while((readLine=raf.readLine())!=null) {
@@ -333,24 +276,22 @@ public class YamlUtil { lastPoint = ponit;
}
raf.close();
- RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl daemon-reload"});
+ /*RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl daemon-reload"});
RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl stop prometheus"});
- RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl start prometheus"});
+ RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl start prometheus"});*/
+ RuntimeUtil.exec("systemctl daemon-reload");
+ RuntimeUtil.exec("systemctl stop prometheus");
+ RuntimeUtil.exec("systemctl start prometheus");
flag=true;
} catch (FileNotFoundException e) {
logger.error("prometheusStartHandle error : FileNotFoundException "+e.getMessage(),e);
- e.printStackTrace();
+
} catch (IOException e) {
logger.error("prometheusStartHandle error : IOException "+e.getMessage(),e);
- e.printStackTrace();
+
} finally {
if(raf!=null) {
- try {
- raf.close();
- } catch (IOException e) {
- logger.error("prometheusStartHandle error : FileNotFoundException "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(raf);
}
}
return flag;
@@ -373,7 +314,7 @@ public class YamlUtil { OutputStreamWriter osw = null;
try {
// 修改prometheus.yml配置文件
- File ymlfile = new File(ymlPath);
+ File ymlfile = FileUtil.file(ymlPath);
fileInputStream = new FileInputStream(ymlfile);
Map<String,Object> map = y.loadAs(fileInputStream, Map.class);
if(map==null) {
@@ -395,33 +336,19 @@ public class YamlUtil { y.dump(map,osw);
flag = true;
- } catch (Exception e) {
+ } catch (FileNotFoundException e) {
+ logger.error("prometheusSettingHandle error : "+e.getMessage(),e);
+ } catch (UnsupportedEncodingException e) {
logger.error("prometheusSettingHandle error : "+e.getMessage(),e);
- e.printStackTrace();
} finally {
if(fileInputStream!=null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- logger.error("prometheusSettingHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(fileInputStream);
}
if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- logger.error("prometheusSettingHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(out);
}
if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- logger.error("prometheusSettingHandle error : "+e.getMessage(),e);
- e.printStackTrace();
- }
+ IOUtils.closeQuietly(osw);
}
}
}
|
