如何从包含jar文件的lib文件夹中在pom.xml中生成/创建依赖项

时间:2019-01-25 19:07:13

标签: maven dependencies pom.xml

假设我有一个文件夹,其中包含maven项目所需的所有jar文件。

我想从文件夹中的jar文件自动填充/写入pom.xml部分中的依赖项。有没有现成的自动化方法?

如果文件夹中有一个log4j-core-2.11.1.jar文件,我想获取:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>

谢谢

3 个答案:

答案 0 :(得分:0)

假设jar文件是Maven构建的结果,则可以从以下代码开始:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class CheckMe {

  public static void main(String args[]) throws IOException {

    String fileZip =
        "yourjar.jar";
    ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
    ZipEntry zipEntry = zis.getNextEntry();
    while (zipEntry != null) {
      if (zipEntry.getName().endsWith("pom.xml")) {
        final StringBuilder pom = new StringBuilder();
        final byte[] buffer = new byte[1024];

        while (zis.read(buffer, 0, buffer.length) != -1) {
          pom.append(new String(buffer));
        }

        System.out.println("<dependency>");
        Scanner scanner = new Scanner(pom.toString());
        boolean groupDone = false, artifactDone = false, versionDone = false;
        while (scanner.hasNextLine()) {
          String line = scanner.nextLine();
          if (line.contains("groupId") && !groupDone) {
            System.out.println(line);
            groupDone = true;
          }
          if (line.contains("artifactId") && !artifactDone) {
            System.out.println(line);
            artifactDone = true;
          }
          if (line.contains("version") && !versionDone) {
            System.out.println(line);
            versionDone = true;
          }
        }
        scanner.close();
        System.out.println("</dependency>");
      }
      zipEntry = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
  }
}

这是一个快速的技巧,您必须添加目录扫描程序才能获取jar文件的名称,但这应该可以解决问题。

答案 1 :(得分:0)

@Jens:谢谢,您的代码绝对有帮助(无法投票赞成您;低声望)

由于我想要一种快速(至少对我而言)的方法,所以我最终得到了一些python行: 他们在这里(以防他们能帮助您)

import sys
import json
from urllib.request import urlopen
import hashlib
from string import Template
from collections import namedtuple
from os import listdir

path = 'your path to jar folder'
files = listdir(path)


def hashfile(filepath):
    f = open(filepath, 'rb')
    readFile = f.read()
    sha1Hash = hashlib.sha1(readFile)
    sha1Hashed = sha1Hash.hexdigest()
    return sha1Hashed

def request( hash ):
    url = 'https://search.maven.org/solrsearch/select?q=1:' + \
        hash+'&wt=json&rows=1'
    response = urlopen(url).read()
    return json.loads(response.decode('utf-8'));

dep = '''
<dependency>
    <groupId> $g </groupId>
    <artifactId> $a </artifactId>
    <version> $v </version>
</dependency>
'''

deps= '''
<dependencies>
    $d
</dependencies>
'''

deb_tpl = Template(dep)
debs_tpl = Template(deps)
Jar = namedtuple('Jar',[ 'g', 'a', 'v'])

dependencies = [None]*len(files)
for i, filename in enumerate(files):
    sha1=hashfile( "%s/%s" %(path, filename))
    print("File : %i : sha1 : %s" % (i, sha1))
    obj = request( str(sha1 ))
    if obj['response']['numFound'] == 1:
        jar = Jar(obj['response']['docs'][0]['g'],
                 obj['response']['docs'][0]['a'],
                 obj['response']['docs'][0]['v'])
        dependencies[i] = jar

#         print(obj['response']['docs'][0]['a'])
#         print(obj['response']['docs'][0]['g'])
#         print(obj['response']['docs'][0]['v'])

    else :
        print('Cannot find %s' % filename)
        dependencies[i] = None
deps_all = '\r\n'.join([ deb_tpl.substitute(f._asdict())for f in dependencies if f is not None ])
debs_tpl.substitute(d=deps_all)
print(res)

最终res给了我在search.maven上找到的所有依赖项。 对于缺少的罐子,您可以使用this answer

答案 2 :(得分:0)

我运行了 python 脚本,但它没有完全充实嵌套文件夹等。我在 How to know groupid and artifactid of any external jars in maven android project 找到了一个很好的替代脚本