maven-dependencies插件的模擬實現

maven-dependencies插件的做用就是從本地的maven倉庫中提取jar包,放到某個文件夾下面。這個功能實際上是很簡單的。
我在一家銀行工做時,公司電腦都沒法連外網,因此沒法經過maven下載jar包。可是在公司電腦上開發時,我又想使用maven進行編譯、打包等操做。若是把我電腦上的maven倉庫複製上去,太大,我想根據pom.xml只複製那些項目實際用到的jar包,造成maven倉庫。
首先須要進行以下配置java

targetDir=jars
#always use / ranther than \\
pom=C:/Users/weidiao/Desktop/pabqa/pom.xml
m2=C:/Users/weidiao/.m2
#should put all jars together ?
simple=true

targetDir表示從本地maven倉庫中複製到哪裏去,pom表示pom.xml的路徑,simple表示是否保留maven的目錄結構。若是simple=true,則不保留目錄結構,只複製jar包;若是simple=false,則遵循maven倉庫的目錄格式。
下面的代碼根據pom.xml從本地的maven倉庫中複製信息到一個新的文件夾node

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 給定本地maven倉庫
 * pom.xml文件
 */
public class MavenJarExtractor {
static class Dependency {
    String artifactId;
    String groupId;
    String version;

    public String getArtifactId() {
        return artifactId;
    }

    public void setArtifactId(String artifactId) {
        this.artifactId = artifactId;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public Path getPath() {
        return Paths.get(getGroupId().replace('.', '/'))
                .resolve(Paths.get(getArtifactId()))
                .resolve(getVersion());
    }

    public String getFileName() {
        return getArtifactId() + "-" + getVersion();
    }
}

static class CopyTask {
    Path src;
    Path des;

    public Path getSrc() {
        return src;
    }

    public void setSrc(Path src) {
        this.src = src;
    }

    public Path getDes() {
        return des;
    }

    public void setDes(Path des) {
        this.des = des;
    }
}

String reFirst(String pattern, String s, int group) {
    Pattern p = Pattern.compile(pattern);
    Matcher matcher = p.matcher(s);
    boolean found = matcher.find();
    if (found) {
        return matcher.group(group);
    } else return null;
}

void createDir(Path p) throws IOException {
    p = p.toAbsolutePath();
    if (Files.notExists(p)) {
        if (Files.notExists(p.getParent()))
            createDir(p.getParent());
        Files.createDirectory(p);
    }
}

void copyFolder(Path src, Path des, boolean simple) {
    try {
        Files.list(src).forEach(x -> {
            if (simple && !x.getFileName().toString().endsWith(".jar"))
                return;
            try {
                Files.copy(x, des.resolve(x.getFileName()), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}


List<Dependency> parseDom(String pomPath) throws IOException {
    //解析pom=解析屬性+解析dependency
    Document dom = Jsoup.parse(Paths.get(pomPath).toFile(), "utf8");
    Element p = dom.selectFirst("properties");
    Map<String, String> properties = new HashMap<>();
    if (p != null) {
        Elements ps = p.children();
        for (Element i : ps) {
            properties.put(i.tagName(), i.text());
        }
    }
    List<Dependency> dependencyList = new ArrayList<>();
    for (Element dep : dom.select("dependency")) {
        Dependency dependency = new Dependency();
        dependencyList.add(dependency);
        dependency.setArtifactId(dep.getElementsByTag("artifactId").text());
        dependency.setGroupId(dep.getElementsByTag("groupId").text());
        dependency.setVersion(dep.getElementsByTag("version").text());
        if (dependency.getVersion().matches("\\$\\{.+\\}")) {
            String version = reFirst("\\$\\{(.+)\\}", dependency.getVersion(), 1);
            dependency.setVersion(properties.get(version));
        }
    }
    return dependencyList;
}

List<CopyTask> buildTask(List<Dependency> dependencyList, String m2, String targetDir, boolean simple) {
    //定義任務列表
    List<CopyTask> tasks = new ArrayList<>();
    for (Dependency i : dependencyList) {
        Path depDir = Paths.get(m2).resolve("repository").resolve(i.getPath());
        if (Files.notExists(depDir)) {
            throw new RuntimeException("沒有在 "+depDir+" 找到" + i.getGroupId() + " " + i.getArtifactId());
        }
        CopyTask task = new CopyTask();
        task.setSrc(depDir);
        if (simple) {
            task.setDes(Paths.get(targetDir));
        } else {
            task.setDes(Paths.get(targetDir).resolve("repository").resolve(i.getPath()));
        }
        tasks.add(task);
    }
    System.out.println(JSON.toJSONString(tasks, true));
    return tasks;
}

void executeTask(List<CopyTask> tasks, boolean simple) throws IOException {
    //執行任務
    for (CopyTask task : tasks) {
        if (Files.notExists(task.des)) {
            createDir(task.des);
        }
        copyFolder(task.getSrc(), task.getDes(), simple);
    }
    System.out.println("task over successfully");
}

MavenJarExtractor(String targetDir, String pom, String m2, boolean simple) throws IOException {
    List<Dependency> dependencies = parseDom(pom);
    List<CopyTask> tasks = buildTask(dependencies, m2, targetDir, simple);
    executeTask(tasks, simple);
}

public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
    //加載配置
    Properties config = new Properties();
    config.load(new InputStreamReader(new FileInputStream("mavenjar.properties")));
    String targetDir = config.getProperty("targetDir", "target");
    String m2 = config.getProperty("m2", Paths.get(System.getProperty("user.home")).resolve(".m2").toString());
    String pomPath = config.getProperty("pom");//"C:\\Users\\weidiao\\Desktop\\pabqa\\pom.xml";
    boolean simple = Boolean.parseBoolean(config.getProperty("simple"));
    MavenJarExtractor extractor = new MavenJarExtractor(targetDir, pomPath, m2, simple);
}
}

須要依賴的jar包以下所示:apache

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>wyf</groupId>
    <artifactId>mavenjar</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>MavenJarExtractor</mainClass>
                        </manifest>
                    </archive>
                    <finalName>mavenjar</finalName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
相關文章
相關標籤/搜索