烦恼:当我们手上有一堆三方件jar包,想要转成maven管理时,需要一个一个配置进pom文件中,而且GAV信息还得去收集。

为了快速生成如下信息,我们可以这样....

GAV:groupId + artifactId + version

<dependency>

  <groupId></group>

  <artifactId></artifactId>

  <version></version>

</dependency>

1.通过解压jar包文件,从中提取GAV信息

原理:jar包中的pom.properties文件记录了GAV信息。(由于不是每个jar包都有pom.properties文件的,所以没有该文件的则查询不到。此时可以用方法2,或者手动上网搜索)

1.1 sh脚本方式(还是觉得脚本好用)

getGAV.sh /tmp/lib/javax.servlet-3.0.1.jar test/lib/javax.servlet-3.0.1.jar

参数传文件路径就行,支持多参数

#!/bin/bash

##获取jar包的maven依赖GAV信息
function main()
{
    local notFoundList
    for var in $@
    do
        if [ ! -z "$var" ];then
            local jarName=`echo $var | sed 's#.*/##' | sed 's#.jar##g'`
            local dirName=`dirname $var`
            [ ! -d "$dirName/$jarName" ] && unzip $var -d $dirName/$jarName &>/dev/null
            if [ -d "$dirName/$jarName" ];then
                local pomProperties=`find $dirName/$jarName -name pom.properties`
                if [ "$pomProperties" != "" ];then
                    dos2unix $pomProperties &>/dev/null
                    echo "<dependency>"
                    echo "<groupId>"`grep "groupId" $pomProperties | cut -d'=' -f2`"</groupId>"
                    echo "<artifactId>"`grep "artifactId" $pomProperties | cut -d'=' -f2`"</artifactId>"
                    echo "<version>"`grep "version" $pomProperties | cut -d'=' -f2`"</version>"
                    echo "</dependency>"
                else
                    notFoundList="$var $notFoundList"
                fi
                [ -d "$dirName/$jarName" ] && rm -rf "$dirName/$jarName"
            else
                notFoundList="$var $notFoundList"
            fi
        fi
    done
    if [ "$notFoundList" != "" ];then
        echo "============="
        echo "notFoundList: $notFoundList"
        echo "============="
    fi
}

main $@

1.2 java方式

        /**
         * 通过jar包文件解压,获取maven的依赖信息(GAV:groupId artifactId version)
         *
         * @param jarFilePaths jar包文件名或者全路径
         */
        public static void getGavFromJar(String... jarFilePaths) {
            List<String> notFoundList = new ArrayList<String>();
            int successCount = 0;
            for (String jarFilePath : jarFilePaths) {
                File jarFile = new File(jarFilePath);
                if (jarFile.exists() && jarFile.isFile() && jarFilePath.endsWith(".jar")) {
                    String groupId = "";
                    String artifactId = "";
                    String version = "";
                    // 不解压读取压缩包中的文件内容
                    try (
                        ZipInputStream zis = new ZipInputStream(new FileInputStream(jarFile));
                        ZipFile zipFile = new ZipFile(jarFile);
                    ) {
                        ZipEntry zipEntry;
                        boolean hasPomProperties = false;
                        while ((zipEntry = zis.getNextEntry()) != null) {
                            if (zipEntry.getName().startsWith("META-INF/maven") && zipEntry.getName().endsWith("pom.properties")) {
                                try (
                                        BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
                                ) {
                                    String line;
                                    while ((line = br.readLine()) != null) {
                                        if (line.contains("=")) {
                                            String[] arrGVA = line.split("=");
                                            if (arrGVA.length > 1) {
                                                if ("groupId".equals(line.split("=")[0])) {
                                                    groupId = line.split("=")[1];
                                                } else if ("artifactId".equals(line.split("=")[0])) {
                                                    artifactId = line.split("=")[1];
                                                } else if ("version".equals(line.split("=")[0])) {
                                                    version = line.split("=")[1];
                                                }
                                            }
                                        }
                                    }
                                    hasPomProperties = true;
                                    System.out.println("<dependency>\n<groupId>" + groupId + "</groupId>\n<artifactId>" + artifactId + "</artifactId>\n<version>" + version + "</version>\n</dependency>");
                                    successCount++;
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                            }
                        }
                        if (!hasPomProperties) {
                            notFoundList.add(jarFilePath);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    notFoundList.add(jarFilePath);
                }
            }
            System.out.println();
            System.out.println("success: " + successCount + ", failed: " + notFoundList.size() + ", sum: " + jarFilePaths.length));
            System.out.println("notFoundList: " + notFoundList);
        }        

2.通过jar包名称,获取maven的依赖信息GAV

   原理:访问https://mvnrepository.com/search查询获取相关信息。(由于artifactId和version拿捏得不是百分百准确,所以查询准确率也不是百分百)

        /**
         * 通过jar包名称,获取maven的依赖信息(GAV:groupId artifactId version)
         * @param jarFilePaths jar包文件名或者全路径
         */
        public static void getGavFromWeb(String... jarFilePaths) {
            List<String> notFoundList = new ArrayList<String>();
            int successCount = 0;
            for(String jarFilePath : jarFilePaths) {
                if (!StringUtils.isEmpty(jarFilePath) && jarFilePath.endsWith(".jar")) {
                    String searchUrl = "https://mvnrepository.com/search";
                    File jar = new File(jarFilePath);
                    // 去掉.jar后缀
                    String jarName = jar.getName().substring(0, jar.getName().lastIndexOf("."));
                    // 去掉版本号,获取不一定准确的artifactId,用于关键字搜索
                    String artifactIdSimple = jarName.replaceAll("[-|_]\\d.*", "");
                    // 获取不一定准确的version,用于搜索结果筛选
                    String versionSimple = jarName.substring(artifactIdSimple.length()).replaceFirst("[-|_]", "");
                    try {
                        Document doc = Jsoup.connect(searchUrl).data("q", artifactIdSimple).get();
                        Elements ps = doc.getElementsByClass("im-subtitle");
                        if (!CollectionUtils.isEmpty(ps)) {
                            // artifactId搜索结果取第一条
                            Element p = ps.get(0);
                            if (p.childNodeSize() > 1) {
                                String artifactUrl = p.child(1).absUrl("href");
                                // 从search结果的超链接中截取groupId和artifactId
                                String[] ids = artifactUrl.split("/");
                                String groupId = ids[ids.length - 2];
                                String artifactId = ids[ids.length - 1];

                                String version = "";
                                doc = Jsoup.connect(artifactUrl).get();
                                Elements as = doc.getElementsByClass("vbtn release");
                                // version搜索结果中取对应的,若无则取第一条
                                if (!CollectionUtils.isEmpty(as)) {
                                    if (!StringUtils.isEmpty(versionSimple)) {
                                        for (Element a : as) {
                                            if (versionSimple.equals(a.text())) {
                                                version = versionSimple;
                                                break;
                                            }
                                        }
                                    }
                                    if (StringUtils.isEmpty(version)) {
                                        version = as.get(0).text();
                                    }
                                }
                                System.out.println("<dependency>\n<groupId>" + groupId + "</groupId>\n<artifactId>" + artifactId + "</artifactId>\n<version>" + version + "</version>\n</dependency>");
                                successCount++;
                            } else {
                                notFoundList.add(jarFilePath);
                            }
                        } else {
                            notFoundList.add(jarFilePath);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        notFoundList.add(jarFilePath);
                    }
                } else {
                    notFoundList.add(jarFilePath);
                }
            }
            System.out.println();
            System.out.println("success: " + successCount + ", failed: " + notFoundList.size() + ", sum: " + jarFilePaths.length);
            System.out.println("notFoundList: " + notFoundList);
        }

为什么代码中这么多if-else呢,大概是为了提高容错率吧。

通过jar包名称,获取maven的依赖信息GAV的更多相关文章

  1. 获取类路径中含有beans.xml的jar包名称

    获取类路径中含有beans.xml的jar包名称 package com.stono; import java.io.File; import java.io.IOException; import ...

  2. Dev 日志 | 如何将 jar 包发布到 Maven 中央仓库

    摘要 Maven 中央仓库并不支持直接上传 jar 包,因此需要将 jar 包发布到一些指定的第三方 Maven 仓库,比如:Sonatype OSSRH 仓库,然后该仓库再将 jar 包同步到 Ma ...

  3. 如何将JAR包发布到Maven中央仓库?

    将jar包发布到Maven中央仓库(Maven Central Repository),这样所有的Java开发者都可以使用Maven直接导入依赖,例如fundebug-java: <!-- ht ...

  4. 手动添加jar包到本地maven仓库

    我们都知道使用maven管理jar包的时候,我们需要到远程仓库下载相关的jar包到本地仓库,但是如果远程仓库没有这个jar包呢?这时候我们就需要手动将jar包添加到本地仓库. 起因是我想用百度的富文本 ...

  5. java打jar包与找不到依赖包详解

    eclipse打jar包与找不到依赖包详解 eclipse打工具jar 1.项目右键-->export -->搜索java 2.选择JAR file 3.打包 eclipse打包可执行ja ...

  6. 将jar包发布到maven中央仓库

    将jar包发布到maven中央仓库 最近做了一个swagger-ui的开源项目,因为是采用vue进行解析swagger-json,需要前端支持,为了后端也能方便的使用此功能,所以将vue项目编译后的结 ...

  7. 如何手动把jar包添加进Maven本地仓库

    有以下两种情况你需要手动通过Maven命令把jar文件添加进本地仓库: 1.在中心仓库里没有你想要的jar包. 2.你自己写了一个jar包,在其他项目要用到. 补充:现在仍有很多jar包不支持Mave ...

  8. 添加jar包到本地Maven仓库

              在使用Maven的过程中,经常碰到有些jar包在中央仓库没有的情况.如果公司有私服,那么就把jar包安装到私服上.如果没有私服,那就把jar包安装到本地Maven仓库.今天介绍2种 ...

  9. 本地jar包添加至Maven仓库

    Maven命令将本地的jar包方放到maven仓库中 //自定义本地的jar包在pom文件的参数 <dependency> <groupId>com.eee</group ...

随机推荐

  1. C的位运算符

    1.前言 C的位运算符有&(按位与).|(按位或).^(按位异或).~(按位取反),位运算符把运算对象看作是由二进制位组成的位串信息,按位完成指定的运算,得到相应的结果. 2.位运算符 在上面 ...

  2. Java8 新特性 方法引用

    什么是方法引用   方法引用可以被看作仅仅调用特定方法的Lamdba表达式的一种快捷方式.比如说Lamdba代表的只是直接调用这个方法,最好还是用名称来调用它,可不用用对象.方法名(),方法引用,引用 ...

  3. slf4j log4j logback

    最先大家写日志都用log4j,后来作者勇于创新,又搞了个logback,又为了统一江湖,来了个slf4j,所以目前在代码中进行日志输出,推荐使用slf4j,这样在运行时,你可以决定到底是用log4j还 ...

  4. Qt3D NodeInstantiator 使用时报出index out of range错误的记录

    最近用到NodeInstantiator批量加入实体 刚开始用的时候一直程序崩溃 错误代码大致如下: // main.qml ApplicationWindow { ...... Loader { i ...

  5. css z-index 的学习

    前言:这是笔者第一次写博客,主要是学习之后自己的理解.如果有错误或者疑问的地方,请大家指正,我会持续更新! z-index属性描述元素的堆叠顺序(层级),意思是 A 元素可以覆盖 B 元素,但是 B ...

  6. C#拼音帮助类

    如果使用此帮助类需要引用 using Microsoft.International.Converters.PinYinConverter; using NPinyin; 可以在NuGet里面下载 1 ...

  7. C# 字符串和字节数组转换

    转自:http://blog.sina.com.cn/s/blog_683d60ff0100rhwk.html 定义string变量为str,内存流变量为ms,比特数组为bt 1.字符串转比特数组 ( ...

  8. [C++] 初始化 vs 赋值

  9. 模型文件(checkpoint)对模型参数的储存与恢复

    1.  模型参数的保存: import tensorflow as tfw=tf.Variable(0.0,name='graph_w')ww=tf.Variable(tf.random_normal ...

  10. bytearray与矩阵转换对应关系

    import numpy as npimport osa=bytearray(os.urandom(27))# for i in range(21):# print(a[i])a=np.array(a ...