import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
//import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class ConvertJAR{
static String libdir = "D:/mvnConcert";
static String correctlibdir = libdir+"/correct/";
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException {
Element dependencys = new DOMElement("dependencies");
File dir = new File(libdir); //需生成pom.xml 文件的 lib路径
//---第一遍,精确sh1从仓库取
for (File jar : dir.listFiles()) {
System.out.println("开始::::"+jar.getName());
if (jar.isDirectory()) continue;
Element ele = getDependices2(jar);
if (ele == null || ele.elements().size() == 0) {
continue;
}
dependencys.add(ele);
sharpFile(jar);
System.out.println("完成::::"+jar.getName());
}
System.out.println("\\\n\\\n\\\n\\\n\\\n\\\n\\\n\\\n\\\n\\\n\\\n\\\n\\\n");
//---第二遍,从jar包内取
for (File jar : dir.listFiles()) {
System.out.println("开始::::"+jar.getName());
if (jar.isDirectory()) continue;
Element ele = getDependices3(jar);
if (ele == null||ele.elements().size() == 0) {
continue;
}
dependencys.add(ele);
sharpFile(jar);
System.out.println("完成::::"+jar.getName());
}
System.out.println(dependencys.asXML());
}
// /**
// *外网用
// * @param file
// * @return
// */
// public static Element getDependices(File file) {
// Element dependency = new DOMElement("dependency");
// // 设置代理
// // System.setProperty("http.proxyHost", "127.0.0.1");
// // System.setProperty("http.proxyPort", "8090");
// try {
// String sha1 = getSha1ByFile(file);
// String url = "http://search.maven.org/solrsearch/select?q=1:" + sha1 + "&rows=20&wt=json";
// org.jsoup.nodes.Document doc = Jsoup.connect(url).ignoreContentType(true).timeout(30000).get();
// String elem = doc.body().text();
// JSONObject response = JSONObject.parseObject(elem).getJSONObject("response");
// if (response.containsKey("docs") && response.getJSONArray("docs").size() > 0) {
// JSONObject docJson = response.getJSONArray("docs").getJSONObject(0);
// Element groupId = new DOMElement("groupId");
// Element artifactId = new DOMElement("artifactId");
// Element version = new DOMElement("version");
// groupId.addText(docJson.getString("g"));
// artifactId.addText(docJson.getString("a"));
// version.addText(docJson.getString("v"));
// dependency.add(groupId);
// dependency.add(artifactId);
// dependency.add(version);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return dependency;
// }
// 复制文件
public static void sharpFile(File sourceFile)
throws IOException {
try {
String targetpath = correctlibdir + sourceFile.getName();
File newFile = new File(targetpath);
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(newFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
//关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
System.gc();
boolean delete = sourceFile.delete();
System.out.println("delete-------"+delete);
} catch (Exception E) {
E.printStackTrace();
}
}
public static String getSha1ByFile(File file) throws IOException, NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[1024];
int read;
while ((read = fis.read(data)) != -1) {
sha1.update(data, 0, read);
}
byte[] hashBytes = sha1.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
}
fis.close();
return sb.toString();
}
/**
* 内网专用
* @param file
* @return
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static Element getDependices2(File file) throws NoSuchAlgorithmException, IOException {
Element dependency = null;
String sha1 = getSha1ByFile(file);
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://192.168.29.50:8081/service/extdirect");
String body = "{\"action\":\"coreui_Search\",\"method\":\"read\",\"data\":[{\"page\":1,\"start\":0,\"limit\":300,\"filter\":[{\"property\":\"assets.attributes.checksum.sha1\",\"value\":\""+sha1+"\"}]}],\"type\":\"rpc\",\"tid\":77}";
StringEntity s = new StringEntity(body);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());
JSONObject ob = JSON.parseObject(result);
System.out.println(result);
if (ob!=null&&ob.getJSONObject("result")!=null&&(ob = ob.getJSONObject("result")).containsKey("data") && ob.getJSONArray("data").size() > 0) {
JSONObject docJson = ob.getJSONArray("data").getJSONObject(0);
Element groupId = new DOMElement("groupId");
Element artifactId = new DOMElement("artifactId");
Element version = new DOMElement("version");
groupId.addText(docJson.getString("group"));
artifactId.addText(docJson.getString("name"));
version.addText(docJson.getString("version"));
dependency = new DOMElement("dependency");
dependency.add(groupId);
dependency.add(artifactId);
dependency.add(version);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dependency;
}
/**
* jar内找pom
*/
public static Element getDependices3(File file) {
Element dependency = new DOMElement("dependency");
StringBuilder stringBuilder = new StringBuilder(10240);
String groupId = null;
String artifactId = null;
String version = null;
if (!file.exists()) return dependency;
try (ZipFile zipFile = new ZipFile(file)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getName().endsWith("pom.xml")) {
boolean hasParent = false;
boolean enterParent = false;
try (Scanner scanner = new Scanner(zipFile.getInputStream(entry), "US-ASCII")) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("parent")) {
enterParent = !enterParent;
hasParent = true;
} else if (line.contains("<groupId>")) {
groupId = line;
} else if (!enterParent && line.contains("<artifactId>")) {
artifactId = line;
} else if (line.contains("<version>")) {
version = line;
} else if (!hasParent && groupId != null && artifactId != null && version != null) {
break;
} else if (line.contains("<dependencies>") || line.contains("<dependency>") || line.contains("<properties>") || line.contains("<profiles>") || line.contains("<plugins>")) {
break;
}
}
if (groupId != null && artifactId != null && version != null) {
Element groupIde = new DOMElement("groupId");
Element artifactIde = new DOMElement("artifactId");
Element versione = new DOMElement("version");
groupIde.addText(groupId.trim().replaceAll("<","<").replaceAll(">",">").replaceAll("<groupId>", "").replaceAll("</groupId>", ""));
artifactIde.addText(artifactId.trim().replaceAll("<","<").replaceAll(">",">").replaceAll("<artifactId>", "").replaceAll("</artifactId>", ""));
versione.addText(version.trim().replaceAll("<","<").replaceAll(">",">").replaceAll("<version>", "").replaceAll("</version>", ""));
dependency.add(groupIde);
dependency.add(artifactIde);
dependency.add(versione);
} else {
stringBuilder.append("pom.xml解析异常,当前jar文件是" + file.getCanonicalPath() + ",解析失败的文件是" + entry.getName());
}
}
}
}
} catch (IOException ex) {
System.out.println(ex.toString());
}
return dependency;
}
}