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. postgreSQL数据库的初探

    kali是黑客的强大武器,还有一个也是哦——Metasploit postgreSQL数据库是Metasploit的默认数据库哦! 启动postgresql: service postgresql s ...

  2. Element-ui中为上传组件添加表单校验

    vue所依赖的Element的UI库在使用其中的upload组件时,可能很大几率会遇到这个题,需要给upload组件添加表单校验 大家这里直接看代码就可以 <el-form-item class ...

  3. 图Lasso求逆协方差矩阵(Graphical Lasso for inverse covariance matrix)

    图Lasso求逆协方差矩阵(Graphical Lasso for inverse covariance matrix) 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/ka ...

  4. bcftools

    beftools非常复杂,大概有20个命令,每个命令下面还有N多个参数 annotate .. edit VCF files, add or remove annotations call .. SN ...

  5. FineUIPro v6.0.1 小版本更新!

    这次修正了 v6.0.0版本的几个问题,建议所有用户升级到此版本: +修正调用F.addMainTab时可能出现JS错误的问题(34484135,1450561644).    -仅在未调用F.ini ...

  6. LeetCode 155:最小栈 Min Stack

    LeetCode 155:最小栈 Min Stack 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈. push(x) -- 将元素 x 推入栈中. pop() -- ...

  7. 转载-Qualcomm MSM8953启动流程:PBL-SBL1-(bootloader)LK-Android

    文章转载链接: https://blog.csdn.net/RadianceBlau/article/details/73229005 对于嵌入式工程师了解芯片启动过程是十分有必要的,在分析.调试各种 ...

  8. iOS性能优化-数组、字典便利时间复杂

    上图是几种时间复杂度的关系,性能优化一定程度上是为了降低程序执行效率减低时间复杂度. 如下是几种时间复杂度的实例: O(1) return array[index] == value; 复制代码 O( ...

  9. [ThinkPHP]报错:Fatal error: Namespace declaration statement has to be the very first statement or after any declare call in the script in E:\wamp\www\jdlh\application\index\controller\Index.php on line

    错误提示说命名空间声明语句必须是第一句,可我看就是第一句没毛病呀,这是为啥呢,后面发现<?php 前面有个空格,删掉就正常了 去掉空格之后页面能正常显示

  10. C# 中的浅拷贝与深拷贝

    Ø  简介 在 C# 中分为两种数据类型,值类型和引用类型.我们知道,值类型之间赋值是直接将值赋值给另一个变量,两个变量值的改变都互不影响:而引用类型赋值则是将引用赋值给另一个变量,其中一个变量中的成 ...