【ant】Apache ant 开发

Apache ant 开发

Ant是Apache软件基金会JAKARTA目录中的一个子项目,它有以下的优点。跨平台性。Ant是纯Java语言编写的,所以具有很好的跨平台性。操作简单。Ant是由一个内置任务和可选任务组成的。Ant运行时需要一个XML文件(构建文件)。 Ant通过调用target树,就可以执行各种task。每个task实现了特定接口对象。由于Ant构建文件 是XML格式的文件,所以很容易维护和书写,而且结构很清晰。Ant可以集成到开发环境中。由于Ant的跨平台性和操作简单的特点,它很容易集成到一些开发环 境中去。

ANT 开发工具

推荐使用 Visual Studio Code 开发工具,里边有一款为了优化ant开发而开发的插件 --Ant Editor

使用方法如下

1、下载ANT,安装环境变量

配置环境变量,可以在百度搜到,类似java环境变量,本机为linux,只介绍linux的配置方式

  1. 首先 vi /etc/profile

  2. 在末尾添加

    export ANT_HOME= 自己的地址/ant
    
    export CLASSPATH=.:${ANT_HOME}/lib
    
    export PATH=${ANT_HOME}/bin:$PATH
    
  3. source /etc/profile

  4. 在控制台输入 ant -version,出现版本号即为成功

2、安装以及使用ant Editor
  1. 在右侧点击扩展
    在这里插入图片描述

  2. 输入ant Editor,搜索并下载,显示如下图一样即安装完成
    在这里插入图片描述

  3. 配置变量,配置执行命令 ant -lib xxxxxx -f ,额外lib包

在这里插入图片描述

ANT执行

本地调试开发,使用插件直接点击执行即可
在这里插入图片描述

若在程序调试开发,则按照相关文档操作

自定义ant标签

本文开发使用maven工程

1、引用ant

在pom文件引用ant依赖,本文使用的是1.9版本

<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.9.15</version>
</dependency>
2、继承org.apache.tools.ant.Task

继承 org.apache.tools.ant.Task,并重写 execute方法,主要重写 execute方法,若有其他需求,可参照下边常用方法

相关属性:

  • execute():ant标签执行都会调用此方法,如果任务被多次调用,则此方法可能会被多次调用。

  • 标签入参:封装属性,使用get/set方法即可完成传参

  • 标签出参:调用父类方法getProject().setUserProperty(key,value);或者getProject().setProperty(key,value); 两者的区别 project.setUserProperty 优先级比较高,如果用 setUserProperty 定义的值,setPropert是无法覆盖的

  • init():重写此方法,使得标签初始化,默认不操作

    例子:

    import org.apache.tools.ant.BuildException;
    import org.apache.tools.ant.Task;
    
    /**
     * @author: ccyy
     * @create: 2022-02-08
     * @description: ant 自定义标签 demo
     **/
    public class AntDemo extends Task {
    
        private String name;
    
        private String doSome;
    
        @Override
        public void execute() throws BuildException {
            String rst = "Hello world !" +name +" , " +doSome;
            getProject().setUserProperty(name,rst);
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDoSome() {
            return doSome;
        }
    
        public void setDoSome(String doSome) {
            this.doSome = doSome;
        }
    }
    
3、打包工程

​ 使用maven打包完工程后,放入lib

4、ant引用

标签引用,使用taskdef引用自定义标签

<!-- name为自定义标签名字,classname为标签类路径 -->
<taskdef name="antdemo" classname="xxx.xxx.xxx.AntDemo" />

引用完标签后即可使用标签

		<!-- 引用标签,传参 -->
		<antdemo name="nantian" value="ant demo"/>
		<!-- 输出结果 -->
		<echo message="rst : ${nantian}" />

完整脚本

<project name="ccyyTest" default="default" basedir="..">
	<taskdef name="antdemo" classname="xxx.xxx.xxx.AntDemo" />
	
	<target name="default">
		<!-- 引用标签,传参 -->
		<antdemo name="nantian" value="ant demo"/>
		<!-- 输出结果 -->
		<echo message="rst : ${nantian}" />
	</target>
</project>

ANT进阶

1、标签嵌套调用标签

实现接口org.apache.tools.ant.TaskContainer,并实现addTask()方法

public class AntDemo extends Task implements TaskContainer {
	private Vector<Task> nestedTasks = new Vector<Task>();
	@Override
    public void addTask(Task arg0) {
    	nestedTasks.add(arg0);
    }
    @Override
    public void execute() {
        doTask();
    }
    public void doTask() {
		Iterator<Task> i = nestedTasks.iterator();
		while (i.hasNext()) {
			((Task) i.next()).perform();
		}
	}
 }
2、标签嵌套标签传值

参照 Apache ant 源码 getMother 标签

1、创建静态匿名类

2、封装属性,创建get/set方法

3、使用list接收

/*
 * Copyright (c) 2001-2006 Ant-Contrib project.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.sf.antcontrib.net.httpclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.FileUtils;

public class PostMethodTask extends AbstractMethodTask {

	private List parts = new ArrayList();
	private boolean multipart;
	private transient FileInputStream stream;

	public static class FilePartType {
		private String name;
		private File path;
		private String contentType = FilePart.DEFAULT_CONTENT_TYPE;
		private String charSet = FilePart.DEFAULT_CHARSET;

		public File getPath() {
			return path;
		}

		public void setPath(File path) {
			this.path = path;
		}

		public String getContentType() {
			return contentType;
		}

		public void setContentType(String contentType) {
			this.contentType = contentType;
		}

		public String getCharSet() {
			return charSet;
		}

		public void setCharSet(String charSet) {
			this.charSet = charSet;
		}

		/**
		 * @return the name
		 */
		public String getName() {
			return name;
		}

		/**
		 * @param name
		 *            the name to set
		 */
		public void setName(String name) {
			this.name = name;
		}
	}

	public static class TextPartType {
		private String name = "";
		private String value = "";
		private String charSet = StringPart.DEFAULT_CHARSET;
		private String contentType = StringPart.DEFAULT_CONTENT_TYPE;

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getCharSet() {
			return charSet;
		}

		public void setCharSet(String charSet) {
			this.charSet = charSet;
		}

		public String getContentType() {
			return contentType;
		}

		public void setContentType(String contentType) {
			this.contentType = contentType;
		}

		public void setText(String text) {
			this.value = text;
		}
	}

	public void addConfiguredFile(FilePartType file) {
		this.parts.add(file);
	}

	public void setMultipart(boolean multipart) {
		this.multipart = multipart;
	}

	public void addConfiguredText(TextPartType text) {
		this.parts.add(text);
	}

	public void setParameters(File parameters) {
		PostMethod post = getPostMethod();
		Properties p = new Properties();
		Iterator it = p.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			post.addParameter(entry.getKey().toString(), entry.getValue().toString());
		}
	}

	protected HttpMethodBase createNewMethod() {
		return new PostMethod();
	}

	private PostMethod getPostMethod() {
		return ((PostMethod) createMethodIfNecessary());
	}

	public void addConfiguredParameter(NameValuePair pair) {
		getPostMethod().setParameter(pair.getName(), pair.getValue());
	}

	public void setContentChunked(boolean contentChunked) {
		getPostMethod().setContentChunked(contentChunked);
	}

	protected void configureMethod(HttpMethodBase method) {
		EntityEnclosingMethod post = (EntityEnclosingMethod) method;

		if (parts.size() == 1 && !multipart) {
			Object part = parts.get(0);
			if (part instanceof FilePartType) {
				FilePartType filePart = (FilePartType) part;
				try {
					stream = new FileInputStream(filePart.getPath().getAbsolutePath());
					post.setRequestEntity(new InputStreamRequestEntity(stream, filePart.getPath().length(),
							filePart.getContentType()));
					if (StringUtils.isNotBlank(filePart.getName())) {
						((FilePartType) part).setName(filePart.getName());
					}
				} catch (IOException e) {
					throw new BuildException(e);
				}
			} else if (part instanceof TextPartType) {
				TextPartType textPart = (TextPartType) part;
				try {
					post.setRequestEntity(new StringRequestEntity(textPart.getValue(), textPart.getContentType(),
							textPart.getCharSet()));
				} catch (UnsupportedEncodingException e) {
					throw new BuildException(e);
				}
			}
		} else if (!parts.isEmpty()) {
			Part partArray[] = new Part[parts.size()];
			for (int i = 0; i < parts.size(); i++) {
				Object part = parts.get(i);
				if (part instanceof FilePartType) {
					FilePartType filePart = (FilePartType) part;
					try {
						String name = filePart.getPath().getName();
						if (StringUtils.isNotBlank(filePart.getName())) {
							name = filePart.getName();
						}
						partArray[i] = new CustomFilePart(name, filePart.getPath().getName(), filePart.getPath(),
								filePart.getContentType(), filePart.getCharSet());
					} catch (FileNotFoundException e) {
						throw new BuildException(e);
					}
				} else if (part instanceof TextPartType) {
					TextPartType textPart = (TextPartType) part;
					partArray[i] = new StringPart(textPart.getName(), textPart.getValue(), textPart.getCharSet());
					((StringPart) partArray[i]).setContentType(textPart.getContentType());
				}
			}
			MultipartRequestEntity entity = new MultipartRequestEntity(partArray, post.getParams());
			post.setRequestEntity(entity);
		}
	}

	protected void cleanupResources(HttpMethodBase method) {
		FileUtils.close(stream);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值