16 Commits

Author SHA1 Message Date
c0443d3a8b 完成基本功能。 2022-05-06 11:15:04 +08:00
eb7f53ad4b 保存进度! 2022-05-05 17:53:31 +08:00
91c99ba8f9 完成发送记录保存功能。待完善…… 2022-05-05 16:59:28 +08:00
0fb8b90509 重构一下 2022-05-04 00:08:17 +08:00
cd743c645f 保存进度! 2022-04-28 15:59:40 +08:00
2d1d4dea66 提交小修改! 2022-04-27 23:38:47 +08:00
24cdc66b7d 完成check函数!修正jdbc url的错误! 2022-04-27 17:37:36 +08:00
5da53f02ea 完成判断消息是否已发送功能! 2022-04-27 16:09:58 +08:00
0587001de0 提交小修改! 2022-04-26 23:23:43 +08:00
64170d2e67 提交小修改! 2022-04-26 23:23:10 +08:00
51a2829433 提交小修改! 2022-04-26 23:21:37 +08:00
59977ec9b6 修正读取配置文件utf-8编码的bug! 2022-04-26 23:17:24 +08:00
9d57987f0c 改变配置文件的获取方式!改成singleton! 2022-04-25 23:27:38 +08:00
a78fad18ea 保存进度! 2022-04-25 17:41:41 +08:00
07ae9f88a3 完善 jackson 解析时间。 2022-04-24 11:34:49 +08:00
5496c06eea 保存进度! 2022-04-24 10:20:48 +08:00
13 changed files with 513 additions and 198 deletions

2
.gitignore vendored
View File

@@ -2,3 +2,5 @@ code/java/天气灾害预警/target/
code/java/天气灾害预警/out/
*.jar
*.iws
*.log
*.lck

View File

@@ -1,92 +1,8 @@
# 大灾预警
大灾预警数据抓取。
## Getting started
<h1 style="text-align:center;font-size:4rem;" title>气象灾害预警推送应用</h1>
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
**功能:**
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://cppdisciple.f3322.org:65310/cpicxm/disaster-warning.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://cppdisciple.f3322.org:65310/cpicxm/disaster-warning/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
- 从和风天气查询配置文件中列出地区的气象灾害预警;
- 如果预警则推送厦门太保公众。

View File

@@ -1,12 +1,14 @@
{
"tns_name": "xmcx1",
"ip_addr": "10.39.0.86",
"user_name": "",
"password": "",
"jdbc_url": "jdbc:oracle:thin:@10.39.0.86:1521:xmcx1",
"table_space": "wechat",
"user_name": "wechat",
"password": "@rn7Q+t5zeyKIZ~s",
"tables": [
{
"table_name": "",
"table_description": ""
"table_name": "weather_disaster_notify",
"table_description": "天气预警消息表"
}
]
}

View File

@@ -5,6 +5,13 @@
<artifactId>disaster_warning</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/ojdbc8.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
@@ -72,6 +79,11 @@
</properties>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<!-- <plugin>
<artifactId>maven-assembly-plugin</artifactId>
</plugin> -->
</plugins>
</build>
<profiles>
<profile>

View File

@@ -2,7 +2,7 @@
* @Author: Kane
* @Date: 2022-04-22 10:53:49
* @LastEditors: Kane
* @LastEditTime: 2022-04-23 23:22:57
* @LastEditTime: 2022-05-06 11:08:07
* @FilePath: \DisasterWarning\src\main\java\AppMain.java
* @Description: 和风天气预警推送厦门太保公众号主程序!
*
@@ -11,32 +11,53 @@
import com.cpic.xim.config.City;
import com.cpic.xim.notify.disaster.QWeatherDisasterWarning;
import com.cpic.xim.notify.disaster.WeatherDisasterWarningGrabber;
import com.cpic.xim.config.WeatherDisasterNotifyConfig;
import com.cpic.xim.wechat.officalAccount.sendMessage;
import com.cpic.xim.config.WeatherDisasterNotifyConfig;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.*;
public class AppMain
{
private static final String CONFIG_FILE_PATH = "./config.json";
private final static String LOG_FILE_PATH = "./app.log";
public static void main( String[] args )
{
String json;
WeatherDisasterNotifyConfig config = null;
QWeatherDisasterWarning warning = null;
Logger logger = null;
// 配置logger
try
{
setRootLogger();
logger = Logger.getLogger( "com.cpicxim" );
}
catch ( IOException error )
{
System.out.println( "配置logger失败原因" + error.getMessage() );
return;
}
// 读取配置
try
{
config = WeatherDisasterNotifyConfig.load( CONFIG_FILE_PATH );
config = WeatherDisasterNotifyConfig.getConfig();
}
catch ( IOException error )
{
System.out.println( "读取配置文件失败!" );
System.out.println( error.getMessage() );
logger.log( Level.SEVERE, "读取配置文件失败:{0}", error.getMessage() );
return;
}
@@ -53,22 +74,69 @@ public class AppMain
userKey, city.getCityCode() );
warning = WeatherDisasterWarningGrabber.convertWeatherDisasterWarning( json );
logger.log( Level.INFO, "查询{0}天气预警,结果:{1}。", new Object[]
{ city.getCityName(), json} );
// 判断是否有警报
if ( warning.getWarning().isEmpty() == true)
{
continue;
}
logger.log( Level.INFO, "查询{0}天气预警,发送日志。", new Object[]
{ city.getCityName()} );
sendMessage.sendWeatherDisasterWarning( config.getWechatOfficalAccountURL(),
warning );
logger.log( Level.INFO, "{0}天气预警,日志发送成功。", new Object[]
{ city.getCityName()} );
sendMessage.saveWeatherDisasterWarning( city.getCityName(), warning );
}
catch ( IOException error )
{
System.out.println( "查询" + city.getCityName() + "出现异常!" );
System.out.println( error.getMessage() );
continue;
logger.log( Level.SEVERE, "查询 {0} 出现异常:{1}。", new Object[]
{ city.getCityName(), error.getMessage()} );
}
catch ( SQLException error )
{
logger.log( Level.SEVERE, "查询 {0} 写入数据库失败:{1}。", new Object[]
{ city.getCityName(), error.getMessage()} );
}
catch ( ClassNotFoundException error )
{
logger.log( Level.SEVERE, "查询 {0} 加载oracle驱动失败:{1}。", new Object[]
{ city.getCityName(), error.getMessage()} );
}
catch ( Exception error )
{
logger.log( Level.SEVERE, "查询 {0} 出现未知错误:{1}。", new Object[]
{ city.getCityName(), error.getMessage()} );
}
}
}
/**
* 设置JUL的logger。
*/
private static void setRootLogger() throws IOException
{
Logger rootLogger = Logger.getLogger( "com.cpicxim" );
ConsoleHandler consoleHandler = new ConsoleHandler();
FileHandler fileHandler = new FileHandler( LOG_FILE_PATH );
SimpleFormatter formatter = new SimpleFormatter();
consoleHandler.setFormatter( formatter );
fileHandler.setFormatter( formatter );
rootLogger.addHandler( consoleHandler );
rootLogger.addHandler( fileHandler );
rootLogger.setUseParentHandlers( false );
rootLogger.setLevel( Level.ALL );
}
}

View File

@@ -1,6 +1,7 @@
package com.cpic.xim.config;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;
@@ -11,13 +12,21 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategy;
public class WeatherDisasterNotifyConfig
{
private static final int BUFFER_SIZE = 1024;
private static final String CONFIG_FILE_CHARSET = "UTF-8";
private static final String CONFIG_FILE_PATH = "./config.json";
private static WeatherDisasterNotifyConfig appConfig = null;
public static WeatherDisasterNotifyConfig load( String filePath ) throws IOException
public static WeatherDisasterNotifyConfig getConfig() throws IOException
{
WeatherDisasterNotifyConfig config = null;
if ( appConfig != null)
{
return appConfig;
}
ObjectMapper mapper = new ObjectMapper();
FileReader configFile = null;
FileInputStream configFile = null;
InputStreamReader in = null;
StringBuffer json = null;
char[] buffer = new char[BUFFER_SIZE];
@@ -26,19 +35,20 @@ public class WeatherDisasterNotifyConfig
try
{
configFile = new FileReader( filePath );
configFile = new FileInputStream( CONFIG_FILE_PATH );
in = new InputStreamReader( configFile, CONFIG_FILE_CHARSET );
json = new StringBuffer();
int length = configFile.read( buffer );
int length = in.read( buffer );
while (length != -1)
{
json.append( buffer );
length = configFile.read( buffer );
length = in.read( buffer );
}
config = mapper.readValue( json.toString(), WeatherDisasterNotifyConfig.class );
appConfig = mapper.readValue( json.toString(), WeatherDisasterNotifyConfig.class );
}
finally
{
@@ -55,7 +65,7 @@ public class WeatherDisasterNotifyConfig
}
}
return config;
return appConfig;
}
public WeatherDisasterNotifyConfig()
@@ -129,6 +139,4 @@ public class WeatherDisasterNotifyConfig
private String wechatOfficalAccountURL;
private Vector<City> cities;
private Vector<CpicxmStuff> notifyStuffs;
}

View File

@@ -2,7 +2,7 @@
* @Author: Kane
* @Date: 2022-04-22 17:33:30
* @LastEditors: Kane
* @LastEditTime: 2022-04-23 23:50:20
* @LastEditTime: 2022-04-27 16:53:13
* @FilePath: \DisasterWarning\src\main\java\com\cpic\xim\config\db\DBTable.java
* @Description:
*
@@ -12,6 +12,8 @@ package com.cpic.xim.config.db;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DBTable
{
public DBTable()
@@ -59,6 +61,9 @@ public class DBTable
return Objects.hash( tableName, tableDescription );
}
@JsonProperty( "table_name")
private String tableName;
@JsonProperty( "table_description")
private String tableDescription;
}

View File

@@ -2,7 +2,7 @@
* @Author: Kane
* @Date: 2022-04-22 17:33:30
* @LastEditors: Kane
* @LastEditTime: 2022-04-23 23:51:46
* @LastEditTime: 2022-04-25 21:33:07
* @FilePath: \DisasterWarning\src\main\java\com\cpic\xim\config\db\OracleConfig.java
* @Description:
*
@@ -11,7 +11,11 @@
package com.cpic.xim.config.db;
import java.util.Vector;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @Description oracle数据库相关参数对象。
*/
public class OracleConfig
{
@@ -45,6 +49,17 @@ public class OracleConfig
this.jdbcURL = jdbcURL;
}
public String getTableSpace()
{
return tableSpace;
}
public void setTableSpace( String tableSpace )
{
this.tableSpace = tableSpace;
}
public String getUserName()
{
return userName;
@@ -75,10 +90,24 @@ public class OracleConfig
this.tables = tables;
}
@JsonProperty( "tns_name")
private String tnsName;
@JsonProperty( "ip_addr")
private String ipAddr;
@JsonProperty( "jdbc_url")
private String jdbcURL;
@JsonProperty( "table_space")
private String tableSpace;
@JsonProperty( "user_name")
private String userName;
@JsonProperty( "password")
private String password;
@JsonProperty( "tables")
private Vector<DBTable> tables;
}

View File

@@ -0,0 +1,77 @@
/*
* @Author: Kane
* @Date: 2022-04-25 21:45:12
* @LastEditors: Kane
* @LastEditTime: 2022-05-03 22:34:37
* @FilePath: \DisasterWarning\src\main\java\com\cpic\xim\config\db\OracleConfigManager.java
* @Description: oracle数据库配置文件加载类
*
* Copyright (c) ${2022} by Kane, All Rights Reserved.
*/
package com.cpic.xim.config.db;
import java.io.*;
import com.fasterxml.jackson.databind.*;
public class OracleConfigManager
{
private static final String CONFIG_FILE_PATH = "./db.json";
private static final String CONFIG_FILE_CHARSET = "UTF-8";
private static final int BUFFER_SIZE = 1024;
private static OracleConfig dbConfig = null;
private OracleConfigManager()
{}
public static OracleConfig getOracleConfig() throws IOException
{
FileInputStream file = null;
InputStreamReader in = null;
StringBuffer json = null;
char[] buffer = new char[BUFFER_SIZE];
if ( dbConfig != null)
{
return dbConfig;
}
try
{
file = new FileInputStream( CONFIG_FILE_PATH );
in = new InputStreamReader( file, CONFIG_FILE_CHARSET );
json = new StringBuffer();
int count = in.read( buffer );
while (count != -1)
{
json.append( buffer );
count = in.read( buffer );
}
ObjectMapper mapper = new ObjectMapper();
dbConfig = mapper.readValue( json.toString(), OracleConfig.class );
}
catch ( IOException error )
{
throw error;
}
finally
{
try
{
file.close();
}
catch ( Exception error )
{
error.printStackTrace();
}
}
return dbConfig;
}
}

View File

@@ -1,23 +1,24 @@
/*
* @Author: Kane
* @Date: 2022-04-24 10:21:46
* @LastEditors: Kane
* @LastEditTime: 2022-04-24 11:28:58
* @FilePath: \DisasterWarning\src\main\java\com\cpic\xim\notify\disaster\QWeatherDisasterWarning.java
* @Description:
*
* Copyright (c) ${2022} by Kane, All Rights Reserved.
*/
package com.cpic.xim.notify.disaster;
import java.util.Date;
import java.util.Vector;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
public class QWeatherDisasterWarning
{
public QWeatherDisasterWarning( String code,
String updateTime,
String fxLink,
Vector<QWeatherDisasterWarningItem> warning,
QWeatherDisasterWarningRefer refer )
{
this.code = code;
this.updateTime = updateTime;
this.fxLink = fxLink;
this.warning = warning;
this.refer = refer;
}
public QWeatherDisasterWarning() {}
public QWeatherDisasterWarning()
{}
public String getCode()
{
@@ -29,12 +30,12 @@ public class QWeatherDisasterWarning
this.code = code;
}
public String getUpdateTime()
public Date getUpdateTime()
{
return updateTime;
}
public void setUpdateTime( String updateTime )
public void setUpdateTime( Date updateTime )
{
this.updateTime = updateTime;
}
@@ -69,9 +70,19 @@ public class QWeatherDisasterWarning
this.refer = refer;
}
@JsonProperty( "code")
private String code;
private String updateTime;
@JsonProperty( "updateTime")
@JsonFormat( pattern = "yyyy-MM-dd\'T\'HH:mmXXX")
private Date updateTime;
@JsonProperty( "fxLink")
private String fxLink;
@JsonProperty( "warning")
private Vector<QWeatherDisasterWarningItem> warning;
@JsonProperty( "refer")
private QWeatherDisasterWarningRefer refer;
}

View File

@@ -1,23 +1,19 @@
package com.cpic.xim.notify.disaster;
import java.util.Date;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
//import com.fasterxml.jackson.annotation.JsonIgnore;
public class QWeatherDisasterWarningItem
{
public QWeatherDisasterWarningItem() {}
public QWeatherDisasterWarningItem( String id,
String sender,
String pubTime,
String title,
String status,
String level,
String type,
String typeName,
String text,
String related,
public QWeatherDisasterWarningItem()
{}
public QWeatherDisasterWarningItem( String id, String sender, Date pubTime, String title,
String status, String level, String type, String typeName, String text, String related,
String urgency, String certainty)
{
this.id = id;
@@ -46,34 +42,20 @@ public class QWeatherDisasterWarningItem
return false;
}
QWeatherDisasterWarningItem that = (QWeatherDisasterWarningItem) o;
return id.equals( that.id ) && Objects.equals( sender, that.sender ) && Objects.equals( pubTime,
that.pubTime ) && Objects.equals(
title,
that.title ) && Objects.equals( status, that.status ) && Objects.equals( level,
that.level ) && Objects.equals(
type,
that.type ) && Objects.equals( typeName, that.typeName ) && Objects.equals( text,
that.text ) && Objects.equals(
related,
that.related ) && Objects.equals( urgency, that.urgency ) && Objects.equals( certainty,
that.certainty );
return id.equals( that.id ) && Objects.equals( sender, that.sender )
&& Objects.equals( pubTime, that.pubTime ) && Objects.equals( title, that.title )
&& Objects.equals( status, that.status ) && Objects.equals( level, that.level )
&& Objects.equals( type, that.type ) && Objects.equals( typeName, that.typeName )
&& Objects.equals( text, that.text ) && Objects.equals( related, that.related )
&& Objects.equals( urgency, that.urgency )
&& Objects.equals( certainty, that.certainty );
}
@Override
public int hashCode()
{
return Objects.hash( id,
sender,
pubTime,
title,
status,
level,
type,
typeName,
text,
related,
urgency,
certainty );
return Objects.hash( id, sender, pubTime, title, status, level, type, typeName, text,
related, urgency, certainty );
}
public String getId()
@@ -96,12 +78,12 @@ public class QWeatherDisasterWarningItem
this.sender = sender;
}
public String getPubTime()
public Date getPubTime()
{
return pubTime;
}
public void setPubTime( String pubTime )
public void setPubTime( Date pubTime )
{
this.pubTime = pubTime;
}
@@ -198,8 +180,11 @@ public class QWeatherDisasterWarningItem
private String id;
private String sender;
@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
private String pubTime;
@JsonProperty( "pubTime")
@JsonFormat( shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd\'T\'HH:mmXXX")
private Date pubTime;
private String title;
private String status;
private String level;

View File

@@ -2,7 +2,7 @@
* @Author: Kane
* @Date: 2022-04-22 10:53:49
* @LastEditors: Kane
* @LastEditTime: 2022-04-23 23:46:54
* @LastEditTime: 2022-05-06 11:14:32
* @FilePath: \DisasterWarning\src\main\java\com\cpic\xim\wechat\officalAccount\sendMessage.java
* @Description: 用来推送公众号消息的程序库。
*
@@ -10,13 +10,20 @@
*/
package com.cpic.xim.wechat.officalAccount;
import com.cpic.xim.config.db.OracleConfigManager;
import com.cpic.xim.config.db.OracleConfig;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Vector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.cpic.xim.notify.disaster.*;
import com.cpic.xim.httpUtil.HttpUtils;
@@ -31,7 +38,7 @@ public class sendMessage
/**
* 推送天气灾害预警!接口文档参考 彭奕洁 编写《消息发送接口调用文档》
*
* 使用 post 方式,请求体内容以最基础的 post 格式。
* @param officalAccountURL 产险厦门分公司公众号接口网址
* @param warning 灾害预警对象
*/
@@ -57,7 +64,6 @@ public class sendMessage
String color = warningLevel.keySet().contains( item.getLevel() )
? warningLevel.get( item.getLevel() )
: "#000000";
requestBody = new StringBuilder();
requestBody.append( "tplid=57&groupid=1&first=尊敬的#realname#,您好!&" );
@@ -76,6 +82,181 @@ public class sendMessage
}
}
/**
* 检查预警是否已经推送过,通过 QWeatherDisasterWarningItem 对象的 id 属性。
* 查询 oracle xmcx1 数据库 wechat 表空间下 weather_disaster_notify 表,
* 统计 warningID 的数量如果不为0,说明该预警已经保存过,视为已经推送过。
* @param warningID 预警的id
* @return 如果推送过返回false否则返回 true。
*/
public static boolean checkWarningHasSended( String warningID )
throws ClassNotFoundException, SQLException, IOException
{
boolean result = false;
OracleConfig dbConfig = OracleConfigManager.getOracleConfig();;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String jdbcURL = dbConfig.getJdbcURL();
String userName = dbConfig.getUserName();
String password = dbConfig.getPassword();
String sql = "select count(*) from weather_disaster_notify where notify_id = ?";
// Logger logger = Logger.getLogger( "com.cpicxim.wechat.officalAccount.sendMessage" );
try
{
Class.forName( "oracle.jdbc.driver.OracleDriver" );
conn = DriverManager.getConnection( jdbcURL, userName, password );
stmt = conn.prepareStatement( sql );
stmt.setString( 1, warningID );
rs = stmt.executeQuery();
if ( rs.next() && rs.getInt( 1 ) == 0)
{
result = true;
}
}
finally
{
try
{
if ( rs != null)
{
rs.close();
}
}
catch ( Exception error )
{
error.printStackTrace();
}
try
{
if ( stmt != null)
{
stmt.close();
}
}
catch ( Exception error )
{
error.printStackTrace();
}
try
{
if ( conn != null)
{
conn.close();
}
}
catch ( Exception error )
{
error.printStackTrace();
}
}
return result;
}
/**
* 保存天气预警警报数据。
* 保存至 oracle xmcx1 数据库 wechat 表空间下 weather_disaster_notify 表。
* 保存的数据用来判断预警是否已经推送过,以防止反复推送数据。
* @param city 城市名称
* @param warning 预警数据,为 QWeatherDisasterWarningItem 对象。
* @throws SQLException 执行sql时可能抛出的异常。出现sql异常就回滚事务。
* @throws IOException 读取数据库配置文件时可能抛出的异常。
* @throws ClassNotFoundException 加载oracle jdbc驱动时可能抛出的异常。
*/
public static void saveWeatherDisasterWarning( String city, QWeatherDisasterWarning warnings )
throws SQLException, IOException, ClassNotFoundException
{
Connection conn = null;
PreparedStatement stmt = null;
String sql = "insert into weather_disaster_notify(notify_id, sender, city,"
+ "warning_level, warning_type_code, warning_type_name, title,"
+ "text, pub_time) values( ?,?,?,?,?,?,?,?,?)";
OracleConfig dbConfig = OracleConfigManager.getOracleConfig();
String jdbcURL = dbConfig.getJdbcURL();
String userName = dbConfig.getUserName();
String password = dbConfig.getPassword();
try
{
Class.forName( "oracle.jdbc.driver.OracleDriver" );
conn = DriverManager.getConnection( jdbcURL, userName, password );
stmt = conn.prepareStatement( sql );
for ( QWeatherDisasterWarningItem warning : warnings.getWarning() )
{
java.sql.Timestamp pubTime =
new java.sql.Timestamp( warning.getPubTime().getTime() );
stmt.setString( 1, warning.getId() );
stmt.setString( 2, warning.getSender() );
stmt.setString( 3, city );
stmt.setString( 4, warning.getLevel() );
stmt.setString( 5, warning.getType() );
stmt.setString( 6, warning.getTypeName() );
stmt.setString( 7, warning.getTitle() );
stmt.setString( 8, warning.getText() );
stmt.setTimestamp( 9, pubTime );
stmt.execute();
}
// 没有问题就提交
conn.commit();
}
catch ( SQLException error )
{
// 出现sql错误就回滚
if ( conn != null)
{
conn.rollback();
}
throw error;
}
finally
{
try
{
if ( stmt != null)
{
stmt.close();
}
}
catch ( Exception error )
{
error.printStackTrace();
}
try
{
if ( conn != null)
{
conn.close();
}
}
catch ( Exception error )
{
error.printStackTrace();
}
}
}
static
{
// 预警级别色彩

View File

@@ -2,7 +2,7 @@
* @Author: Kane
* @Date: 2022-04-22 10:53:49
* @LastEditors: Kane
* @LastEditTime: 2022-04-23 23:44:54
* @LastEditTime: 2022-05-06 11:14:35
* @FilePath: \DisasterWarning\src\test\java\com\cpic\xim\wechat\officalAccount\sendMessageTest.java
* @Description:
*
@@ -16,6 +16,7 @@ import org.junit.Test;
import static org.junit.Assert.*;
import com.cpic.xim.httpUtil.*;
import java.io.IOException;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -72,11 +73,29 @@ public class sendMessageTest
QWeatherDisasterWarning warning =
mapper.readValue( warningJSON, QWeatherDisasterWarning.class );
sendMessage.sendWeatherDisasterWarning( url, warning );
String city = "东山县";
sendMessage.saveWeatherDisasterWarning( city, warning );
}
catch ( Exception error )
{
fail( error.getMessage() );
}
}
// @Test
public void testCheckWarningHasSended()
{
String warningID = "10123060820220422061200476313081";
try
{
sendMessage.checkWarningHasSended( warningID );
}
catch ( Exception error )
{
error.printStackTrace();
}
}
}