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>

maven-dependencies插件的模拟实现的更多相关文章

  1. maven常用插件pom配置

    一.问题描述: 部署一个maven打包项目时,jar包,依赖lib包全部手动上传至服务器,然后用maven部署报错:Exception in thread "main" java. ...

  2. 自己动手编写Maven的插件

    Maven的插件机制是完全依赖Maven的生命周期的,因此理解生命周期至关重要.本文参考官方文档后使用archetype创建,手动创建太麻烦. 创建创建项目 选择maven-archetype-moj ...

  3. 13 Maven 编写插件

    Maven 编写插件 Maven 的任何行为都是由插件完成的,包括项目的清理.绵编译.测试以及打包等操作都有其对应的 Maven 插件.每个插件拥有一个或者多个目标,用户可以直接从命令行运行这些插件目 ...

  4. maven项目在myeclipse中不出现Maven Dependencies 和maven标识的解决方法

    这种情况通常出现在 我们新加载了一个 maven的项目,但是myeclipse没识别到. 或者说 我们把该项目修改成了maven项目--------也就是说该项目 有了pom.xml 但是还没有mav ...

  5. (转)淘淘商城系列——使用maven tomcat插件启动聚合工程

    http://blog.csdn.net/yerenyuan_pku/article/details/72672389 上文我们一起学习了如何使用maven tomcat插件来启动web工程,本文我们 ...

  6. (转)淘淘商城系列——使用maven tomcat插件启动web工程

    http://blog.csdn.net/yerenyuan_pku/article/details/72672138 上文我们一起学习了怎样搭建maven工程,这篇文章我就来教大家一起学习怎样用to ...

  7. 【maven】插件和依赖管理

    1.插件管理 定义 pluginManagement 用来做插件管理的.它是表示插件声明,即你在项目中的pluginManagement下声明了插件,Maven不会加载该插件,pluginManage ...

  8. 【01】Maven依赖插件之maven-dependency-plugin

    一.插件目标(goal) 1.analyze:分析项目依赖,确定哪些是已使用已声明的,哪些是已使用未声明的,哪些是未使用已声明的 2.analyze-dep-mgt:分析项目依赖,列出已解析的依赖项与 ...

  9. Maven 的插件和生命周期的绑定

    一.Maven 的生命周期 Maven 的生命周期是对所有的构建过程进行抽象和统一.Maven 的生命周期是抽象的,这意味着生命周期本身不做任何实际的工作,生命周期只是定义了一系列的阶段,并确定这些阶 ...

  10. 【转】Maven Jetty 插件的问题(css/js等目录死锁)的解决

    Maven Jetty 插件的问题(css/js等目录死锁,不能自动刷新)的解决:   1. 打开下面的目录:C:\Users\用户名\.m2\repository\org\eclipse\jetty ...

随机推荐

  1. 设置view的layer属性方法

    1.需要导入QuartzCore.framewoork框架到工程2.在文件中导入#import 3.设置 必须导入的空间 #import<QuartzCore/QuartzCore.h> ...

  2. matlab C程序

    通过把耗时长的函数用c语言实现,并编译成mex函数可以加快执行速度 Matlab本身是不带c语言的编译器的,所以要求你的机器上已经安装有VC,BC或Watcom C中的一种 注:在Matlab里,矩阵 ...

  3. 如何使用 CODING 进行瀑布流式研发

    你好,欢迎使用CODING!这份最佳实践将帮助你通过 CODING 更好地实践瀑布流式开发流程. 什么是瀑布流式研发 1970 年温斯顿·罗伊斯(Winston Royce)提出了著名的"瀑 ...

  4. [PHP] 内部接口简单加密验证方式

    1. 当有内部系统之间进行调用的时候,也需要简单的进行一下调用方的验证,一种简单的内部接口加密验证方式.此加密方式需要三个参数,分别是api地址,pin码,entry标识,其中pin和entry是接口 ...

  5. eclipse C++ 配置自动提示

    转:http://www.cnblogs.com/myitm/archive/2010/12/17/1909194.html 定位到:Windows→Preferences→Java→Editor→C ...

  6. WebUI自动化测试框架

    基于Python+Selenium+Unittest+Ddt+HTMLReport 框架结构: Business:业务相关公共模块,如登录 Common:业务无关公共模块,如读取文件 PageObje ...

  7. 联邦学习 Federated Learning 相关资料整理

    本文链接:https://blog.csdn.net/Sinsa110/article/details/90697728代码微众银行+杨强教授团队的联邦学习FATE框架代码:https://githu ...

  8. 利用java程序构造mysql测试数据

    package com.baidu.mysql;import java.sql.*; public class MysqlJdbc { /** * @param args */ public stat ...

  9. 古来月小队 Alpha冲刺阶段博客目录

    一.Scrum Meeting 第六周: 链接:https://www.cnblogs.com/ouc-xxxxxx/p/11789325.html 任务:搭建安卓编程环境,学习安卓前端知识 第七周: ...

  10. 数据库连接池 DBUtils:

    import pymysqlfrom DBUtils.PooledDB import PooledDB, SharedDBConnectionPOOL = PooledDB ( creator=pym ...