免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1275 | 回复: 0
打印 上一主题 下一主题

模拟maven的管理jar包。使用文件签名。非版本号 [复制链接]

论坛徽章:
1
数据库技术版块每日发帖之星
日期:2015-07-11 22:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-14 09:39 |只看该作者 |倒序浏览
在家整理以前的项目时,并想备份到网盘,发现项目很多都不是使用maven的老项目,感觉jar非常多,而且重复也比较多,所以就想把那些重复的jar去掉,并可以还原。

使用缓存 java  Jars  cache  是否清理jar 地址
还原      java Jars  restore  地址

原理是会在有.project文件的目录生成一个.jars文件用来记录 相对地址下的jar,及其md5值

最后发现:其实并没有什么用,权当呵呵了。

主代码
  1. package org.zlb.kits;

  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.FileReader;
  8. import java.io.IOException;
  9. import java.io.PrintWriter;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.List;

  13. import org.zlb.kits.digest.DigestKit;
  14. import org.zlb.kits.io.FileKit;
  15. import org.zlb.kits.io.IOKit;

  16. /**
  17. * 模拟Maven管理jar包,程序。
  18. *
  19. * @author zenglb
  20. */
  21. public class Jars {
  22.     /**
  23.      * 池的根目录
  24.      */
  25.     private final File jarsCache;
  26.     private final String jarsCachePath;
  27.     /**
  28.      * 默认提供的配置文件。
  29.      */
  30.     private static final String DEFAULT_JARS_FILE_NAME = "/.jars";

  31.     /**
  32.      * 需要传入jar池的地址。
  33.      *
  34.      * @param jarsCache
  35.      */
  36.     public Jars(String jarsCache) {
  37.         this.jarsCache = new File(jarsCache);
  38.         if (!this.jarsCache.exists()) {
  39.             this.jarsCache.mkdir();
  40.         }
  41.         if (this.jarsCache.isFile()) {
  42.             throw new IllegalArgumentException("jarsCache must exists be a Directory!");
  43.         }
  44.         jarsCachePath = this.jarsCache.getAbsolutePath();
  45.     }

  46.     public Jars() {
  47.         this("D:/0_base" + DEFAULT_JARS_FILE_NAME);
  48.     }

  49.     public void analysis(String pathName, boolean isCache, boolean isClear) {
  50.         File path = new File(pathName);
  51.         if (!path.exists() || path.isFile()) {
  52.             throw new IllegalArgumentException("pathName must exists and isDirectory!");
  53.         }
  54.         fileEach(path, isCache, isClear);
  55.     }

  56.     private void fileEach(File path, boolean isCache, boolean isClear) {
  57.         if (null != path) {
  58.             Logs.debug("analysis isCache = [%s] isClear =[%s]  %s ", isCache, isClear, path.getAbsolutePath());
  59.             if (path.exists()) {
  60.                 if (path.isFile()) {
  61.                     return;
  62.                 }
  63.                 boolean project = isProject(path);
  64.                 if (project) {
  65.                     if (isCache) {
  66.                         cacheProject(path, isClear);
  67.                     } else {
  68.                         restoreProject(path);
  69.                     }
  70.                 } else {
  71.                     File[] files = path.listFiles();
  72.                     if (null != files) {
  73.                         for (File file : files) {
  74.                             fileEach(file, isCache, isClear);
  75.                         }
  76.                     }
  77.                 }
  78.             }
  79.         }
  80.     }

  81.     /**
  82.      * 还原一个java工程
  83.      *
  84.      * @param path
  85.      */
  86.     private void restoreProject(File path) {
  87.         if (isProject(path)) {
  88.             String base = path.getAbsolutePath();
  89.             Logs.debug("restore project: %s", base);
  90.             Logs.debug("=======================================");
  91.             File jars = new File(base + DEFAULT_JARS_FILE_NAME);
  92.             if (jars.exists() && jars.isFile()) {
  93.                 BufferedReader in = null;
  94.                 try {
  95.                     in = new BufferedReader(new FileReader(jars));
  96.                     String line = null;
  97.                     String[] tt = null;
  98.                     File jar = null;
  99.                     while (null != (line = in.readLine())) {
  100.                         tt = line.split("####");
  101.                         if (tt.length == 2) {
  102.                             jar = new File(base + tt[0].trim());
  103.                             Logs.debug("try restore %s >> %s", jar.getName(), tt[1].trim());
  104.                             restoreJar(jar, tt[1].trim());
  105.                         }
  106.                     }
  107.                 } catch (IOException e) {
  108.                     e.printStackTrace();
  109.                 } finally {
  110.                     IOKit.closeIo(in);
  111.                 }

  112.             }
  113.         }
  114.     }

  115.     /**
  116.      * 缓存一个工程
  117.      *
  118.      * @param path
  119.      * @param isClear
  120.      */
  121.     private void cacheProject(File path, boolean isClear) {
  122.         if (isProject(path)) {
  123.             Logs.debug("cache project: %s", path.getAbsolutePath());
  124.             Logs.debug("-----------------------------------------");
  125.             List<File> jarFileLst = new ArrayList<File>();
  126.             findJars(path, jarFileLst);

  127.             String md5 = null;
  128.             String relativePath = null;
  129.             ArrayList<String> jarsContent = new ArrayList<String>();
  130.             int basePath = path.getAbsolutePath().length();
  131.             for (File jar : jarFileLst) {
  132.                 md5 = getFileMD5(jar);
  133.                 Logs.debug("try cache %s >> %s", jar.getName(), md5);
  134.                 relativePath = jar.getAbsolutePath().trim().substring(basePath);
  135.                 jarsContent.add(relativePath + "####" + md5);
  136.                 cacheJar(jar, md5);
  137.             }

  138.             if (!jarsContent.isEmpty()) {
  139.                 File f = new File(path.getAbsolutePath() + DEFAULT_JARS_FILE_NAME);
  140.                 if (f.exists()) {
  141.                     Logs.debug("rename " + DEFAULT_JARS_FILE_NAME);

  142.                     copyFile(f, new File(
  143.                             f.getAbsoluteFile() + ".bak." + DateKit.printDateTime(new Date(), "yyyyMMddHHmmss")));
  144.                 }
  145.                 PrintWriter out = null;
  146.                 try {
  147.                     out = new PrintWriter(f);
  148.                     for (String ss : jarsContent) {
  149.                         out.println(ss);
  150.                     }
  151.                 } catch (FileNotFoundException e) {
  152.                 } finally {
  153.                     try {
  154.                         out.flush();
  155.                     } catch (Exception e) {
  156.                     }
  157.                     IOKit.closeIo(out);
  158.                 }
  159.                 if (isClear) {
  160.                     Logs.debug("delete jars! : %s", jarFileLst.size());
  161.                     for (File file : jarFileLst) {
  162.                         file.delete();
  163.                     }
  164.                 }
  165.             }
  166.             Logs.debug("=======================================");
  167.             Logs.debug("\n");
  168.         }
  169.     }

  170.     /**
  171.      * 查找工程中的所有jar包
  172.      *
  173.      * @param path
  174.      * @param jarFileLst
  175.      */
  176.     private void findJars(File path, List<File> jarFileLst) {
  177.         if (null != jarFileLst && null != path && path.exists()) {
  178.             if (path.isFile() && path.getName().trim().toLowerCase().endsWith(".jar")) {
  179.                 jarFileLst.add(path);
  180.             } else if (path.isDirectory()) {
  181.                 File[] files = path.listFiles();
  182.                 if (null != files) {
  183.                     for (File file : files) {
  184.                         findJars(file, jarFileLst);
  185.                     }
  186.                 }
  187.             }
  188.         }
  189.     }

  190.     /**
  191.      * 缓存jar
  192.      *
  193.      * @param jar
  194.      * @param md5
  195.      * @return
  196.      */
  197.     private boolean cacheJar(File jar, String md5) {
  198.         if (null != jar && jar.isFile() && null != md5) {
  199.             File saveFile = new File(jarsCachePath + getCachePath(jar.getName(), md5));
  200.             FileKit.makeDir(saveFile.getParentFile());
  201.             if (saveFile.exists() && md5.equals(getFileMD5(saveFile))) {// 已经存在
  202.                 Logs.debug("cache %s exists", jar.getName());
  203.                 return true;
  204.             }
  205.             copyFile(jar, saveFile);
  206.             Logs.debug("cache  %s success", jar.getName());
  207.             return true;
  208.         }
  209.         Logs.debug("cache  %s[%s] falid", null != jar ? jar.getName() : "ERR", md5);
  210.         return false;
  211.     }

  212.     /**
  213.      * 还原一个jar到指定地址
  214.      *
  215.      * @param jar
  216.      * @param md5
  217.      * @return
  218.      */
  219.     private boolean restoreJar(File jar, String md5) {
  220.         String name = jar.getName();
  221.         if (jar.exists() && md5.equals(getFileMD5(jar))) {
  222.             Logs.debug("restore %s exists", name);
  223.             return true;
  224.         }
  225.         File dbFile = new File(jarsCachePath + getCachePath(name, md5));
  226.         if (dbFile.exists() && md5.equals(getFileMD5(dbFile))) {
  227.             FileKit.makeDir(jar.getParentFile());
  228.             copyFile(dbFile, jar);
  229.             Logs.debug("restore  %s success", name);
  230.             return true;
  231.         }
  232.         Logs.debug("restore  %s[%s] falid", name, md5);
  233.         return false;
  234.     }

  235.     /**
  236.      * 通过名字的hash值计算包所在地址。
  237.      *
  238.      * @param name
  239.      * @param md5
  240.      * @return
  241.      */
  242.     protected String getCachePath(String name, String md5) {
  243.         int hash = name.hashCode();
  244.         hash = (hash > 0 ? hash : 0 - hash) % 1000;
  245.         return String.format("/%3$02x/%4$03x/%1$s_%2$s", name, md5, hash / 100, hash % 100);
  246.     }

  247.     /**
  248.      * 是否为一个项目,包含.classpath和.project文件就是项目。
  249.      *
  250.      * @param path
  251.      * @return
  252.      */
  253.     public boolean isProject(File path) {
  254.         int i = 1;
  255.         if (null != path && path.exists() && path.isDirectory()) {
  256.             File[] lst = path.listFiles();
  257.             String fileName = null;
  258.             if (null != lst) {
  259.                 for (File file : lst) {
  260.                     if (file.isFile()) {
  261.                         fileName = file.getName();
  262.                         if (".project".equalsIgnoreCase(fileName.trim())) {
  263.                             i--;
  264.                         }
  265.                     }
  266.                 }
  267.             }
  268.         }
  269.         return i <= 0;
  270.     }

  271.     /**
  272.      * 计算文件的MD5值
  273.      *
  274.      * @param file
  275.      * @return
  276.      */
  277.     private static String getFileMD5(File file) {
  278.         if (null == file || !file.isFile()) {
  279.             return null;
  280.         }
  281.         FileInputStream in = null;
  282.         try {
  283.             in = new FileInputStream(file);
  284.             byte[] data = IOKit.readToByteBuffer(in, Integer.MAX_VALUE);
  285.             return DigestKit.md5Digest(data).toLowerCase();
  286.         } catch (Exception e) {
  287.             e.printStackTrace();
  288.         } finally {
  289.             IOKit.closeIo(in);
  290.         }
  291.         return null;
  292.     }

  293.     private static boolean copyFile(File src, File to) {
  294.         if (null != src && src.isFile() && null != to) {
  295.             FileInputStream in = null;
  296.             FileOutputStream out = null;
  297.             byte[] tmp = new byte[8192];
  298.             try {
  299.                 in = new FileInputStream(src);
  300.                 out = new FileOutputStream(to);
  301.                 int n = 0;
  302.                 while (-1 < (n = in.read(tmp))) {
  303.                     out.write(tmp, 0, n);
  304.                 }
  305.                 return true;
  306.             } catch (Exception e) {
  307.                 e.printStackTrace();
  308.             } finally {
  309.                 if (null != out) {
  310.                     try {
  311.                         out.flush();
  312.                     } catch (IOException e) {
  313.                     }
  314.                     IOKit.closeIo(out);
  315.                 }
  316.                 IOKit.closeIo(in);
  317.             }
  318.         }
  319.         return false;
  320.     }

  321.     public static void main(String[] args) throws Exception {
  322.         args = new String[] { "restore", "D:/tmp/J2EE_WP" };
  323.         boolean isERROR = true;
  324.         if (args.length >= 2) {
  325.             Boolean isCache = null;
  326.             boolean isClear = false;
  327.             if ("cache".equals(args[0])) {
  328.                 isCache = true;
  329.                 if (args.length == 3) {
  330.                     isClear = Boolean.valueOf(args[1]);
  331.                 }
  332.             } else if ("restore".equals(args[0])) {
  333.                 isCache = false;
  334.             }
  335.             String pathName = args[args.length - 1].trim();
  336.             if (null != isCache) {
  337.                 new Jars().analysis(pathName, isCache, isClear);
  338.                 return;
  339.             }
  340.         }
  341.         if (isERROR) {
  342.             Logs.debug("using type[cache|restore] isClear[true|false] projectPath");
  343.         }
  344.     }
  345. }
复制代码
文件操作组件
  1. /**
  2. * 创建文件夹
  3. *
  4. * @param file
  5. * @return
  6. */
  7. public static synchronized boolean makeDir(File file) {
  8.     if (null != file) {
  9.         if (file.exists() && file.isDirectory()) {
  10.             return true;
  11.         }
  12.         if (makeDir(file.getParentFile())) {
  13.             file.mkdir();
  14.             return true;
  15.         }
  16.     }
  17.     return false;
  18. }
复制代码
文件流读取
  1. public static byte[] readToByteBuffer(InputStream inStream, int maxSize) throws IOException {
  2.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  3.         if (maxSize > 0) {
  4.             int bufferSize = 0x2000;
  5.             byte[] buffer = new byte[bufferSize];
  6.             int read;
  7.             int remaining = maxSize;

  8.             while (true) {
  9.                 read = inStream.read(buffer);
  10.                 if (-1 == read) {
  11.                     break;
  12.                 }
  13.                 if (read > remaining) {
  14.                     outStream.write(buffer, 0, remaining);
  15.                     break;
  16.                 }
  17.                 remaining -= read;
  18.                 outStream.write(buffer, 0, read);
  19.                 if (bufferSize > read) {
  20.                     break;
  21.                 }
  22.             }
  23.         }
  24.         return outStream.size() > 0 ? outStream.toByteArray() : null;
  25.     }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP