基于 Maven 中心库,通过 Jar 包生成 POM 的 dependency

#Maven#Java#工具

背景

之前写过一篇通过 Jar 包生成 Maven POM.xml 的 dependency,方便将非 Maven 项目转换为 Maven 项目。 原项目对 Jar 的搜索基于 Nexus2 的相关接口开发,随着很多仓库从 Nexus2 升级到 Nexus3 或者其他服务,原项目渐渐不可用了。 新代码将 Nexus2 接口改为对接 Maven 中心库。站内另留了一份 Nexus2 版的代码。

项目结构

整个项目只有 6 个 Java 文件 —— 一个主类,加上五个用来接中心库返回值的实体类:

jar2pom
├── pom.xml
└── src/main/java/com/jxh/tool
    ├── Jar2pom.java              # 主类:遍历目录里的 jar、查坐标、打印 dependency
    └── entity
        ├── SolrSearch.java       # 响应根节点
        ├── ResponseHeader.java   # 状态码与耗时
        ├── Response.java         # 结果集
        ├── Docs.java             # 单条坐标
        └── Spellcheck.java       # 拼写建议

Maven 坐标是 cn.jxh.tool:jar2pom:2.0-SNAPSHOT,依赖只有三个:httpclient 4.5.5 负责发请求,fastjson 1.2.68 负责解 JSON,dom4j 负责拼 XML。README 里记的开发环境是 JDK 1.7 + Maven 3.5 + IDEA 社区版。

核心代码

    public static void main(String[] args) {
        //先通过Jar的SHA1查询 如果不存在则解析Manifest查询
        File libs = new File("D:\\lib");
        for (File jar : libs.listFiles()) {

            System.out.println("<!--  " + jar.getName() + " -->");

            Docs doc = getPomByChecksum(jar);
            if (null != doc) {
                System.out.println("<!--  Search by Checksum -->");
                System.out.println(assemblePomElement(doc).asXML());
                continue;
            }

            doc = getPomByManifest(jar);
            if (null != doc) {
                System.out.println("<!--  Search by Manifest -->");
                System.out.println(assemblePomElement(doc).asXML());
                continue;
            }

            System.out.println("<!--  No data was found -->");

            System.out.println();
        }

    }

    /**
     * 通过Jar SHA1返回Pom dependency
     *
     * @param file
     * @return
     */
    public static Docs getPomByChecksum(File file) {
        Docs docs = null;

        String checkSum = getCheckSum(file, "SHA1");
        String jsonString = doGet(nexusUrl + "&q=1:" + checkSum);
        SolrSearch solrSearch = JSONObject.parseObject(jsonString, SolrSearch.class);

        if (solrSearch.getResponseHeader().getStatus() == 0 && solrSearch.getResponse().getDocs().size() > 0) {
            docs = solrSearch.getResponse().getDocs().get(0);
        }
        return docs;
    }


    /**
     * 通过Jar Manifest返回Pom dependency
     *
     * @param file
     * @return
     */
    public static Docs getPomByManifest(File file) {
        Docs docs = null;

        try {
            JarFile jarfile = new JarFile(file);
            Manifest mainmanifest = jarfile.getManifest();
            jarfile.close();
            if (null == mainmanifest) {
                return null;
            }
            String a = null, v = null;
            if (mainmanifest.getMainAttributes().containsKey(new Attributes.Name("Extension-Name"))) {
                a = mainmanifest.getMainAttributes().getValue(new Attributes.Name("Extension-Name"));
            } else if (mainmanifest.getMainAttributes().containsKey(new Attributes.Name("Implementation-Title"))) {
                a = mainmanifest.getMainAttributes().getValue(new Attributes.Name("Implementation-Title"));
            } else if (mainmanifest.getMainAttributes().containsKey(new Attributes.Name("Specification-Title"))) {
                a = mainmanifest.getMainAttributes().getValue(new Attributes.Name("Specification-Title"));
            }
            if (a != null && a.length() != 0) {
                a = a.replace("\"", "").replace(" ", "-");
            }
            if (mainmanifest.getMainAttributes().containsKey(new Attributes.Name("Bundle-Version"))) {
                v = mainmanifest.getMainAttributes().getValue(new Attributes.Name("Bundle-Version"));
            } else if (mainmanifest.getMainAttributes().containsKey(new Attributes.Name("Implementation-Version"))) {
                v = mainmanifest.getMainAttributes().getValue(new Attributes.Name("Implementation-Version"));
            } else if (mainmanifest.getMainAttributes().containsKey(new Attributes.Name("Specification-Version"))) {
                v = mainmanifest.getMainAttributes().getValue(new Attributes.Name("Specification-Version"));
            }
            if (v != null && v.length() != 0) {
                v = v.replace("\"", "").replace(" ", "-");
            }
            String jsonString = doGet(nexusUrl + "&q=a:" + a + "%20v:" + v);
            SolrSearch solrSearch = JSONObject.parseObject(jsonString, SolrSearch.class);

            if (solrSearch.getResponseHeader().getStatus() == 0) {
                docs = solrSearch.getResponse().getDocs().get(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return docs;
    }

    /**
     * 组装 dependency
     *
     * @param docs
     * @return
     */
    public static Element assemblePomElement(Docs docs) {
        Element dependency = new DOMElement("dependency");
        if (docs != null) {
            dependency.addAttribute("groupId", docs.getG());
            dependency.addAttribute("artifactId", docs.getA());
            dependency.addAttribute("version", docs.getV());
        }
        return dependency;
    }

    /**
     * 发起Get请求
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {
        String srtResult = null;
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpCilent.execute(httpGet);
            srtResult = EntityUtils.toString(httpResponse.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpCilent.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return srtResult;
    }

    /**
     * 计算CheckSum
     *
     * @param file
     * @param algorithm SHA1 or MD5
     * @return
     */
    public static String getCheckSum(File file, String algorithm) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance(algorithm);
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

Solr 的响应是怎么变成对象的

中心库这套接口底下是 Solr,回给你的是一坨嵌套 JSON。代码没有一层层 getJSONObject() 去抠字段,而是让 fastjson 直接把整段响应收进对象:

SolrSearch solrSearch = JSONObject.parseObject(jsonString, SolrSearch.class);

映射规则就是「字段名对上即可」,所以五个实体类都很薄:

类对应节点字段实际用到
SolrSearch根节点responseHeader / response / spellcheck三个容器
ResponseHeaderresponseHeaderstatus / QTimestatus == 0 即查询成功
ResponseresponsenumFound / start / docsdocs
Docsdocs[] 的每一项id / g / a / v / p / latestVersion / versionCount / timestamp / text / ec / repositoryIdg / a / v
Spellcheckspellchecksuggestions没用上

能落进 dependency 的只有三个字段,正好是 Solr 那份命名里的单字母缩写:

dependency.addAttribute("groupId", docs.getG());
dependency.addAttribute("artifactId", docs.getA());
dependency.addAttribute("version", docs.getV());

g / a / v 之外的那些 —— latestVersion(最新版本)、p(打包类型)、ec(该版本下有哪些文件)、versionCount(版本总数)、repositoryId(命中哪个仓库)、Spellcheck.suggestions(拼写建议)—— 都解析了但没用。类的骨架留在那里,将来想加「取最新版」或者「提示拼写」,字段是现成的。

用实体类而不是手写 JSON 路径,好处很直白:解析一行就完成,后面取值都是 getter,字段名写错了编译器直接报,而不是运行时静默接到一个 null。

它什么时候查不出结果

这个工具解决的是「一批本地 jar,不知道 Maven 坐标」。但它依赖两个前提:jar 公开发布过,且 Manifest 没被改过。下面这几种情况它就交不出来,用之前心里有个数:

  1. jar 压根不在 Maven 中心库。 中心库只收公开发布过的构件。国内厂商私服的包、公司内部工具包,以及因为授权原因不能上中心库的(典型是 Oracle 的 JDBC 驱动),SHA1 查不到,Manifest 也拼不出可用坐标,最后只打印一行 No data was found,得自己手写。
  2. 只查中心库一个源。 nexusUrl 是写死的中心库地址,查不了公司私服(Nexus3、Artifactory)。要换成自家仓库,改这个常量和对应的查询参数即可 —— 2018 那版就是从 Nexus2 这么换过来的,前提是私服也提供可搜索接口。
  3. Manifest 里的名字不等于 Maven 坐标。 回退这条路,artifactId 是拿 Extension-Name → Implementation-Title → Specification-Title 依次取的,version 取 Bundle-Version → Implementation-Version → Specification-Version。很多 jar 这几个字段是空的,或者写的是「XXX SDK」这种给人看的名字,搜出来的结果就不保证对;被改过包名、重新打过的 jar,SHA1 也会落空,最后都只能走到这条「猜」的路上。所以输出里标着 Search by Manifest 的那几条,建议开 Maven 仓库页面核一眼。
  4. 命中多条时只取第一条。 无论走哪条路,最后都是 getDocs().get(0),没有按版本排序再挑这类逻辑 —— 查询串里本来就带了 rows=1,只打算要一条。
  5. 用法上的硬编码。 main() 里待处理目录写死成 D:\lib,libs.listFiles() 只扫一层、也不筛后缀,换成别的路径、或者 lib 下面还有子目录,都得先改代码;结果是打在标准输出里的,得自己从控制台复制出来。

下载地址

早年的仓库链接挂在 JiaXiaohei 这个账号名下,后来改成了 Megawatt,老链接会自动跳过去,外部引用不用改。