做了一个简单的服务器监视程序。还有些问题没解决 SocketthreadSUNF#.net
程序员文章站
2022-07-05 22:26:30
...
服务器经常不堪重负挂掉,人工重启太麻烦。因此决定写一个自动监视服务器的东东,其中涉及到文件操作、动态编译并执行java文件、模拟Http提交、线程控制等东西。稍作修改也可以做成一个提醒程序。
/**
* This class define some functions to be executed.
* The class to be executed by AutoExec must content a main method.
* @author Einstein
* Create date 2005-11-1
*/
package myJava;
import java.util.Date;
import java.text.SimpleDateFormat;
public class ExecuteJava implements Runnable
{
public boolean serverAlive(String host,int port,String ncFileName)
{
PostData pd=new PostData(host,port);
pd.myNC(ncFileName);
Date now=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeString=sdf.format(now);
//System.out.println(pd.getReceive());
if(pd.getReceive().indexOf("HTTP/1.1 200 OK")<0)
{
System.out.println("["+timeString+"] The server \""+host+"\" has been shutdown!");
return false;
}
else
{
System.out.println("["+timeString+"] The server \""+host+"\" is all right!");
System.out.println("I will see it latter...");
}
pd.close();
return true;
}
public void run()
{
serverAlive("www.c-gec.com",80,"f:\\nc.txt");
}
public static void main(String[] args)
{
System.out.println("=======================================================");
System.out.println("= ServerStateWatcher V1.0 =");
System.out.println("= Code by Einstein =");
System.out.println("= Email:zhuangEinstein@tom.com =");
System.out.println("=======================================================");
String host="www.cnb2b.cn";
String ncFile="f:\\nc.txt";
int port=80;
ExecuteJava ej=new ExecuteJava();
if(!ej.serverAlive(host,port,ncFile))
{
int aliveNum=0;
for(int i=0;i<10;i++)
{//do this repeating to confirm the host is over....
if(ej.serverAlive(host,port,ncFile))aliveNum++;
if(aliveNum>2)break;
}
if(aliveNum<2)
{//do some reboot job when the server is not alive.
System.out.println("The server "+host+" may be shutdown so let's reboot it now!");
ExecuteFile ef=new ExecuteFile("rebootTomcat.bat");
ef.execute();
}
}
}
}
/**
* 执行外部命令或者外部文件
* @author Einstein
* Email: zhuangEinstein@tom.com
* 创建日期 2005-10-29
*/
package myJava;
import java.io.*;
public class ExecuteFile
{
private String cmd;
private String[] argv;
private String returnString="";
ExecuteFile()
{
this.cmd=null;
this.argv=null;
}
ExecuteFile(String command)
{
this.cmd=command;
}
ExecuteFile(String command,String[] argvs)
{
this.cmd=command;
this.argv=argvs;
}
public String[] getArgv() {
return argv;
}
public void setArgv(String[] argv) {
this.argv = argv;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getReturnString()
{
return returnString;
}
public boolean execute(String cmd,String[] argv)
{
try
{
this.setCmd(cmd);
this.setArgv(argv);
Process p=Runtime.getRuntime().exec("cmd /c "+this.cmd,this.argv);
InputStreamReader isr = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader (isr);
String line = null;
this.returnString="";
while ((line = input.readLine ()) != null)
{//捕获新进程的控制台输出,并作为返回结果存在returnString中
returnString+=line+"\n";
//System.out.println(line);
}
return true;
}catch(Exception ex){return false;}
}
public boolean execute(String cmd)
{
try
{
this.setCmd(cmd);
this.execute(this.cmd,null);
return true;
}catch(Exception ex){return false;}
}
public boolean execute()
{
try
{
if(this.cmd!=null&&this.argv!=null)
{
return this.execute(this.cmd,this.argv);
}
else
{
return this.execute(this.cmd);
}
}catch(Exception ex){return false;}
}
}
/**
* @(#)PostData.java 05/10/31
*/
package myJava;
import java.net.*;
import java.io.*;
/**
* This Class is a Data-Post class.It is use to
* send string data or byte data to a specify host whith specify port.
* @author Einstein
* Email: zhuangEinstein@tom.com
* Date: 2005-10-31
*/
public class PostData
{
private final int MAX_PORT=65535;
private int MAX_WAIT_TIME=20;//maxt time to wait for the socket receive data;depend on your net state.
private String host="127.0.0.1";
private String postContent="";
private int port=80;
private Socket socket=null;
boolean connected=false;
private String receive="";
/**
* The construction functions.
*/
PostData(){}
PostData(String host,int port)
{
if(port<0||port>MAX_PORT)
{
System.out.println("The port must be between 0 and 65535!");
return;
}
if(host==null||host.trim().equals(""))
{
System.out.println("The host name can't be null!");
return;
}
this.host=host;
this.port=port;
try
{
socket=new Socket(host,port);
connected=true;
}
catch(Exception ex)
{
System.out.println("Can't connect to the server named \""+host+"\" and port "+port);
socket=null;this.host=null;this.port=0;connected=false;
}
}
/**
* Set or get some parameters of this Object whose attribute is readable and writeable.
*/
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public String getReceive() {
return receive;
}
/**
* Connect to the server after set parameters which are needed.
* Return true when success or false when fail.
* @return boolean
*/
public boolean connect()
{
return this.connect(this.host,this.port);
}
public boolean connect(String host,int port)
{
if(host!=null&&port>0)
{
this.host=host;
this.port=port;
try
{
socket=new Socket(this.host,this.port);
connected=true;
}
catch(Exception ex)
{
System.out.println("Can't connect to the server named \""+host+"\" and port "+port);
socket=null;this.host=null;this.port=0;connected=false;return false;
}
return true;
}
else
{
return false;
}
}
public boolean sendData(String content)
{
if(!this.connected||this.socket==null)
{
System.out.println("You can't send data before connect to a host!");
return false;
}
try
{
PrintWriter pout=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
String[] sendContents=content.split("\\\\n\\\\r");
for(int i=0;i<sendContents.length;i++)
{
//System.out.println("==================>"+sendContents[i]);
pout.println(sendContents[i]);
}
}catch(Exception ex){this.close();return false;}
return true;
}
public boolean sendHttpData(String content)
{
try
{
//System.out.println("Begin to send Data!==================="+new java.util.Date().getTime());
if(sendData(content)&&sendData("")&&sendData(""))
{
socket.setSoTimeout(MAX_WAIT_TIME*1000);//Set the max time to wait for data receiving.
//System.out.println("Begin to receive Data!==================="+new java.util.Date().getTime());
BufferedReader bin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while((msg=bin.readLine())!=null)
{
receive+=msg+"\n\r";
//System.out.println(msg+"<=================="+"\n");
}
//System.out.println("End to receive Data!==================="+new java.util.Date().getTime());
}
return true;
}catch(Exception ex){return false;}
}
public boolean myNC(String fileName)
{
String content="";
String sendData="";
MyFile mf=new MyFile(fileName);
while(!(content=mf.readLine()).equals("<$文件末尾$>"))
{
sendData+=content+"\\n\\r";
}
return sendHttpData(sendData);
}
public boolean close()
{
if(this.socket!=null)
{
this.connected=false;
try
{
this.socket.close();
}catch(Exception ex){System.out.println("Close socket Exception!");return false;}
this.socket=null;
return true;
}
return false;
}
}
/**
* This class is used to automatic execute some commands.
* Including normal shell commands , java files and java classes.
* It can be used to do some repetitive job.
* @author Einstein
* Create date 2005-11-1
*/
package myJava;
import java.lang.Runnable;
import java.lang.reflect.*;
public class AutoExec implements Runnable
{
//Command or java file to execute.
private String command="";
//Mode COMMAND_MODE is to execute command,including executable files.
private final int COMMAND_MODE=0;
//Mode FILE_MODE is to execute java files.
private final int FILE_MODE=1;
private final int CLASS_MODE=2;
//Time between tow commands.
private long sleepSeconds=1000*1;
private long executeTimes=0;
private int execMode=COMMAND_MODE;
private ExecuteFile executer=new ExecuteFile();
/**
* The package of the class which will be executed.
*/
private String javaPackage="myJava";
/**
* The class_path of this file(AutoExec.java).
* You can change it by the set method when it needed.
*/
private String ownClassPath="E:\\myHibernate\\class\\";
AutoExec()
{}
AutoExec(String cmd)
{
this(cmd,0);
}
AutoExec(String cmd,long seconds)
{
if(cmd!=null)
{
this.command=cmd;
executer.setCmd(cmd);
}
if(seconds>0)this.sleepSeconds=seconds*1000;
}
public String getJavaPackage()
{
return javaPackage;
}
public void setJavaPackage(String javaPackage)
{
this.javaPackage = javaPackage;
}
public String getOwnClassPath()
{
return ownClassPath;
}
public void setOwnClassPath(String ownClassPath)
{
this.ownClassPath = ownClassPath;
}
public int getExecMode()
{
return execMode;
}
public void setExecMode(int md)
{
this.execMode = md;
}
public long getExecuteTimes()
{
return executeTimes;
}
public void setExecuteTimes(long executeTimes)
{
this.executeTimes = executeTimes;
}
public String getCommand()
{
return command;
}
public void setCommand(String command)
{
this.command = command;
}
public ExecuteFile getExecuter()
{
return executer;
}
public void setExecuter(ExecuteFile executer)
{
this.executer = executer;
}
public long getSleepSeconds()
{
return sleepSeconds/1000;
}
public void setSleepSeconds(long sleepSeconds)
{
this.sleepSeconds = sleepSeconds*1000;
}
public void run()
{
if(this.execMode==COMMAND_MODE)
{
executer.execute(this.command);
System.out.println(executer.getReturnString());
}
else if(execMode==FILE_MODE)
{
executeJavaFile(this.command);
}
else if(execMode==CLASS_MODE)
{//Execute class
this.executeClass(this.command);
}
else
{
System.out.println("No mode is setted!");
System.exit(0);
}
}
public boolean execute()
{
if(this.command==null)
{
System.out.println("No command to execute!!");
return false;
}
if(this.executer==null)
{
System.out.println("Executer is not valid!");
return false;
}
AutoExec ae=new AutoExec();//ae is a new object so it must be initialized before use it.
ae.setJavaPackage(this.javaPackage);
ae.setOwnClassPath(this.ownClassPath);
ae.setCommand(this.command);
ae.setExecMode(this.getExecMode());
Thread thd=new Thread(ae);
long i=0;
try
{
if(this.getExecuteTimes()>0)
{
while(i++<this.executeTimes)
{
System.out.println("[cmd/file]"+this.getCommand());
thd.start();
if(this.getSleepSeconds()>0)
{
System.out.println("Sleep for "+sleepSeconds/1000+" seconds!");
thd.sleep(this.sleepSeconds);
}
try
{
if(!thd.isAlive())
{
thd.stop();
System.out.println("Stop the thread successful!");
}
else
{
thd.join(10000);
}
}catch(Exception ex){}
thd=null;
thd=new Thread(ae);
}
}
else
{
while(true)
{
System.out.println("[cmd/file]:"+this.getCommand());
thd.start();
if(this.getSleepSeconds()>0)
{
System.out.println("Sleep for "+sleepSeconds/1000+" seconds!");
thd.sleep(this.sleepSeconds);
}
try
{
if(!thd.isAlive())
{
thd.stop();
System.out.println("Stop the thread successful!");
}
else
{
thd.join(10000);
}
}catch(Exception ex){}
thd=null;
thd=new Thread(ae);
}
}
}catch(Exception ex){System.out.println("Error when execute thread"+i);return false;}
return true;
}
/**
* Execute a java file.
* @param fileName
* @return
*/
public boolean executeJavaFile(String fileName)
{
if(fileName==null||fileName.toLowerCase().indexOf(".java")!=fileName.length()-5)
{
System.out.println("Only java files can be executed!");
return false;
}
com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
String[] args=new String[]{"-d",ownClassPath,fileName};
String className=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.length()-5);
//System.out.println("Begin to execute file: "+fileName+" whose class Name is:"+className);
try
{
int status=javac.compile(args);
if(status!=0)
{
System.out.println("Some error occurs in the java file: "+fileName);
return false;
}
return executeClass(this.javaPackage+"."+className);
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Fail to execute java file named \""+fileName+"\"!");return false;
}
}
/**
* Execute a java class file ,be sure that the class is executable.
* @param className The name of the class to be executed,including the package and class name.
* @return
*/
public boolean executeClass(String className)
{
try
{
Class cls=Class.forName(className);
if(cls!=null)
{
Method main = cls.getMethod("main", new Class[] { String[].class });
main.invoke(null,new Object[]{ new String[0]});
}
else
{
System.out.println("The main method is not found!");
return false;
}
return true;
}catch(Exception ex){ex.printStackTrace();System.out.println("Fail to execute class named \""+className+"\"!");return false;}
}
}
/**
* @author Einstein
* Email: zhuangEinstein@tom.com
* Create date: 2005-10-29
*/
package myJava;
public class Test
{
public static void main(String[] argv)
{
/**
* 自动执行测试
*/
AutoExec ae=new AutoExec();
ae.setCommand("myJava.ExecuteJava");
ae.setExecMode(2);
ae.setSleepSeconds(300);
ae.setExecuteTimes(0);
ae.execute();
/**
* 发送数据测试
PostData pd=new PostData("www.sohu.com",80);
pd.myNC("f:\\nc.txt");
System.out.println(pd.getReceive());
pd.close();
/**
* 文件操作测试
*/
/*
String content="";
MyFile mf=new MyFile("f:\\nc.txt");
int i=0;
while(!(content=mf.readLine()).equals("<$文件末尾$>"))
{
System.out.println(content);
}
System.out.println(content+mf.getFilePointer());
*/
/**
* 执行外部命令测试
ExecuteFile exec=new ExecuteFile("shutdown -a");
if(exec.execute(exec.getCmd()))
{
System.out.println("执行成功!");
}
else
{
System.out.println("执行失败,请确定该文件存在!");
}
System.out.println(exec.getReturnString());
*/
}
}
/**
* This class define some functions to be executed.
* The class to be executed by AutoExec must content a main method.
* @author Einstein
* Create date 2005-11-1
*/
package myJava;
import java.util.Date;
import java.text.SimpleDateFormat;
public class ExecuteJava implements Runnable
{
public boolean serverAlive(String host,int port,String ncFileName)
{
PostData pd=new PostData(host,port);
pd.myNC(ncFileName);
Date now=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeString=sdf.format(now);
//System.out.println(pd.getReceive());
if(pd.getReceive().indexOf("HTTP/1.1 200 OK")<0)
{
System.out.println("["+timeString+"] The server \""+host+"\" has been shutdown!");
return false;
}
else
{
System.out.println("["+timeString+"] The server \""+host+"\" is all right!");
System.out.println("I will see it latter...");
}
pd.close();
return true;
}
public void run()
{
serverAlive("www.c-gec.com",80,"f:\\nc.txt");
}
public static void main(String[] args)
{
System.out.println("=======================================================");
System.out.println("= ServerStateWatcher V1.0 =");
System.out.println("= Code by Einstein =");
System.out.println("= Email:zhuangEinstein@tom.com =");
System.out.println("=======================================================");
String host="www.cnb2b.cn";
String ncFile="f:\\nc.txt";
int port=80;
ExecuteJava ej=new ExecuteJava();
if(!ej.serverAlive(host,port,ncFile))
{
int aliveNum=0;
for(int i=0;i<10;i++)
{//do this repeating to confirm the host is over....
if(ej.serverAlive(host,port,ncFile))aliveNum++;
if(aliveNum>2)break;
}
if(aliveNum<2)
{//do some reboot job when the server is not alive.
System.out.println("The server "+host+" may be shutdown so let's reboot it now!");
ExecuteFile ef=new ExecuteFile("rebootTomcat.bat");
ef.execute();
}
}
}
}
/**
* 执行外部命令或者外部文件
* @author Einstein
* Email: zhuangEinstein@tom.com
* 创建日期 2005-10-29
*/
package myJava;
import java.io.*;
public class ExecuteFile
{
private String cmd;
private String[] argv;
private String returnString="";
ExecuteFile()
{
this.cmd=null;
this.argv=null;
}
ExecuteFile(String command)
{
this.cmd=command;
}
ExecuteFile(String command,String[] argvs)
{
this.cmd=command;
this.argv=argvs;
}
public String[] getArgv() {
return argv;
}
public void setArgv(String[] argv) {
this.argv = argv;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getReturnString()
{
return returnString;
}
public boolean execute(String cmd,String[] argv)
{
try
{
this.setCmd(cmd);
this.setArgv(argv);
Process p=Runtime.getRuntime().exec("cmd /c "+this.cmd,this.argv);
InputStreamReader isr = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader (isr);
String line = null;
this.returnString="";
while ((line = input.readLine ()) != null)
{//捕获新进程的控制台输出,并作为返回结果存在returnString中
returnString+=line+"\n";
//System.out.println(line);
}
return true;
}catch(Exception ex){return false;}
}
public boolean execute(String cmd)
{
try
{
this.setCmd(cmd);
this.execute(this.cmd,null);
return true;
}catch(Exception ex){return false;}
}
public boolean execute()
{
try
{
if(this.cmd!=null&&this.argv!=null)
{
return this.execute(this.cmd,this.argv);
}
else
{
return this.execute(this.cmd);
}
}catch(Exception ex){return false;}
}
}
/**
* @(#)PostData.java 05/10/31
*/
package myJava;
import java.net.*;
import java.io.*;
/**
* This Class is a Data-Post class.It is use to
* send string data or byte data to a specify host whith specify port.
* @author Einstein
* Email: zhuangEinstein@tom.com
* Date: 2005-10-31
*/
public class PostData
{
private final int MAX_PORT=65535;
private int MAX_WAIT_TIME=20;//maxt time to wait for the socket receive data;depend on your net state.
private String host="127.0.0.1";
private String postContent="";
private int port=80;
private Socket socket=null;
boolean connected=false;
private String receive="";
/**
* The construction functions.
*/
PostData(){}
PostData(String host,int port)
{
if(port<0||port>MAX_PORT)
{
System.out.println("The port must be between 0 and 65535!");
return;
}
if(host==null||host.trim().equals(""))
{
System.out.println("The host name can't be null!");
return;
}
this.host=host;
this.port=port;
try
{
socket=new Socket(host,port);
connected=true;
}
catch(Exception ex)
{
System.out.println("Can't connect to the server named \""+host+"\" and port "+port);
socket=null;this.host=null;this.port=0;connected=false;
}
}
/**
* Set or get some parameters of this Object whose attribute is readable and writeable.
*/
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public String getReceive() {
return receive;
}
/**
* Connect to the server after set parameters which are needed.
* Return true when success or false when fail.
* @return boolean
*/
public boolean connect()
{
return this.connect(this.host,this.port);
}
public boolean connect(String host,int port)
{
if(host!=null&&port>0)
{
this.host=host;
this.port=port;
try
{
socket=new Socket(this.host,this.port);
connected=true;
}
catch(Exception ex)
{
System.out.println("Can't connect to the server named \""+host+"\" and port "+port);
socket=null;this.host=null;this.port=0;connected=false;return false;
}
return true;
}
else
{
return false;
}
}
public boolean sendData(String content)
{
if(!this.connected||this.socket==null)
{
System.out.println("You can't send data before connect to a host!");
return false;
}
try
{
PrintWriter pout=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
String[] sendContents=content.split("\\\\n\\\\r");
for(int i=0;i<sendContents.length;i++)
{
//System.out.println("==================>"+sendContents[i]);
pout.println(sendContents[i]);
}
}catch(Exception ex){this.close();return false;}
return true;
}
public boolean sendHttpData(String content)
{
try
{
//System.out.println("Begin to send Data!==================="+new java.util.Date().getTime());
if(sendData(content)&&sendData("")&&sendData(""))
{
socket.setSoTimeout(MAX_WAIT_TIME*1000);//Set the max time to wait for data receiving.
//System.out.println("Begin to receive Data!==================="+new java.util.Date().getTime());
BufferedReader bin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while((msg=bin.readLine())!=null)
{
receive+=msg+"\n\r";
//System.out.println(msg+"<=================="+"\n");
}
//System.out.println("End to receive Data!==================="+new java.util.Date().getTime());
}
return true;
}catch(Exception ex){return false;}
}
public boolean myNC(String fileName)
{
String content="";
String sendData="";
MyFile mf=new MyFile(fileName);
while(!(content=mf.readLine()).equals("<$文件末尾$>"))
{
sendData+=content+"\\n\\r";
}
return sendHttpData(sendData);
}
public boolean close()
{
if(this.socket!=null)
{
this.connected=false;
try
{
this.socket.close();
}catch(Exception ex){System.out.println("Close socket Exception!");return false;}
this.socket=null;
return true;
}
return false;
}
}
/**
* This class is used to automatic execute some commands.
* Including normal shell commands , java files and java classes.
* It can be used to do some repetitive job.
* @author Einstein
* Create date 2005-11-1
*/
package myJava;
import java.lang.Runnable;
import java.lang.reflect.*;
public class AutoExec implements Runnable
{
//Command or java file to execute.
private String command="";
//Mode COMMAND_MODE is to execute command,including executable files.
private final int COMMAND_MODE=0;
//Mode FILE_MODE is to execute java files.
private final int FILE_MODE=1;
private final int CLASS_MODE=2;
//Time between tow commands.
private long sleepSeconds=1000*1;
private long executeTimes=0;
private int execMode=COMMAND_MODE;
private ExecuteFile executer=new ExecuteFile();
/**
* The package of the class which will be executed.
*/
private String javaPackage="myJava";
/**
* The class_path of this file(AutoExec.java).
* You can change it by the set method when it needed.
*/
private String ownClassPath="E:\\myHibernate\\class\\";
AutoExec()
{}
AutoExec(String cmd)
{
this(cmd,0);
}
AutoExec(String cmd,long seconds)
{
if(cmd!=null)
{
this.command=cmd;
executer.setCmd(cmd);
}
if(seconds>0)this.sleepSeconds=seconds*1000;
}
public String getJavaPackage()
{
return javaPackage;
}
public void setJavaPackage(String javaPackage)
{
this.javaPackage = javaPackage;
}
public String getOwnClassPath()
{
return ownClassPath;
}
public void setOwnClassPath(String ownClassPath)
{
this.ownClassPath = ownClassPath;
}
public int getExecMode()
{
return execMode;
}
public void setExecMode(int md)
{
this.execMode = md;
}
public long getExecuteTimes()
{
return executeTimes;
}
public void setExecuteTimes(long executeTimes)
{
this.executeTimes = executeTimes;
}
public String getCommand()
{
return command;
}
public void setCommand(String command)
{
this.command = command;
}
public ExecuteFile getExecuter()
{
return executer;
}
public void setExecuter(ExecuteFile executer)
{
this.executer = executer;
}
public long getSleepSeconds()
{
return sleepSeconds/1000;
}
public void setSleepSeconds(long sleepSeconds)
{
this.sleepSeconds = sleepSeconds*1000;
}
public void run()
{
if(this.execMode==COMMAND_MODE)
{
executer.execute(this.command);
System.out.println(executer.getReturnString());
}
else if(execMode==FILE_MODE)
{
executeJavaFile(this.command);
}
else if(execMode==CLASS_MODE)
{//Execute class
this.executeClass(this.command);
}
else
{
System.out.println("No mode is setted!");
System.exit(0);
}
}
public boolean execute()
{
if(this.command==null)
{
System.out.println("No command to execute!!");
return false;
}
if(this.executer==null)
{
System.out.println("Executer is not valid!");
return false;
}
AutoExec ae=new AutoExec();//ae is a new object so it must be initialized before use it.
ae.setJavaPackage(this.javaPackage);
ae.setOwnClassPath(this.ownClassPath);
ae.setCommand(this.command);
ae.setExecMode(this.getExecMode());
Thread thd=new Thread(ae);
long i=0;
try
{
if(this.getExecuteTimes()>0)
{
while(i++<this.executeTimes)
{
System.out.println("[cmd/file]"+this.getCommand());
thd.start();
if(this.getSleepSeconds()>0)
{
System.out.println("Sleep for "+sleepSeconds/1000+" seconds!");
thd.sleep(this.sleepSeconds);
}
try
{
if(!thd.isAlive())
{
thd.stop();
System.out.println("Stop the thread successful!");
}
else
{
thd.join(10000);
}
}catch(Exception ex){}
thd=null;
thd=new Thread(ae);
}
}
else
{
while(true)
{
System.out.println("[cmd/file]:"+this.getCommand());
thd.start();
if(this.getSleepSeconds()>0)
{
System.out.println("Sleep for "+sleepSeconds/1000+" seconds!");
thd.sleep(this.sleepSeconds);
}
try
{
if(!thd.isAlive())
{
thd.stop();
System.out.println("Stop the thread successful!");
}
else
{
thd.join(10000);
}
}catch(Exception ex){}
thd=null;
thd=new Thread(ae);
}
}
}catch(Exception ex){System.out.println("Error when execute thread"+i);return false;}
return true;
}
/**
* Execute a java file.
* @param fileName
* @return
*/
public boolean executeJavaFile(String fileName)
{
if(fileName==null||fileName.toLowerCase().indexOf(".java")!=fileName.length()-5)
{
System.out.println("Only java files can be executed!");
return false;
}
com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
String[] args=new String[]{"-d",ownClassPath,fileName};
String className=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.length()-5);
//System.out.println("Begin to execute file: "+fileName+" whose class Name is:"+className);
try
{
int status=javac.compile(args);
if(status!=0)
{
System.out.println("Some error occurs in the java file: "+fileName);
return false;
}
return executeClass(this.javaPackage+"."+className);
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Fail to execute java file named \""+fileName+"\"!");return false;
}
}
/**
* Execute a java class file ,be sure that the class is executable.
* @param className The name of the class to be executed,including the package and class name.
* @return
*/
public boolean executeClass(String className)
{
try
{
Class cls=Class.forName(className);
if(cls!=null)
{
Method main = cls.getMethod("main", new Class[] { String[].class });
main.invoke(null,new Object[]{ new String[0]});
}
else
{
System.out.println("The main method is not found!");
return false;
}
return true;
}catch(Exception ex){ex.printStackTrace();System.out.println("Fail to execute class named \""+className+"\"!");return false;}
}
}
/**
* @author Einstein
* Email: zhuangEinstein@tom.com
* Create date: 2005-10-29
*/
package myJava;
public class Test
{
public static void main(String[] argv)
{
/**
* 自动执行测试
*/
AutoExec ae=new AutoExec();
ae.setCommand("myJava.ExecuteJava");
ae.setExecMode(2);
ae.setSleepSeconds(300);
ae.setExecuteTimes(0);
ae.execute();
/**
* 发送数据测试
PostData pd=new PostData("www.sohu.com",80);
pd.myNC("f:\\nc.txt");
System.out.println(pd.getReceive());
pd.close();
/**
* 文件操作测试
*/
/*
String content="";
MyFile mf=new MyFile("f:\\nc.txt");
int i=0;
while(!(content=mf.readLine()).equals("<$文件末尾$>"))
{
System.out.println(content);
}
System.out.println(content+mf.getFilePointer());
*/
/**
* 执行外部命令测试
ExecuteFile exec=new ExecuteFile("shutdown -a");
if(exec.execute(exec.getCmd()))
{
System.out.println("执行成功!");
}
else
{
System.out.println("执行失败,请确定该文件存在!");
}
System.out.println(exec.getReturnString());
*/
}
}
上一篇: 前端大牛得到的最佳职业生涯建议 javascript
下一篇: 终于看了X战警3