派生自 projectDept/qhighschool

Administrator
2022-11-18 b6a92bcd70d2edfb8bf2a2e784b37e1fcd036c10
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package com.qxueyou.scc.base.util;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
 
import org.apache.commons.lang3.StringUtils;
 
/**
 * Ç°Èý¸öÊôÐÔ¸ù¾Ýʵ¼Ê´æ´¢Î»ÖÃÉèÖÃ
 * @author ody.yuan
 *
 */
public class MyJsCssVersionUtils {
    
     /** web¹¤³ÌµÄ·¢²¼Â·¾¶  */
    private static String webContent = "qxueyou";
    
    /** web¹¤³ÌÖÐwebÎļþ¼ÐµÄ¾ø¶Ô·¾¶ D:\project\workspace_web\versioncontroller0\web\js\qxueyou.js  */
    /** web¹¤³ÌÖÐwebÎļþ¼ÐµÄ¾ø¶Ô·¾¶ D:\project\workspaceStkkk\qxueyou_web\web\js\qxueyou.js  */
    private static String webFileAbsolutePath = "C:" + File.separator + "workspace" + File.separator + "qxueyou_web";
    
    /** É¨Ãèjs¡¢css¡¢htmlÎļþµÄÎļþ¼Ð¾ø¶Ô·¾¶£¬¹Ì¶¨ÉèÖÃΪwebĿ¼  */
    private static String fileScanDirec = "C:" + File.separator + "workspace" + File.separator + "qxueyou_web";
    
    /** Æ¥ÅähtmlÖÐÒýÈëjsÎļþ  */
    private static Pattern scriptImportPattrrn = Pattern.compile("<script(.*)src(.*)</script>");
    
    /** Æ¥ÅähtmlÖÐÒýÈëcssÎļþ  */
    private static Pattern cssImportPattrrn = Pattern.compile("<link(.*)href(.*)rel(.*)>");
    
    private static char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    
    
    /**
     * µÃµ½´¦Àí¹ýµÄÎļþ·¾¶Îªkey£¬Îļþmd5ֵΪvalueµÄmap
     * @param filePath Îļþ·¾¶
     * @param fileExtension ÎļþÀàÐÍ
     * @param map map
     */
    private static void getFileMD5Map(String filePath,String fileExtension,Map<String,String> map,String version){
        readFile(filePath,fileExtension,map,version);
    }
    
    /**
     * µÃµ½Â·¾¶ÏµÄËùÐèÎļþºÍÎļþµÄmd5Öµ
     * @param filePath
     * @param fileExtension
     * @param map
     */
    private static void readFile(String filePath,String fileExtension,Map<String,String> map,String version){
        
        File file = new File(filePath);
        if(file.isFile()){
            String fiePath = file.getAbsolutePath();
            //·ûºÏÖ¸¶¨ÀàÐÍ
            if(fiePath.endsWith(fileExtension)){
                generateMap(file,fileExtension,map,version);
            }
        }else if(file.isDirectory()){
            String[] fileList = file.list();
            for(String name : fileList){
                readFile(filePath + File.separator + name,fileExtension,map,version);
            }
        }
    }
    
    /**
     * µÃµ½Ò»¸öÎļþµÄmap
     * @param file
     * @param map
     */
    private static void generateMap(File file, String fileExtension, Map<String,String> map,String version){
        //TODO  Ëõ¶Ìmd5Öµ
        String strKey = file.getAbsolutePath();
        strKey = strKey.replace(webFileAbsolutePath, File.separator + webContent);
        strKey = strKey.replace("\\", "/");
        String strValue = getMD5(file);
        if(StringUtils.isNotBlank(strValue)){
            strValue = version;
        }
        map.put(strKey, strValue);
        
    }
    
    /**
     * ¶ÔÎļþÈ«ÎÄÉú³ÉMD5ÕªÒª
     * 
     * @param file
     *            Òª¼ÓÃܵÄÎļþ
     * @return MD5ÕªÒªÂë
     */
    public static String getMD5(File file) {
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            byte[] buffer = new byte[2048];
            int length = -1;
            //ÔÝʱ²»ÓÃ
            //long s = System.currentTimeMillis();
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
            byte[] b = md.digest();
            return byteToHexString(b);
            // 16λ¼ÓÃÜ
            // return buf.toString().substring(8, 24);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 
    /**
     * °Ñbyte[]Êý×éת»»³ÉÊ®Áù½øÖÆ×Ö·û´®±íʾÐÎʽ
     * @param tmp    Òª×ª»»µÄbyte[]
     * @return Ê®Áù½øÖÆ×Ö·û´®±íʾÐÎʽ
     */
    private static String byteToHexString(byte[] tmp) {
        
        String s;
        // ÓÃ×Ö½Ú±íʾ¾ÍÊÇ 16 ¸ö×Ö½Ú
        char str[] = new char[16 * 2]; // Ã¿¸ö×Ö½ÚÓà16 ½øÖƱíʾµÄ»°£¬Ê¹ÓÃÁ½¸ö×Ö·û£¬
        // ËùÒÔ±íʾ³É 16 ½øÖÆÐèÒª 32 ¸ö×Ö·û
        int k = 0; // ±íʾת»»½á¹ûÖжÔÓ¦µÄ×Ö·ûλÖÃ
        for (int i = 0; i < 16; i++) { // ´ÓµÚÒ»¸ö×Ö½Ú¿ªÊ¼£¬¶Ô MD5 µÄÿһ¸ö×Ö½Ú
            // ×ª»»³É 16 ½øÖÆ×Ö·ûµÄת»»
            byte byte0 = tmp[i]; // È¡µÚ i ¸ö×Ö½Ú
            str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // È¡×Ö½ÚÖиߠ4 Î»µÄÊý×Öת»», 
            // >>> ÎªÂß¼­ÓÒÒÆ£¬½«·ûºÅλһÆðÓÒÒÆ
            str[k++] = hexDigits[byte0 & 0xf]; // È¡×Ö½ÚÖе͠4 Î»µÄÊý×Öת»»
        }
        s = new String(str); // »»ºóµÄ½á¹ûת»»Îª×Ö·û´®
        return s;
    }
    
    /**
     * 
     * @param filePath
     * @param fileExtension
     * @param map
     */
    private static void getHtml(String filePath,String fileExtension,Map<String,String> map){
        readHtmlFile(fileScanDirec,".ftl",map);
    }
    
    /**
     * µÃµ½Â·¾¶ÏµÄËùÐèÎļþºÍÎļþµÄmd5Öµ
     * @param filePath
     * @param fileExtension
     * @param map
     */
    private static void readHtmlFile(String filePath,String fileExtension,Map<String,String> map){
        
        File file = new File(filePath);
        if(file.isFile()){
            String fiePath = file.getAbsolutePath();
            //·ûºÏÖ¸¶¨ÀàÐÍ
            if(fiePath.endsWith(fileExtension)){
                addVersion(file,map);
            }
        }else if(file.isDirectory()){
            String[] fileList = file.list();
            for(String name : fileList){
                readHtmlFile(filePath + File.separator + name,fileExtension,map);
            }
        }
    }
    
    /**
     * µÃµ½Ò»¸öÎļþµÄmap
     * @param file
     * @param map
     */
    private static void addVersion(File file,Map<String,String> map){
        //TODO  Ëõ¶Ìmd5Öµ
        InputStream is = null;
        OutputStream os = null;
        List<String> contentList = new ArrayList<String>();
        
        // ¶ÁÎļþ
        try {
            //Ö¸¶¨utf-8¸ñʽ
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
            String line = null;
            
            while ((line = br.readLine()) != null) {
                //TODO version ´«nullÖµ
                String modLine = getModLine(line, null,map);
                if (modLine != null) {
                    //System.out.println(modLine);
                    line = modLine;
                }
                line = line + "\r\n";
                contentList.add(line);
            }
            // ¹Ø±ÕÁ÷
            br.close();
        } catch (Exception e) {
            System.out.println("¶ÁÎļþʧ°Ü£º" + file.getAbsolutePath());
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
 
        }
        // Ð´Îļþ
        try {
            //Ö¸¶¨utf8¸ñʽ
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
            
            for (Iterator<String> it = contentList.iterator(); it.hasNext();) {
                String line = it.next();
                bw.write(line);
            } 
            // ¸üе½Îļþ
            bw.flush();
            // ¹Ø±ÕÁ÷
            bw.close();
        } catch (Exception e) {
            System.out.println("дÎļþʧ°Ü£º" + file.getAbsolutePath());
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 
     * ²éÕÒÎļþÐèÒªµÄ°æ±¾ºÅµÄjs Óëcss ÐÐ
     * @param line ÐÐ×Ö·û
     * @param version Ä¬Èϰ汾
     * @param map md5 map
     * @return 
     */
    private static String getModLine(String line, String version, Map<String, String> map) {
        
        //Æ¥ÅähtmlÒýÈëjsÎļþ       eg:<script type="text/javascript" src="/qxueyou/web/js/qxueyou.js"></script>
        if (scriptImportPattrrn.matcher(line).find()) {
            //ÒÔÒýºÅ·Ö¸ô£¬ÒÔ/¿ªÊ¼
            String md5Version = null;
            String strLine[] = line.split("\"");
            for(String str:strLine){
                if(null != md5Version){
                    break;
                }
                if(str.startsWith("/")){
                    //Èç¹ûÒÑÓа汾ºÅ£¬°´?·Ö¸ô£¬È¡µÚÒ»¸ö
                    if(str.lastIndexOf("?version") != -1){
                        str = str.substring(0, str.lastIndexOf("?version"));
                    }
                    md5Version = map.get(str);
                }
            }
            
            int pos = line.lastIndexOf(".js");
            if(null != md5Version){
                String modLine = line.substring(0, pos) + ".js?version=" + md5Version+ "\"></script>";
                return modLine;
            }
        
        //Æ¥ÅähtmlÒýÈëcssÎļþ      eg£º<link href="/qxueyou/web/css/bootstrap.min.css" rel="stylesheet">
        } else if (cssImportPattrrn.matcher(line).find()) {
            
            //ÒÔÒýºÅ·Ö¸ô£¬ÒÔ/¿ªÊ¼
            String md5Version = null;
            String strLine[] = line.split("\"");
            for(String str:strLine){
                if(null != md5Version){
                    break;
                }
                if(str.startsWith("/")){
                    //Èç¹ûÒÑÓа汾ºÅ£¬°´?·Ö¸ô£¬È¡µÚÒ»¸ö
                    if(str.lastIndexOf("?version") != -1){
                        str = str.substring(0, str.lastIndexOf("?version"));
                    }
                    md5Version = map.get(str);
                }
            }
            
            int pos = line.lastIndexOf(".css");
            if(null != md5Version){
                String modLine = line.substring(0, pos) + ".css?version=" + md5Version+ "\" rel=\"stylesheet\">";
                return modLine;
            }
            
        }
        
        return line;
    }
 
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
        String version = df.format(date);
        
        Map<String,String> objMap = new HashMap<String,String>();
        //Ìí¼ÓjsÎļþ
        getFileMD5Map(fileScanDirec,".js",objMap,version);
        //Ìí¼ÓCSSÎļþ
        getFileMD5Map(fileScanDirec,".css",objMap,version);
        
        //Ñ­»·htmlÎļþ£¬ÐÞ¸ÄÆäÖеÄcssºÍjsÒýÈë·¾¶
        getHtml(fileScanDirec,".ftl",objMap);
        
        System.out.println("successful");
        
    }
 
}