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

问题描述 投票:0回答:4

假设我有一个文件夹,其中包含 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>

谢谢你

maven dependencies pom.xml
4个回答
2
投票

@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)

Final res 为我提供了在 search.maven 上找到的所有依赖项。 对于丢失的罐子,您可以使用这个答案


1
投票

假设 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
投票

我运行了python脚本,但它没有完全充实wrt嵌套文件夹等。我在如何知道maven android项目中任何外部jar的groupid和artifactid中找到了一个很好的替代脚本


0
投票

为了构建 toki lou tok 的想法,我在 Java 中实现了针对 Maven Central 的 sha1hash 检查。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.junit.Test;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class PomBuilder {

    @Test
    public void buildPOM() {
        String pathToFolder = "path to lib folder";

        File currentDirectory = new File(pathToFolder);

        // Get a list of all the jars in the current directory
        File[] jars = currentDirectory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
            }
        });

        for (File jar : jars) {
            try {
                //extractPomStream(jar);
                String hashedFile = getSHA1Hash(jar);
                
                String urlString = "https://search.maven.org/solrsearch/select?q=1:" + 
                        hashedFile+"&wt=json&rows=1";
                
                String response = getUrlContent(urlString);
                
                JSONObject json = new JSONObject(response); 
                JSONObject dependency = json.getJSONObject("response").getJSONArray("docs").getJSONObject(0);
                
                String depEntry = formatDependencyEntry((String) dependency.get("g"), (String) dependency.get("a"), (String) dependency.get("v"));
                
                System.out.println(depEntry);
            } catch (IOException | NoSuchAlgorithmException | JSONException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                System.out.println("Failed to create entry for " + jar.getName());
            }
        }
    }
    
    private String formatDependencyEntry(String groupId, String artifactId, String version) {
        String dependency = "<dependency>\r\n" 
                + " <groupId><<groupID>></groupId>\r\n"
                + " <artifactId><<artifactId>></artifactId>\r\n"
                + " <version><<version>></version>\r\n" 
                + "</dependency>";
        
        if(groupId == null)
            groupId="";
            
        if(artifactId == null)
            artifactId = "";
            
        if(version == null) 
            version = "";
        
        dependency = dependency.replace("<<groupID>>", groupId);
        dependency = dependency.replace("<<artifactId>>", artifactId);
        dependency = dependency.replace("<<version>>", version);
        
        return dependency;
    }

    public String getSHA1Hash(File file) throws NoSuchAlgorithmException, IOException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        try(FileInputStream fileInputStream = new FileInputStream(file)){
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                messageDigest.update(buffer, 0, bytesRead);
            }
            byte[] sha1Hash = messageDigest.digest();
            return convertByteArrayToHex(sha1Hash);
        }
    }

    private String convertByteArrayToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    public String getUrlContent(String urlString) {
        URL url;

        try {
            url = new URL(urlString);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));

            String inputLine;
            String returnString = "";
            while ((inputLine = br.readLine()) != null) {
                returnString += inputLine;
            }
            br.close();

            return returnString;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";
    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.