maven-dependencies插件的模拟实现

maven-dependencies插件的作用就是从本地的maven仓库中提取jar包,放到某个文件夹下面。这个功能其实是很简单的。
我在一家银行工作时,公司电脑都无法连外网,所以无法通过maven下载jar包。但是在公司电脑上开发时,我又想使用maven进行编译、打包等操作。如果把我电脑上的maven仓库复制上去,太大,我想根据pom.xml只复制那些项目实际用到的jar包,形成maven仓库。
首先需要进行如下配置

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仓库中复制信息到一个新的文件夹

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包如下所示:

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

转载于:https://www.cnblogs.com/weiyinfu/p/11105462.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Maven使用Tomcat8-maven-plugin插件可以将Web应用程序部署到Tomcat服务器上。以下是使用Tomcat8-maven-plugin插件的步骤: 1. 在pom.xml文件中添加以下插件配置: ``` <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat8-maven-plugin</artifactId> <version>3.0-r1756463</version> <configuration> <url>http://localhost:8080/manager/text</url> <username>admin</username> <password>admin</password> <path>/myapp</path> </configuration> </plugin> </plugins> </build> ``` 2. 配置Tomcat服务器的管理用户和密码,以便插件可以将应用程序部署到服务器上。在Tomcat的conf/tomcat-users.xml文件中添加以下内容: ``` <role rolename="manager-gui"/> <user username="admin" password="admin" roles="manager-gui"/> ``` 3. 在命令行中执行以下命令将应用程序部署到Tomcat服务器上: ``` mvn tomcat8:deploy ``` 4. 如果需要重新部署应用程序,可以执行以下命令: ``` mvn tomcat8:redeploy ``` 5. 如果需要从Tomcat服务器中卸载应用程序,可以执行以下命令: ``` mvn tomcat8:undeploy ``` 以上就是使用Tomcat8-maven-plugin插件的基本步骤。需要注意的是,插件的版本号和Tomcat服务器的版本号需要匹配,否则可能会出现兼容性问题。 ### 回答2: Maven是一种基于Java平台的自动化构建工具,可以管理项目的依赖关系、编译、测试以及部署。Tomcat8-maven-plugin则是Maven插件的一种,用于将Maven项目打包成Web应用并且在Tomcat容器中运行。 Tomcat8-maven-plugin插件的使用方法如下: 1.在Maven项目的pom.xml文件中,添加如下插件配置: ``` <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat8-maven-plugin</artifactId> <version>X.X.X</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>TomcatServer</server> <path>/hello</path> </configuration> </plugin> </plugins> </build> ``` 其中,groupId和artifactId表示Tomcat8-maven-plugin插件的组ID和插件ID,version表示插件的版本号。configuration标签中的三个元素分别表示Tomcat管理页面的URL、Maven的服务器配置、Web应用在Tomcat容器中的访问路径。 2.运行Maven命令,将项目打包成war包: ``` mvn package ``` 3.将war包上传到Tomcat服务器,并在Tomcat管理页面上部署Web应用。 4.在Maven项目的根目录下,运行如下命令启动Tomcat容器: ``` mvn tomcat8:run ``` 5.在浏览器中输入http://localhost:8080/hello,即可访问Web应用。 总的来说,使用Tomcat8-maven-plugin插件能够简化项目的部署和运行,并且可以通过配置实现一些定制化的需求,适合于中小型Java Web项目的开发和维护。 ### 回答3: Maven是一个Java项目管理和构建工具,能够自动下载所需的依赖包、自动编译、测试和打包等,方便开发人员进行软件项目的快速开发。 Tomcat8-maven-plugin是一个Maven插件,它可用于将Web应用程序部署到Tomcat容器中。它能够快捷地将Web应用程序打包并部署到Tomcat 8服务器中,无需手动将WAR文件复制到Tomcat的webapps目录中。 它提供了许多配置选项,例如上下文路径、端口等参数,可以根据需要定制化自己的应用程序配置,使得部署更加灵活和方便。 使用Tomcat8-maven-plugin插件的步骤如下: 1. 在pom.xml文件中添加Tomcat8-maven-plugin配置 ```xml <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat8-maven-plugin</artifactId> <version>3.0-r1756466</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>tomcat8</server> <path>/myApp</path> </configuration> </plugin> </plugins> </build> ``` 2. 运行 Maven Build ``` mvn clean install ``` 以上是Tomcat8-maven-plugin插件的基本配置和使用方法,通过它能够简单高效地实现Web应用程序的部署和管理,方便开发人员进行项目开发和测试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值