读取jar文件的sha1码,请求maven官方的solrsearch接口查询该jar文件所对应的maven坐标信息

时间:2022-06-15 11:56:10

版权声明:本文为博主原创文章,未经博主允许不得转载。

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.io.IOUtils; import java.io.*;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map; /**
* 读取jar文件的sha1码,请求maven官方的solrsearch接口查询该jar文件所对应的maven坐标信息
* Created by Nihaorz on 2017/4/20.
*/
public class MakeMavenInfo { public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
long start = System.currentTimeMillis();
File dir = new File("C:\\Users\\Administrator\\Desktop\\jars");
for (File jar : dir.listFiles()) {
String sha1 = getSha1ByFile(jar);
Map<String, String> map = getMavenInfoBySha1(jar, sha1);
System.out.println(map);
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end-start)/1000 + "秒");
} /**
* 根据jar包输入流获取该文件的sha1码
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
*/
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));
}
return sb.toString();
} /**
* 根据sha1码请求接口拿到该jar包对应的maven坐标信息
* @param jar
* @param sha1
* @return
*/
public static Map<String, String> getMavenInfoBySha1(File jar, String sha1){
Map<String, String> map = new HashMap<String, String>();
String url = "http://search.maven.org/solrsearch/select?q=1:\"";
StringBuilder sb = new StringBuilder();
sb.append(url).append(sha1).append("\"&rows=20&wt=json");
map.put("jarName", jar.getName());
try {
String jsonStr = IOUtils.toString(new URL(sb.toString()));
JsonObject json = new JsonParser().parse(jsonStr).getAsJsonObject();
JsonObject obj = json.getAsJsonObject("response").getAsJsonArray("docs").get(0).getAsJsonObject();
map.put("groupId", obj.get("g").getAsString());
map.put("artifactId", obj.get("a").getAsString());
map.put("version", obj.get("v").getAsString());
map.put("packaging", obj.get("p").getAsString());
map.put("result", "true");
} catch (Exception e) {
e.printStackTrace();
map.put("result", "false");
System.out.println(sb);
}
return map;
} }

参考:  http://www.sha1-online.com/sha1-java/

     http://search.maven.org/#api