烦恼:当我们手上有一堆三方件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. EXT.net 1.x TreePanel的一个坑

    Ext.net TreePanel有一个方法 drptreepanel.setChecked({ ids: idsarray, silent: true });  如果TreePanel里有1,3两个 ...

  2. jmeter通过BeanShell,实现对接口参数HmacSHA256加密(转)

    jmeter通过BeanShell,实现对接口参数HmacSHA256加密2019-04-29 05:10 ps. 最近抓包网站的登陆请求,发现就2个参数,用户名和密码,通过工具去请求这个接口,一直返 ...

  3. cmake 配置

    罗列一下cmake常用的命令.CMake支持大写.小写.混合大小写的命令. 1. 添加头文件目录INCLUDE_DIRECTORIES 语法:include_directories([AFTER|BE ...

  4. DRF框架和Vue框架阅读目录

    Vue框架目录 (一)Vue框架(一)——Vue导读.Vue实例(挂载点el.数据data.过滤器filters).Vue指令(文本指令v-text.事件指令v-on.属性指令v-bind.表单指令v ...

  5. JDK9版本以上Java独有的一个轻量级小工具,你知道吗?jshell

    jshell,是JavaJDK9这个大版本更新以来,带来的一个轻量级小工具.我们再也不用进入Java目录,编写一个Java文件,然后再去编译,最后才能执行它. 这里,你可以直接写一个小功能,就能去实现 ...

  6. 局域网访问PHP项目网站 用IP地址进入

    先在apache中的 httpd.conf中将 Allow from 127.0.0.1 修改为Allow from all 如果你的是Allow from all的话就不需要改 然后再将 Docum ...

  7. 动软软件 生成 实体类模板(EnterpriseFrameWork框架)

    1.废话不多说,直接上效果图 . 2 .动软模板代码 <#@ template language="c#" HostSpecific="True" #&g ...

  8. Winows上简单配置使用kafka(.net使用)

    一.kafka环境配置 1.jdk安装 安装文件:http://www.oracle.com/technetwork/java/javase/downloads/index.html 下载JDK安装完 ...

  9. 端口排查步骤-7680端口分析-Dosvc服务

    出现大量7680端口的内网连接,百度未找到端口信息,需证明为系统服务,否则为蠕虫 1. 确认端口对应进程PID netstat -ano 7680端口对应pid:6128 2. 查找pid对应进程 t ...

  10. IntelliJ IDEA live template 方法配置

    ** * <p></p> * 功能描述 * $params$ * @return $return$ * @author abc * @date $time$ $date$ * ...