经过jar包名称,获取maven的依赖信息GAV

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

为了快速生成以下信息,咱们能够这样....bash

GAV:groupId + artifactId + versionmaven

<dependency>spa

  <groupId></group>unix

  <artifactId></artifactId>code

  <version></version>blog

</dependency>ip

 

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

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

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呢,大概是为了提升容错率吧。