##maven依赖文件自动解析
###项目描述:
将web项目转换为maven格式时,需要解决jar包依赖,并生成pom.xml;
默认通过eclipse的maven插件自动转换时,原有的lib无法自动解析,需要手工编写pom文件,比较复杂;
通过此类,可以自动解析生成jar包的依赖信息;
经实践,约51%的jar可以自动解析,剩余的jar需要手工进行维护;
###解析算法:
1、如果jar文件由maven生成,则jar文件中包含pom.properties文件,可以解析该文件获取pom信息;
2、如果无法从jar文件中解析,则从本地maven资源库中读取pom信息,默认pom文件命名:jar文件名.pom
3、对于无法解析的内容,需要将jar文件名拷贝到excel中,手工编辑依赖信息;
###java代码
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class MavenDependencyExtract {
private static Logger log = Logger.getLogger(MavenDependencyExtract.class);
public static void main(String[] args) throws Exception {
// 待解析的jar包目录
String projectPath = "D:\\WorkSpace\\lib";
// 本地manven资源库
String mavenPath = "E:\\maven\\repository";
(new MavenDependencyExtract()).parse(projectPath, mavenPath);
}
public void parse(String projectPath, String mavenPath) {
try {
List<File> projectLibList = new ArrayList<File>();
List<String> findList = new ArrayList<String>();
Map<String, String> mvnPomMap = new HashMap<String, String>();
initFileMap(mavenPath, mvnPomMap, ".pom");
initFileList(projectPath, projectLibList, ".jar");
System.out.println("-----------------------------------------start");
System.out.println("jar文件\t状态\t依赖包");
for (File f : projectLibList) {
String dep = parseJarFile(f.getAbsolutePath());
String name = f.getName();
String status = "否";
if (dep == null || dep.equals("")) // 从maven查找
dep = parsePomFile(name, mvnPomMap);
if (dep == null || dep.equals("")) {// 无法解析
dep = "";
} else {
status = "是";
findList.add(name);
}
System.out.println(name + "\t" + status + "\t" + dep);
}
System.out.println("-----------------------------------------end");
System.out.println("jar包总数:" + projectLibList.size());
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("匹配pom数:" + findList.size() + "("
+ df.format(findList.size() * 100.0 / projectLibList.size()) + "%)");
System.out.println("对于无法解析的内容,请将横线中的内容拷贝到excel中,进行二次编辑。");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从jar文件中解析maven依赖信息
*
*
* 原始文件:quartz-1.8.6.jar
* 原始数据样式:
* version=1.8.6
* groupId=org.quartz-scheduler
* artifactId=quartz
*
* 解析后返回的数据样式:
*
* org.quartz-scheduler
* quartz
* 1.8.6
*
*
*
* @param file
* @return maven格式依赖信息
* @throws Exception
*/
private String parseJarFile(String file) throws Exception {
ZipFile zf = new ZipFile(file);
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
String dep = "";
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
} else {
long size = ze.getSize();
if (size > 0 && ze.getName().matches(".*pom.properties")) {
BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
String line;
Map<String, String> map = new HashMap<String, String>();
while ((line = br.readLine()) != null) {
String name = null;
if (line.matches("version=.*"))
name = "version";
if (line.matches("groupId=.*"))
name = "groupId";
if (line.matches("artifactId=.*"))
name = "artifactId";
if (name != null)
map.put(name, line.split("=")[1]);
}
br.close();
if (map.size() == 3) {
dep = "" ;
dep += "" + map.get("groupId") + "";
dep += "" + map.get("artifactId") + "";
dep += "" + map.get("version") + "";
dep += "";
}
}
}
}
zin.closeEntry();
zin.close();
zf.close();
return dep;
}
/**
* 从pom文件中解析maven依赖信息
*
* @param name
* 待解析的jar文件名称
* @param mvnPomMap
* 包含pom文件的map
* @return 解析后的解析maven依赖信息
*/
private String parsePomFile(String name, Map<String, String> mvnPomMap) {
String dep = "";
name = name.substring(0, name.length() - 3) + "pom";
if (mvnPomMap.containsKey(name)) {
String path = mvnPomMap.get(name);
Element root = getRoot(path);
dep = "" ;
dep += getWarpValue(root, "groupId");
dep += getWarpValue(root, "artifactId");
dep += getWarpValue(root, "version");
dep += "";
}
return dep;
}
private String getWarpValue(Element parent, String childName) {
String result = "";
Element element = parent.element(childName);
if (element != null) {
result = "<" + childName + ">" + element.getStringValue() + "" + childName + ">";
}
return result;
}
/**
* 获取xml根节点
*
* @param fileName
* xml文件名称
* @return 返回xml根节点
*/
private Element getRoot(String fileName) {
Element root = null;
try {
Document document = DocumentHelper.parseText(getFileString(fileName));
root = document.getRootElement();
} catch (Exception e) {
log.error("初始化xml失败:" + e);
}
return root;
}
/**
* 遍历目录下的,扩展名为suffix的文件列表
*
* @param strPath
* 根目录
* @param filelist
* 返回list
* @param suffix
* 文件扩展名
*/
private void initFileList(String strPath, List<File> filelist, String suffix) {
File dir = new File(strPath);
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
String fileName = f.getName();
if (f.isDirectory()) {
initFileList(f.getAbsolutePath(), filelist, suffix);
} else if (fileName.endsWith(suffix)) {
filelist.add(f);
}
}
}
}
/**
* 遍历目录下的,扩展名为suffix的文件
*
* @param strPath
* 根目录
* @param fileMap
* 返回map
* @param suffix
* 文件扩展名
*/
private void initFileMap(String strPath, Map<String, String> fileMap, String suffix) {
File dir = new File(strPath);
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
String fileName = f.getName();
if (f.isDirectory()) {
initFileMap(f.getAbsolutePath(), fileMap, suffix);
} else if (fileName.endsWith(suffix)) {
fileMap.put(fileName, f.getAbsolutePath());
}
}
}
}
/**
* 读取文本文件,返回字符串
*
* @param path
* 文件全路径
* @return 返回文件内容
*/
private String getFileString(String path) {
String result = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
String line;
while ((line = br.readLine()) != null)
result += line;
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}