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

fslejnso  于 2024-01-06  发布在  Maven
关注(0)|答案(4)|浏览(271)

假设我有一个包含maven项目中所需的所有jar文件的文件夹。
我想从文件夹中的jar文件自动填充/写入pom.xml部分中的依赖关系。是否有现有的自动化方法?
如果文件夹中有一个log4j-core-2.11.1.jar文件,我想得到:

  1. <dependency>
  2. <groupId>org.apache.logging.log4j</groupId>
  3. <artifactId>log4j-core</artifactId>
  4. <version>2.11.1</version>
  5. </dependency>

字符串
谢谢你

mtb9vblg

mtb9vblg1#

@Jens:谢谢你,你的代码绝对有帮助(不能投票给你;低代表)
由于我想快速(至少对我来说),我最后用了几行Python代码:

  1. import sys
  2. import json
  3. from urllib.request import urlopen
  4. import hashlib
  5. from string import Template
  6. from collections import namedtuple
  7. from os import listdir
  8. path = 'your path to jar folder'
  9. files = listdir(path)
  10. def hashfile(filepath):
  11. f = open(filepath, 'rb')
  12. readFile = f.read()
  13. sha1Hash = hashlib.sha1(readFile)
  14. sha1Hashed = sha1Hash.hexdigest()
  15. return sha1Hashed
  16. def request( hash ):
  17. url = 'https://search.maven.org/solrsearch/select?q=1:' + \
  18. hash+'&wt=json&rows=1'
  19. response = urlopen(url).read()
  20. return json.loads(response.decode('utf-8'));
  21. dep = '''
  22. <dependency>
  23. <groupId> $g </groupId>
  24. <artifactId> $a </artifactId>
  25. <version> $v </version>
  26. </dependency>
  27. '''
  28. deps= '''
  29. <dependencies>
  30. $d
  31. </dependencies>
  32. '''
  33. deb_tpl = Template(dep)
  34. debs_tpl = Template(deps)
  35. Jar = namedtuple('Jar',[ 'g', 'a', 'v'])
  36. dependencies = [None]*len(files)
  37. for i, filename in enumerate(files):
  38. sha1=hashfile( "%s/%s" %(path, filename))
  39. print("File : %i : sha1 : %s" % (i, sha1))
  40. obj = request( str(sha1 ))
  41. if obj['response']['numFound'] == 1:
  42. jar = Jar(obj['response']['docs'][0]['g'],
  43. obj['response']['docs'][0]['a'],
  44. obj['response']['docs'][0]['v'])
  45. dependencies[i] = jar
  46. # print(obj['response']['docs'][0]['a'])
  47. # print(obj['response']['docs'][0]['g'])
  48. # print(obj['response']['docs'][0]['v'])
  49. else :
  50. print('Cannot find %s' % filename)
  51. dependencies[i] = None
  52. deps_all = '\r\n'.join([ deb_tpl.substitute(f._asdict())for f in dependencies if f is not None ])
  53. debs_tpl.substitute(d=deps_all)
  54. print(res)

字符串
Final res提供了search. maven上找到的所有依赖项。

展开查看全部
monwx1rj

monwx1rj2#

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

  1. import java.io.FileInputStream;
  2. import java.io.IOException;
  3. import java.util.Scanner;
  4. import java.util.zip.ZipEntry;
  5. import java.util.zip.ZipInputStream;
  6. public class CheckMe {
  7. public static void main(String args[]) throws IOException {
  8. String fileZip =
  9. "yourjar.jar";
  10. ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
  11. ZipEntry zipEntry = zis.getNextEntry();
  12. while (zipEntry != null) {
  13. if (zipEntry.getName().endsWith("pom.xml")) {
  14. final StringBuilder pom = new StringBuilder();
  15. final byte[] buffer = new byte[1024];
  16. while (zis.read(buffer, 0, buffer.length) != -1) {
  17. pom.append(new String(buffer));
  18. }
  19. System.out.println("<dependency>");
  20. Scanner scanner = new Scanner(pom.toString());
  21. boolean groupDone = false, artifactDone = false, versionDone = false;
  22. while (scanner.hasNextLine()) {
  23. String line = scanner.nextLine();
  24. if (line.contains("groupId") && !groupDone) {
  25. System.out.println(line);
  26. groupDone = true;
  27. }
  28. if (line.contains("artifactId") && !artifactDone) {
  29. System.out.println(line);
  30. artifactDone = true;
  31. }
  32. if (line.contains("version") && !versionDone) {
  33. System.out.println(line);
  34. versionDone = true;
  35. }
  36. }
  37. scanner.close();
  38. System.out.println("</dependency>");
  39. }
  40. zipEntry = zis.getNextEntry();
  41. }
  42. zis.closeEntry();
  43. zis.close();
  44. }
  45. }

字符串
这是一个快速的黑客,你必须添加你的目录扫描仪,以获得所有的jar文件名,但它应该做的伎俩。

展开查看全部
qncylg1j

qncylg1j3#

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

8i9zcol2

8i9zcol24#

基于toki lou tok的想法,我在Java中实现了针对maven central的sha1hash检查。

  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FilenameFilter;
  5. import java.io.IOException;
  6. import java.security.MessageDigest;
  7. import java.security.NoSuchAlgorithmException;
  8. import org.junit.Test;
  9. import java.io.InputStreamReader;
  10. import java.net.MalformedURLException;
  11. import java.net.URL;
  12. import java.net.URLConnection;
  13. import org.codehaus.jettison.json.JSONException;
  14. import org.codehaus.jettison.json.JSONObject;
  15. public class PomBuilder {
  16. @Test
  17. public void buildPOM() {
  18. String pathToFolder = "path to lib folder";
  19. File currentDirectory = new File(pathToFolder);
  20. // Get a list of all the jars in the current directory
  21. File[] jars = currentDirectory.listFiles(new FilenameFilter() {
  22. @Override
  23. public boolean accept(File dir, String name) {
  24. return name.endsWith(".jar");
  25. }
  26. });
  27. for (File jar : jars) {
  28. try {
  29. //extractPomStream(jar);
  30. String hashedFile = getSHA1Hash(jar);
  31. String urlString = "https://search.maven.org/solrsearch/select?q=1:" +
  32. hashedFile+"&wt=json&rows=1";
  33. String response = getUrlContent(urlString);
  34. JSONObject json = new JSONObject(response);
  35. JSONObject dependency = json.getJSONObject("response").getJSONArray("docs").getJSONObject(0);
  36. String depEntry = formatDependencyEntry((String) dependency.get("g"), (String) dependency.get("a"), (String) dependency.get("v"));
  37. System.out.println(depEntry);
  38. } catch (IOException | NoSuchAlgorithmException | JSONException e) {
  39. // TODO Auto-generated catch block
  40. //e.printStackTrace();
  41. System.out.println("Failed to create entry for " + jar.getName());
  42. }
  43. }
  44. }
  45. private String formatDependencyEntry(String groupId, String artifactId, String version) {
  46. String dependency = "<dependency>\r\n"
  47. + " <groupId><<groupID>></groupId>\r\n"
  48. + " <artifactId><<artifactId>></artifactId>\r\n"
  49. + " <version><<version>></version>\r\n"
  50. + "</dependency>";
  51. if(groupId == null)
  52. groupId="";
  53. if(artifactId == null)
  54. artifactId = "";
  55. if(version == null)
  56. version = "";
  57. dependency = dependency.replace("<<groupID>>", groupId);
  58. dependency = dependency.replace("<<artifactId>>", artifactId);
  59. dependency = dependency.replace("<<version>>", version);
  60. return dependency;
  61. }
  62. public String getSHA1Hash(File file) throws NoSuchAlgorithmException, IOException {
  63. MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
  64. try(FileInputStream fileInputStream = new FileInputStream(file)){
  65. byte[] buffer = new byte[1024];
  66. int bytesRead;
  67. while ((bytesRead = fileInputStream.read(buffer)) != -1) {
  68. messageDigest.update(buffer, 0, bytesRead);
  69. }
  70. byte[] sha1Hash = messageDigest.digest();
  71. return convertByteArrayToHex(sha1Hash);
  72. }
  73. }
  74. private String convertByteArrayToHex(byte[] bytes) {
  75. StringBuilder hexString = new StringBuilder();
  76. for (byte b : bytes) {
  77. hexString.append(String.format("%02x", b));
  78. }
  79. return hexString.toString();
  80. }
  81. public String getUrlContent(String urlString) {
  82. URL url;
  83. try {
  84. url = new URL(urlString);
  85. URLConnection conn = url.openConnection();
  86. // open the stream and put it into BufferedReader
  87. BufferedReader br = new BufferedReader(
  88. new InputStreamReader(conn.getInputStream()));
  89. String inputLine;
  90. String returnString = "";
  91. while ((inputLine = br.readLine()) != null) {
  92. returnString += inputLine;
  93. }
  94. br.close();
  95. return returnString;
  96. } catch (MalformedURLException e) {
  97. e.printStackTrace();
  98. } catch (IOException e) {
  99. e.printStackTrace();
  100. }
  101. return "fail";
  102. }
  103. }

字符串

展开查看全部

相关问题