Analog maven-dependencies plug-in implementation

Role maven-dependencies plugin jar package is extracted from the local maven repository, into a folder below. This feature is actually very simple.
I work in a bank, company computers are not even outside the network, it is not possible to download by maven jar package. But the development on company computers, I want to use maven to compile, package and so on. If you copy up maven repository on my computer, too, I want to copy the jar package those items actually used only in accordance with pom.xml, forming a maven repository.
First, you need the following configuration

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

Where targetDir indicates a copy from your local maven repository, pom represents the path of pom.xml, simple indicate whether to keep the directory structure of maven. If simple = true, the directory structure is not preserved, only copy jar packets; if simple = false, then follow the directory format maven repository.
The following code copy information from a local warehouse in maven pom.xml according to a new folder

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);
}
}

Rely jar package as follows:

<?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>

Guess you like

Origin www.cnblogs.com/weiyinfu/p/11105462.html
Recommended