java操做Maven

      記錄瞬間java

 

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * @author
 * @version MavenUtil,
 */
public class MavenUtil {
    private static final Logger LOGGER           = LoggerFactory.getLogger(MavenUtil.class);
    private final String  WEB_INF_PATH           = "./";//MavenUtil.class.getClassLoader().getResource("../").getPath();
    private final String  COMPILE_PATH           = WEB_INF_PATH + "sourceCode/";
    private final String  EMBEDDED_MAVEN_PATH    = WEB_INF_PATH + "maven/";
    private final List<String> fileList = new ArrayList<String>();

    public void maven(String path) {
        List<String> getPoms = findPomFile(path);
        boolean flag = isJacoco(getPoms);
        List<String> fileList = getModuleList(getPoms);
        for (String pom: fileList) {
            ProcessBuilder pb = new ProcessBuilder();
            //構建命令
            if (System.getProperty("os.name").contains("Windows")) {
                if (flag) {
                    pb.command("cmd", "/c", "mvn", "clean", "test", "compile", "-f", pom);
                } else {
                    pb.command("cmd", "/c", "mvn", "-DskipTests=true", "clean", "compile", "-f",
                            pom);
                }

            } else if (System.getProperty("os.name").contains("Linux")) {
                if (flag) {
                    pb.command("mvn", "clean", "test", "compile", "-f", pom);
                } else {
                    pb.command("mvn", "-DskipTests=true", "clean", "compile", "-f", pom);
                }
            } else {
                LOGGER.info("Unknown System..." + System.getProperty("os.name"));
            }
            try {
                //執行命令
                Process process = pb.start();
                InputStream inputStream = process.getInputStream();
                byte[] buffer = new byte[1024];
                int readSize;
                while ((readSize = inputStream.read(buffer)) > 0) {
                    System.out.write(buffer, 0, readSize);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    /**
     * 查找全部pom文件
     * @param path
     * @return
     */
    private List<String> findPomFile(String path){
        File file = new File(path);

        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夾是空的!");
                return fileList;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory() && ! file2.getName().contains(".git")
                            && ! file2.getName().contains("src")) {
                        // 此處是文件夾
                        findPomFile(file2.getAbsolutePath());
                    } else {
                        if (file2.getName().contains("pom.xml")) {
                            fileList.add(file2.getAbsolutePath());
                            System.out.println("文件:" + file2.getAbsolutePath());
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        return fileList;
    }

    /**
     * 判斷是否存在多模塊,若是存在將會去除存在模塊的pom文件
     * @param fromPoms
     * @return
     */
    private List<String> getModuleList(List<String> fromPoms) {
        int count = fromPoms.size();
        for (String getPom: fromPoms) {
            final SAXReader reader = new SAXReader();
            Document document = null;
            try {
                document = reader.read(getPom);
                final List modules = document.getRootElement().element("modules").elements();
                if (modules != null) {
                    for (final Object module : modules) {
                        final String moduleName = ((Element) module).getText();
                        Iterator<String> iterator = fromPoms.iterator();
                        while (iterator.hasNext()) {
                            String pom = iterator.next();
                            if (pom.contains(moduleName)) {
                                iterator.remove();
                                count--;
                            }
                        }
                    }
                }
                if (count <= 1){
                    break;
                }
            } catch (final DocumentException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                System.out.print(getPom);
            }
        }
        return fromPoms;
    }

    /**
     * 讀取文件,判斷讀取的行中是否存在jacoco字符串
     * @param poms
     * @return
     */
    private boolean isJacoco(List<String> poms){
        boolean flag = false;
        BufferedReader reader = null;
        try {
            for (String getPom: poms){
                File pomFile = new File(getPom);
                reader = new BufferedReader(new FileReader(pomFile));
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    if (tempString.contains("org.jacoco")) {
                        flag = true;
                        break;
                    }
                }
                reader.close();
                if (flag) { break; }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return flag;
    }
    /**
     * 修改權限(這裏粗獷的修改成777,若有精細化的權限控制,本身調整一下)
     * 由於一些緣由,雖然線上默認的執行用戶是root,而且權限爲rwx,依然會報權限不足的錯誤
     * 若是有大神指導緣由請指點一二
     * @throws Exception
     */
    public void afterPropertiesSet() throws Exception {
        //修改maven目錄權限
        Process chmodMaven = new ProcessBuilder("chmod", "-R", "777", EMBEDDED_MAVEN_PATH).start();
        //等待完成
        chmodMaven.waitFor();
        LOGGER.info("修改權限完成:{}", EMBEDDED_MAVEN_PATH);

        //修改編譯目錄權限
        Process chmodCompile = new ProcessBuilder("chmod", "-R", "777", COMPILE_PATH).start();
        chmodCompile.waitFor();
        LOGGER.info("修改權限完成:{}", COMPILE_PATH);
    }

/**
* 遞歸查找文件
* @param baseDirName 查找的文件夾路徑
* @param targetFileName 須要查找的文件名
* @param fileList 查找到的文件集合
*/
public static void findFiles(String baseDirName, String targetFileName, List<File> fileList) {

File baseDir = new File(baseDirName); // 建立一個File對象
if (!baseDir.exists() || !baseDir.isDirectory()) { // 判斷目錄是否存在
System.out.println("文件查找失敗:" + baseDirName + "不是一個目錄!");
}
String tempName = null;

File tempFile;
File[] files = baseDir.listFiles();
if ( files.length == 0 ) {//該文件夾下沒有文件,爲空文件夾
System.out.println("爲空文件夾");
}
for (int i = 0; i < files.length; i++) {
tempFile = files[i];
if ( tempFile.isDirectory() ) {
findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);
} else if ( tempFile.isFile() ) {
tempName = tempFile.getName();
if ( tempName.equals(targetFileName) ) {
System.out.println(tempFile.getAbsoluteFile().toString());
fileList.add(tempFile.getAbsoluteFile());
}
}
}
}
}

 

主要實現了,對maven項目的編譯操做。區分了Windows和Linux兩個下同的不一樣操做。git

能夠考慮不去讀取pom文件,而是直接到target目錄下遍歷帶exec的文件,dom

這樣操做能夠直接定位到指定的模塊,使得覆蓋率信息圈定在摸一個具體模塊下。maven

 

 

===============================ui

相關文章
相關標籤/搜索