通過jar中的pom查看衝突的jar包

在使用maven進行項目管理時,有時 候引用了第三方的jar文件,這些jar文件裏面一般包含一個pom文件,描述的是它自己依賴的jar包,在這個文件中引用的jar文件有可能會跟工程需要的jar產生版本衝突,這個時候就需要知道到底是哪個jar包引用了衝突的包,下面這段代碼就是會搜索指定目錄下的jar文件,讀取其中的pom.xml。

package com.test;
 
import java.io.File;
import java.io.FileFilter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
 
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * 查找jar文件中的pom.xml文件,並且根據正則來查找dependencies節點中的 groupId,artifactId
 * @author Administrator
 *
 */
public class POMFind {
 
    /**
     * 查找dependency節點
     * 比較 groupId artifactId version(使用正則判斷)
     * 有匹配的結果返回true
     * 
     * @param dependency
     * @param groupIdReg
     * @param artifactIdReg
     * @param versionReg
     * @return
     */
    public static boolean findDependency(Node dependency, String groupIdReg,
            String artifactIdReg, String versionReg) {
        String nodeName = dependency.getNodeName();
        boolean b_groupId = false;
        boolean b_artifactId = false;
        boolean b_version = true;
        if (null == groupIdReg && null == artifactIdReg && null == versionReg)
            return false;
        if (null == nodeName)
            return false;
        nodeName=nodeName.toLowerCase();
        String textContent=String.valueOf(dependency.getTextContent());
        if (null != groupIdReg && "groupid".equals(nodeName)) {
            b_groupId = Pattern.compile(groupIdReg)
                    .matcher(textContent).matches();
        }
        if (null != artifactIdReg && "artifactid".equals(nodeName)) {
            b_artifactId = Pattern.compile(artifactIdReg)
                    .matcher(textContent).matches();
        }
        // version 暫不使用
//      if (null != versionReg && "version".equals(nodeName)) {
//          b_version = Pattern.compile(versionReg)
//                  .matcher(textContent).matches();
//      }
        // version不作爲主要的查詢條件,只作爲groupId 或artifactId的附加條件
        // 只有當groupId 或artifactId兩者匹配時,纔會對version進行匹配
        //  單獨只匹配version無意義
        return (b_groupId || b_artifactId);
    }
 
    /**
     * 獲取jar文件中的pom文件解析出dependencies節點,然後再去解析dependency節點
     * @param in
     * @param groupIdReg
     * @param artifactIdReg
     * @param versionReg
     * @return
     * @throws Exception
     */
    public static boolean excutefind(InputStream in, String groupIdReg,
            String artifactIdReg, String versionReg) throws Exception {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                .newInstance();
        Document document = builderFactory.newDocumentBuilder().parse(in);
        if(null == document.getElementsByTagName("dependencies").item(0))
            return false;
        //dependencies節點
        NodeList nodeList = document.getElementsByTagName("dependencies")
                .item(0).getChildNodes();
        Node node = null;
        for (int i = 0; i < nodeList.getLength(); i++) {
            node = nodeList.item(i);
            if ("dependency".equals(node.getNodeName()) && node.hasChildNodes()) {
                //dependency 節點
                NodeList tlist = node.getChildNodes();
                for (int m = 0; m < tlist.getLength(); m++) {
                    if (findDependency(tlist.item(m), groupIdReg,
                            artifactIdReg, versionReg)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    /**
     * 找出basePath裏面的所有jar文件
     * @param basePath  一般爲tomcat中工程的lib目錄
     * @param fileName   在jar文件中需要查找的文件名稱 (pom.xml)
     * @param groupIdReg
     * @param artifactIdReg
     * @param versionReg
     * @return
     */
    public static List<File> find(String basePath, String fileName,
            String groupIdReg, String artifactIdReg, String versionReg) {
        List<File> list = new ArrayList<File>();
        File root = new File(basePath);
        File[] fileList = root.listFiles(new FileFilter(){
            @Override
            public boolean accept(File f) {
                // TODO Auto-generated method stub
                return f.getName().endsWith(".jar");
            }
 
        });
        for (int i = 0; i < fileList.length; i++) {
            try {
                @SuppressWarnings("resource")
                JarFile jarFile = new JarFile(fileList[i]);
                //  jar文件中的所有JarEntry
                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = (JarEntry) entries.nextElement();
                    String name = jarEntry.getName();
                    // 獲取pom.xml文件
                    if (null != name
                            && fileName.equals(name.substring(
                                    name.lastIndexOf("/") + 1, name.length()))) {
                        boolean result=POMFind.excutefind(jarFile.getInputStream(jarEntry),
                                groupIdReg, artifactIdReg, versionReg);
                        if(result)
                            list.add(fileList[i]);
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return list;
    }
 
    /**
     * @since 2014-3-20
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String basePath = "F:\\test\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\webapp\\WEB-INF\\lib\\";
        String fileName = "pom.xml";
        String artifactIdReg = "^XmlSchema$";
        List<File> list = find(basePath, fileName, null, artifactIdReg, null);
        for (File f : list) {
            System.err.println(f.getName());
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章