package lucne.test; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test; public class MavenPomUtil { //待索引文件路径
private static String indexFilePath;
//索引存储路径
public static String dirpath;
private static List<File> files = new ArrayList<File>(); static{
try {
indexFilePath="F:\\Repositorys\\MavenLib";
dirpath=new File("").getCanonicalPath()+"\\Index\\Directory";
} catch (IOException e) {
e.printStackTrace();
};
} @Test
public void search() throws IOException{
Map<String, Boolean> errorMap=parserJarPomResult("F:\\workce\\eclispe\\newplaterom\\pom.xml");
System.out.println(errorMap);
} @Test
public void initCreateIndex(){
checkFile(new File(indexFilePath));
createMavenLibIndex(files);
} /**
* 返回结果
* */
public Map<String, Boolean> parserJarPomResult(String pompath){
return parserJarPomError(parserXmlFile(pompath));
} /**
* 解析pom文件后,将结果集验证是否有误差
* */
private Map<String, Boolean> parserJarPomError(List<String> jars){
Map<String, Boolean> errorMap = new HashMap<String, Boolean>();
if(jars!=null&&!jars.isEmpty()){
for(String jarname:jars){
boolean bo = searchMavenLibPathBoolean(jarname);
if(!bo){
errorMap.put(jarname, bo);
}
}
}
return errorMap;
} /**
* 解析pom文件
* */
@SuppressWarnings("unchecked")
private List<String> parserXmlFile(String pomFilePath){
File pom = new File(pomFilePath);
List<String> jarList = new ArrayList<String>();
try {
SAXReader xmlreader = new SAXReader();
org.dom4j.Document doc = xmlreader.read(pom);
Element el = doc.getRootElement();
Element dependencies = el.element("dependencies");
Map<String, String> propertiesMap = null;
Element properties = el.element("properties");
if(properties!=null){
propertiesMap = new HashMap<String, String>();
Iterator<Element> propertiesIt = properties.elementIterator();
while(propertiesIt.hasNext()){
Element propertieChildren = propertiesIt.next();
String name = propertieChildren.getName();
String text = propertieChildren.getText();
propertiesMap.put("\\$\\{"+name+"\\}", text);
}
}
Iterator<Element> dependenciesIt = dependencies.elementIterator();
while(dependenciesIt.hasNext()){
Element dependency=dependenciesIt.next();
Element artifactId=dependency.element("artifactId");
Element version=dependency.element("version");
Element scope=dependency.element("scope");
Element classifier=dependency.element("classifier");
String artifactIdValue = artifactId.getText();
String versionValue = version.getText();
String jarFileName="";
if(scope==null||!scope.getText().equals("system")){
jarFileName=artifactIdValue.concat("-").concat(versionValue);
if(classifier!=null){
String classifiervalue=classifier.getText();
jarFileName=jarFileName.concat("-").concat(classifiervalue);
}
jarFileName=jarFileName.concat(".jar");
}else if(scope.getText().equals("system")){
Element systemPath=dependency.element("systemPath");
String systemPathValue=systemPath.getText();
int lastindex=systemPathValue.lastIndexOf("/");
jarFileName=systemPathValue.substring(lastindex+1, systemPathValue.length());
}
if(propertiesMap!=null){
for(String key:propertiesMap.keySet()){
jarFileName=jarFileName.replaceAll(key, propertiesMap.get(key));
}
}
jarList.add(jarFileName);
}
} catch (DocumentException e) {
e.printStackTrace();
}
return jarList;
} /**
* 查询索引是否存在
* @return boolean
* */
public static boolean searchMavenLibPathBoolean(String jarFilenName){
boolean flag=false;
try {
Directory dir = FSDirectory.open(new File(MavenPomUtil.dirpath));
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
/* QueryParser parser = new QueryParser(Version.LUCENE_40, "filename", new StandardAnalyzer(Version.LUCENE_40));
Query query = parser.parse(jarFilenName);*/
Term term = new Term("filename",jarFilenName);
TermQuery query = new TermQuery(term);
TopDocs docs = searcher.search(query, 2);
if(docs.totalHits>0){
flag=true;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
} /**
* 查询jar存在路径
* @return Map
* */
public static Map<String, List<String>> searchMavenLibPath(String jarFilenName){
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> pathlist = new ArrayList<String>();
try {
Directory dir = FSDirectory.open(new File(MavenPomUtil.dirpath));
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser(Version.LUCENE_40, "filename", new StandardAnalyzer(Version.LUCENE_40));
Query query = parser.parse(jarFilenName);
TopDocs docs = searcher.search(query, 2);
for(ScoreDoc scoredoc:docs.scoreDocs){
Document doc = searcher.doc(scoredoc.doc);
String filepath = doc.get("filepath");
pathlist.add(filepath);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
map.put(jarFilenName, pathlist);
return map;
} /**
* 创建索引
* */
private void createMavenLibIndex(List<File> files){
try {
Directory dir = FSDirectory.open(new File(dirpath));
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, new StandardAnalyzer(Version.LUCENE_40));
config.setOpenMode(OpenMode.CREATE);
IndexWriter writer = new IndexWriter(dir, config);
for(File file:files){
if(file.isFile()){
Document doc = new Document();
doc.add(new StringField("filename", file.getName(), Store.YES));
doc.add(new StringField("filepath",file.getPath(),Store.YES));
writer.addDocument(doc);
}
}
writer.forceMerge(1);//优化压缩段,大规模添加数据的时候建议,少使用本方法,会影响性能
writer.commit();//提交数据
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 查询待索引文件
* */
private void checkFile(File checkFile){// 查看目录下的所有文件
if (checkFile.exists()) {
if (checkFile.isDirectory()) {
File[] f = checkFile.listFiles();// 查看目录的文件
for (int i = 0; i < f.length; i++) {
checkFile(f[i]);
}
} else {
String fileName=checkFile.getName();
if(fileName.endsWith(".jar")){
files.add(checkFile);
}
}
}
} }