1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package com.main;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
 
 
public class HzipServer extends Thread {
    public static final String MYSQLBACKUPDIR = "MYSQLBACKUPDIR";            //mysqlÊý¾Ý¿â±¸·ÝÎļþ¼ÐÃû³Æ
    public static final int MAXSTORAGE = 3;
    public static boolean ISNEEDDELETE = false;
    public Socket socket;
    
    public HzipServer() {
        
    }
    
    public HzipServer(Socket socket) {
        this.socket = socket;
    }
    
    public DeleteRegularThread createDeleteRegularThreadStructure() {
        return new DeleteRegularThread();
    }
    
    @Override
    public void run() {
        try {
            InputStream ins = socket.getInputStream();
            ZipInputStream zis=new ZipInputStream(ins);
            
            String rootDir=null;
            //ÔÚ´Ë´ÎÁ¬½ÓÖÐ,ÊÇ·ñÊǵÚÒ»´Î¶Áµ½ZipEntry.¶Áµ½µÄµÚÒ»¸öEntry,¾ÍÊÇÕýÔÚ±»´«ÊäµÄÎļþ¼Ð¡£
            boolean isFirst=true;
            String savePath="D:"+File.separator+MYSQLBACKUPDIR+File.separator;
            //ÒÔÉÏΪ±£´æ½ÓÊÕµ½µÄÎļþ¼ÐµÄλÖá£
            //Èç,·þÎñ¶Ë´«ÊäµÄÎļþ¼ÐÊÇD:\zipfolder,Ôò¸ÃÎļþ¼ÐÔÚ¿Í»§¶Ë½«±£´æÔÚD:\MYSQLBACKUPDIR\¡£
            //ΪÁËÁ¼ºÃµÄÒÆÖ²ÐÔ,ÕâÀïÓÃFile.separator£¬
            //ÒòΪ·Ö¸ô·ûÔÚ²»Í¬µÄ²Ù×÷ϵͳÉÏ,¿ÉÄܲ»Ò»Ñù¡£
            
            ZipEntry ze=null;
            ZipOutputStream zos=null;
            FileOutputStream fos=null;
            OutputStream os=null;
            byte[] b=new byte[1024];
            int length=-1;            
            while( (ze=zis.getNextEntry())!=null  )
            {
                String name=ze.getName();
                File file=null;
                if(ze.isDirectory())
                {
                    if(isFirst)
                    {
                        isFirst=false;
                        
                        //ÕâÀï¿ÉÄÜÒÆÖ²ÐÔ²»ºÃ,ÎÒ»¹Ã»Ñо¿Í¸,ÔÝÓô˷¨¡£
                        String[] temp=name.split("\\\\");
                        
                        //Îļþ¼ÐµÄÃû×Ö.²Î¿´·þÎñ¶Ë´úÂë¿ÉÖª,Õâ¸öÃû×ÖÊÇ"/"½áβµÄ¡£
                        String selfName=temp[temp.length-1];
                        
                        //È¥µô"/",ÕâÀï²ÅÊÇÕæÕýµÄÎļþ¼ÐµÄÃû×Ö¡£
                        //ºóÃæ½ÓÊÕµ½µÄÎļþ½«ÒªÒÔrootDirΪ²ÎÕÕÎï,È·¶¨±£´æÎ»Öá£
                        rootDir=selfName.substring(0, selfName.length()-1);
                        
                        //µ½ÁËÕâÀï,Õâ¸öÎļþ¼ÐµÄ·¾¶Æäʵ¾ÍÊÇD:\gitspace\zipfolderÁË¡£
                        file=new File(savePath+selfName);
                    }
                    
                    int index=name.indexOf(rootDir);
                    
                    //È磬¸ÃÎļþÔÚ·þÎñ¶ËµÄλÖÃÊÇD:\zipfolder\a.txt,ÔòtempDir=zipfolder\a.txt
                    String tempDir=name.substring(index,name.length());
                    
                    //Á½Õ߯´ºÏ£¬¸ÃÎļþÔÚ¿Í»§¶ËµÄ±£´æÂ·¾¶Ò²¾ÍÊÇD:\gitspace\zipfolder\a.txtÁË¡£
                    //Ïà¶ÔÓÚziplolder£¬¸ÃÎļþµÄλÖÃδ·¢Éú±ä»¯¡£
                    file=new File(savePath+tempDir);
                    
                    if(!file.exists())
                    {
                        file.mkdirs();
                    }
                }
                else
                {
                    int index=name.indexOf(rootDir);
                    String tempFileDir=name.substring(index,name.length());
                    file=new File(savePath+tempFileDir);
                    fos=new FileOutputStream(file);
                    while( (length=zis.read(b))> -1 )
                    {
                        fos.write(b, 0, length);
                        fos.flush();
                    }
                    //Õâ¾ä±ØÐëÓÐ,²»È»Îļþ¶àÁË,´ò¿ªµÄÎļþ¹ý¶à,½«»á·¢ÉúÒì³£
                    fos.close();
                }
            }
            socket.close();
            ISNEEDDELETE = true;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    
    
    /**
     *     ¶¨ÆÚɾ³ý¶àÓàµÄ±¸·ÝÊý¾Ý
     * @author LiJun
     *
     */
    class DeleteRegularThread extends Thread{
        
        @Override
        public void run() {
            while(true) {
                try {
                    String savePath="D:"+File.separator+MYSQLBACKUPDIR+File.separator;
                    File fileroot = new File(savePath);
                    File[] files = fileroot.listFiles();
                    if(ISNEEDDELETE && files.length >3) {
                        deleteFileRoot(savePath, MAXSTORAGE);        //ɾ³ý³¬¹ý3´ÎµÄ±¸·ÝÊý¾Ý
                        ISNEEDDELETE = false;
                    }            
                    sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        /**
         *     µÝ¹éɾ³ýĿ¼ÏµÄËùÓÐÎļþ¼°×ÓĿ¼ÏÂËùÓÐÎļþ
         * @param dir ½«ÒªÉ¾³ýµÄÎļþĿ¼
         * @return boolean Returns "true" if all deletions were successful.
         *                 If a deletion fails, the method stops attempting to
         *                 delete and returns "false".
         */
        public boolean deleteDir(File dir) {
            if (dir.isDirectory()) {
                String[] children = dir.list();
                //µÝ¹éɾ³ýĿ¼ÖеÄ×ÓĿ¼ÏÂ
                for (int i=0; i<children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
            // Ä¿Â¼´ËʱΪ¿Õ£¬¿ÉÒÔɾ³ý
            return dir.delete();
        }
        
        /**
         * ±£Áôµ±Ç°Ä¿Â¼ÖеÄÖ¸¶¨ÊýÄ¿µÄÎļþ¼Ð            (ɾ³ýµ±Ç°Îļþ¼ÐϵÄ×îÔç֮ǰµÄ±¸·ÝÊý¾Ý)
         * @param filePath                ÐèÒª±¸·ÝÊý¾ÝµÄÎļþ¼Ð
         * @param filecount                 ±¸·ÝÊý¾ÝµÄ±ÊÊý
         */
        public void deleteFileRoot(String filePath,int filecount) {
            File file = new File(filePath);
            if(file.exists()) {
                File[] files = file.listFiles();
                Arrays.sort(files, new CompratorByLastModified());
                if(files.length>=filecount && filecount>0) {
                    //System.out.println("Îļþ¼Ð¸öÊý£º"+files.length + "\t ×î´ó±ÊÊý£º"+filecount);
                    for(int i=(filecount-1);i<files.length;i++) {
                        deleteDir(files[i]);
                    }
                }
            }
        }
    }
    
    //±È½ÏÁ½¸öÎļþ¼ÐϵÄÎļþ
    static class CompratorByLastModified implements Comparator<File> {
        public int compare(File f1, File f2) {
            long diff = f1.lastModified() - f2.lastModified();
            if (diff > 0) {
                return -1;//µ¹ÐòÕýÐò¿ØÖÆ
            }else if (diff == 0) {
                return 0;
            }else {
                return 1;//µ¹ÐòÕýÐò¿ØÖÆ
            }
        }
    }
    
    public static void main(String[] args) {
        try {
            ServerSocket serveracept = new ServerSocket(10100);
            HzipServer server = null;
            
            server = new HzipServer();
            DeleteRegularThread deletethread = server.createDeleteRegularThreadStructure();
            deletethread.start();        //Æô¶¯É¾³ý¶àÓ౸·ÝÊý¾Ý¿âÏß³Ì
            
            while(true) {
                Socket s = serveracept.accept();
                //System.out.println("¼àÌýµ½¿Í»§¶ËÁ¬½Ó");
                server = new HzipServer(s);
                server.start();
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}