first commit

This commit is contained in:
super-l
2017-04-11 19:35:14 +08:00
parent cdf35b31a2
commit 7d49057a28
16 changed files with 623 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.idea
.DS_Store

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="commons-logging-1.1.1" level="project" />
<orderEntry type="library" name="httpclient-4.5.1" level="project" />
<orderEntry type="library" name="httpcore-4.4.4" level="project" />
</component>
</module>

BIN
lib/commons-logging-1.1.1.jar Executable file

Binary file not shown.

BIN
lib/httpclient-4.5.1.jar Executable file

Binary file not shown.

BIN
lib/httpcore-4.4.4.jar Executable file

Binary file not shown.

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: com.superl.Main

3
src/META-INF/MANIFEST.MF Normal file
View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: com.superl.Main

View File

@@ -0,0 +1,132 @@
package com.superl;
/**
* @Package com.superl
* @Description 创蓝短信接口
* @Author superl www.superl.org
* @Date 2017/4/11 下午5:59
* @Version V1.0
*/
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class ChuanglanSMS {
private CloseableHttpClient client;
private String account;
private String password;
private static final String SEND_URL="http://222.73.117.138:7891/mt";
private static final String QUERY_URL="http://222.73.117.138:7891/bi";
private static final String INTERNATIONAL_URL="http://222.73.117.140:8044/mt";
public ChuanglanSMS(String account,String password){
this.account = account;
this.password = password;
client = HttpClients.createDefault();
//System.out.println(account);
}
public CloseableHttpResponse sendMessage(String phone, String content) {
String encodedContent = null;
try {
encodedContent = URLEncoder.encode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuffer strBuf = new StringBuffer(SEND_URL);
strBuf.append("?un=").append(account);
strBuf.append("&pw=").append(password);
strBuf.append("&da=").append(phone);
strBuf.append("&sm=").append(encodedContent);
strBuf.append("&dc=15&rd=1&rf=2&tf=3");
HttpGet get = new HttpGet( strBuf.toString() );
try {
return client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public CloseableHttpResponse queryBalance() {
StringBuffer strBuf = new StringBuffer(QUERY_URL);
strBuf.append("?un=").append(account);
strBuf.append("&pw=").append(password);
strBuf.append("&rf=2");
HttpGet get = new HttpGet( strBuf.toString() );
try {
return client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public CloseableHttpResponse sendInternationalMessage(String phone, String content) {
String encodedContent = null;
try {
encodedContent = URLEncoder.encode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuffer strBuf = new StringBuffer(INTERNATIONAL_URL);
strBuf.append("?un=").append(account);
strBuf.append("&pw=").append(password);
strBuf.append("&da=").append(phone);
strBuf.append("&sm=").append(encodedContent);
strBuf.append("&dc=15&rd=1&rf=2&tf=3");
HttpGet get = new HttpGet( strBuf.toString() );
try {
return client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void close() {
if(client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

30
src/com/superl/Main.java Normal file
View File

@@ -0,0 +1,30 @@
package com.superl;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException{
System.err.println("start MyWatcherService ...");
/*
ChuanglanSMS client = new ChuanglanSMS("xxxxx","xxxxx");
CloseableHttpResponse response = null;
try {
//发送短信
response = client.sendMessage("181xxxxxxxx","验证码为xxxxxxxx");
if(response != null && response.getStatusLine().getStatusCode()==200){
System.out.println(EntityUtils.toString(response.getEntity()));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
client.close();
*/
MyService myWatcherService = new MyService();
myWatcherService.initialize();
myWatcherService.doMonitor();
}
}

View File

@@ -0,0 +1,312 @@
package com.superl;
/**
* @author superl www.superl.org
* @version V1.0
* @Package com.superl
* @Description 监控功能
* @date 2017/4/11 下午6:07
*/
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.ParseException;
import java.io.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.Properties;
import static java.nio.file.StandardWatchEventKinds.*;
public class MyService {
private WatchService watchService = null;
private String filePrefix;
private String monitoredPath;
private Boolean checkPrefix;
private Boolean monitoredDir;
private Boolean monitoredMD;
private String ruledoutDir;
private String mobileNum;
private String userName;
private String passWord;
private String smsContent;
private String eventMethod;
public void initialize() throws IOException{
Properties prop = new Properties();
InputStream inputStream = new FileInputStream("config.properties");
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
prop.load(bf);
inputStream.close(); // 关闭流
/*
InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
Properties prop = new Properties();
prop.load(in);
*/
filePrefix = prop.getProperty("file_prefix");
monitoredPath = prop.getProperty("monitored_path");
checkPrefix = new Boolean(prop.getProperty("check_prefix"));
monitoredDir = new Boolean(prop.getProperty("monitored_directory"));
monitoredMD = new Boolean(prop.getProperty("monitored_move_delete"));
ruledoutDir = prop.getProperty("ruledout_dir");
mobileNum = prop.getProperty("mobile");
userName = prop.getProperty("username");
passWord = prop.getProperty("password");
//System.out.println(ruledoutDir); 测试是否中文乱码
watchService = FileSystems.getDefault().newWatchService();
Paths.get(monitoredPath).register(watchService, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
File file = new File(monitoredPath);
LinkedList<File> fList = new LinkedList<File>();
fList.addLast(file);
while (fList.size() > 0 ) {
File f = fList.removeFirst();
if(f.listFiles() == null)
continue;
for(File file2 : f.listFiles()){
if (file2.isDirectory()){//下一级目录
fList.addLast(file2);
//依次注册子目录
Paths.get(file2.getAbsolutePath()).register(watchService
, StandardWatchEventKinds.ENTRY_CREATE
, StandardWatchEventKinds.ENTRY_MODIFY
, StandardWatchEventKinds.ENTRY_DELETE);
}
}
}
}
public void doMonitor() throws InterruptedException,IOException{
final Properties PROPERTIES = new Properties(System.getProperties());
String separator = PROPERTIES.getProperty("file.separator");
while(true){
try {
WatchKey key = watchService.take();
for(WatchEvent<?> event : key.pollEvents()){
WatchEvent.Kind kind = event.kind();
if(kind == OVERFLOW){
//事件可能lost or discarded
continue;
}
WatchEvent<Path> e = (WatchEvent<Path>)event;
//获取路径
Path path = (Path) key.watchable();
//获取分隔符号
String fullpath = path.toString()+separator;
//获取文件名
Path fileName = e.context();
//拼接文件名称和路径
String filepath = fullpath+fileName;
//获取文件后缀
String prefix = fileName.toString().substring(fileName.toString().lastIndexOf(".")+1);
File theFile = new File(filepath);
//判断是文件还是目录
if(theFile.isFile()){
//判断是否是白名单目录
String[] ruledoutDirArray = ruledoutDir.split(",");
Boolean haveStr = false;
if(ruledoutDirArray!=null||ruledoutDirArray.length!=0){
haveStr = Arrays.asList(ruledoutDirArray).contains(path.toString());
}else{
haveStr = false;
}
if(!haveStr){
if(checkPrefix){
if(prefix.equals(filePrefix)){
if(kind.toString().equals("ENTRY_CREATE")){
eventMethod = "被新建";
}else if (kind.toString().equals("ENTRY_MODIFY")){
eventMethod = "被修改";
}else{
eventMethod = "被操作";
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
smsContent = "文件:"+filepath+eventMethod+",时间:"+df.format(new Date());
//输出提示信息
System.out.println(smsContent);
//发送提示信息到手机短信
ChuanglanSMS client = new ChuanglanSMS(userName,passWord);
CloseableHttpResponse response = null;
try {
response = client.sendMessage(mobileNum,smsContent);
if(response != null && response.getStatusLine().getStatusCode()==200){
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("短信发送成功,内容为:"+smsContent);
}
}catch (ParseException p1) {
System.out.println("短信发送成失败");
p1.printStackTrace();
}catch (IOException i1) {
System.out.println("短信发送成失败");
i1.printStackTrace();
}
client.close();
}
}else{
if(kind.toString().equals("ENTRY_CREATE")){
eventMethod = "被新建";
}else if (kind.toString().equals("ENTRY_MODIFY")){
eventMethod = "被修改";
}else{
eventMethod = "被操作";
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
smsContent = "文件:"+filepath+eventMethod+",时间:"+df.format(new Date());
//输出提示信息
System.out.println(smsContent);
//发送提示信息到手机短信
ChuanglanSMS client = new ChuanglanSMS(userName,passWord);
CloseableHttpResponse response = null;
try {
response = client.sendMessage(mobileNum,smsContent);
if(response != null && response.getStatusLine().getStatusCode()==200){
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("短信发送成功,内容为:"+smsContent);
}
}catch (ParseException p1) {
System.out.println("短信发送成失败");
p1.printStackTrace();
}catch (IOException i1) {
System.out.println("短信发送成失败");
i1.printStackTrace();
}
client.close();
}
}else{
//不监控白名单目录
}
}else if(theFile.isDirectory()){
//System.out.println("这是目录类型");
//判断是否是白名单目录
String[] ruledoutDirArray = ruledoutDir.split("||");
Boolean haveStr;
if(ruledoutDirArray!=null||ruledoutDirArray.length!=0){
haveStr = Arrays.asList(ruledoutDirArray).contains(fullpath);
}else{
haveStr = false;
}
if(!haveStr){
if(monitoredDir){
if(kind.toString().equals("ENTRY_CREATE")){
eventMethod = "被新建";
}else if (kind.toString().equals("ENTRY_MODIFY")){
eventMethod = "被修改";
}else{
eventMethod = "被操作";
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
smsContent = "文件:"+filepath+eventMethod+",时间:"+df.format(new Date());
//输出提示信息
System.out.println(smsContent);
//发送提示信息到手机短信
ChuanglanSMS client = new ChuanglanSMS(userName,passWord);
CloseableHttpResponse response = null;
try {
response = client.sendMessage(mobileNum,smsContent);
if(response != null && response.getStatusLine().getStatusCode()==200){
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("短信发送成功,内容为:"+smsContent);
}
}catch (ParseException p1) {
System.out.println("短信发送成失败");
p1.printStackTrace();
}catch (IOException i1) {
System.out.println("短信发送成失败");
i1.printStackTrace();
}
client.close();
}else{
//不监控目录类型
}
}
}else{
//文件被删除,被移动
//判断是否是白名单目录
String[] ruledoutDirArray = ruledoutDir.split("||");
Boolean haveStr;
if(ruledoutDirArray!=null||ruledoutDirArray.length!=0){
haveStr = Arrays.asList(ruledoutDirArray).contains(fullpath);
}else{
haveStr = false;
}
if(!haveStr){
if(monitoredMD){
if(checkPrefix){
if(prefix.equals(filePrefix)){
if(kind.toString().equals("ENTRY_CREATE")){
eventMethod = "新建操作";
}else if (kind.toString().equals("ENTRY_MODIFY")){
eventMethod = "修改操作";
}else{
eventMethod = "其他操作";
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
smsContent = "文件:"+filepath+" 发生了"+eventMethod+" 操作时间:"+df.format(new Date());
System.out.println(smsContent);
ReadWriteFile myfile = new ReadWriteFile();
myfile.creatTxtFile();
myfile.writeTxtFile(smsContent);
}
}else{
//System.out.printf("Event %s has happened,which fileName is %s%n",kind,filepath);
if(kind.toString().equals("ENTRY_CREATE")){
eventMethod = "新建操作";
}else if (kind.toString().equals("ENTRY_MODIFY")){
eventMethod = "修改操作";
}else{
eventMethod = "其他操作";
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
smsContent = "文件:"+filepath+" 发生了"+eventMethod+" 操作时间:"+df.format(new Date());
System.out.println(smsContent);
ReadWriteFile myfile = new ReadWriteFile();
myfile.creatTxtFile();
myfile.writeTxtFile(smsContent);
}
}else{
//配置文件设置了不监控文件被删除和移动操作
}
}
}
}
if(!key.reset()){
break;
}
} catch (InterruptedException e) {
System.out.println("InterruptedException: " + e.getMessage());
}
}
}
}

View File

@@ -0,0 +1,127 @@
package com.superl;
/**
* @author superl www.superl.org
* @version V1.0
* @Package com.superl
* @Description 读写文件操作类
* @date 2017/4/11 下午6:09
*/
import java.io.*;
public class ReadWriteFile {
public static BufferedReader bufread;
//指定文件路径和名称
private static String path = "log.txt";
private static File filename = new File(path);
private static String readStr ="";
/**
* 创建文本文件.
* @throws IOException
*
*/
public static void creatTxtFile() throws IOException{
if (!filename.exists()) {
filename.createNewFile();
//System.err.println(filename + "已创建!");
}
}
/**
* 读取文本文件.
*
*/
public static String readTxtFile(){
String read;
FileReader fileread;
try {
fileread = new FileReader(filename);
bufread = new BufferedReader(fileread);
try {
while ((read = bufread.readLine()) != null) {
readStr = readStr + read+ "\r\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("文件内容是:"+ "\r\n" + readStr);
return readStr;
}
/**
* 写文件
*/
public static void writeTxtFile(String newStr) throws IOException{
//先读取原有文件内容,然后进行写入操作
String filein = newStr + "\r\n" + readStr + "\r\n";
RandomAccessFile mm = null;
try {
mm = new RandomAccessFile(filename, "rw");
mm.writeBytes(filein);
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
} finally {
if (mm != null) {
try {
mm.close();
} catch (IOException e2) {
// TODO 自动生成 catch 块
e2.printStackTrace();
}
}
}
}
/**
* 将文件中指定内容的第一行替换为其它内容.
*
* @param oldStr 查找内容
* @param replaceStr 替换内容
*/
public static void replaceTxtByStr(String oldStr,String replaceStr) {
String temp = "";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该行前面的内容
for (int j = 1; (temp = br.readLine()) != null
&& !temp.equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
// 将内容插入
buf = buf.append(replaceStr);
// 保存该行后面的内容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}