maven实例
1.simple weather项目介绍
maven权威指南中的例子,simple weather是一个基本的命令行驱动的应用程序,它接收邮政编码输入,然后从yahoo!weather RSS源取得数据,然后解析数据并把结果打印到标准输出
2.创建项目的基本框架
mvn archetype:create -DgroupId=org.sonatype.mavenbook.ch04 -
DartifactId=simple-weather -DpackageName=org.sonatype.mavenbook -Dversion=1.0
成功界面如下:
3.在pom.xml中添加组织,法律和开发人员信息
<licenses> <license> <name>Apache 2</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> <comments>a business-friendly OSS license</comments> </license> </licenses> <organization> <name>Sonatype</name> <url>http://www.sonatype.com</url> </organization> <developers> <developer> <id>liang</id> <name>li liang</name> <roles> <role>developer</role> </roles> </developer> </developers>
4.在pom.xml中添加新的依赖
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>velocity</groupId> <artifactId>velocity</artifactId> <version>1.5</version> </dependency> </dependencies>
5.项目源码
Main.java:系统入口
package org.sonatype.mavenbook.weather;
import java.io.InputStream;
import org.apache.log4j.PropertyConfigurator;
public class Main{
public static void main(String[] args) throws Exception{
PropertyConfigurator.configure(Main.class.getClassLoader()
.getResource("log4j.properties"));
int zipcode = 60202;
try{
zipcode = Integer.parseInt(args[0]);
}catch(Exception e){}
new Main(zipcode).start();
}
private int zip;
public Main(int zip){
this.zip = zip;
}
public void start() throws Exception{
InputStream dataIn = new YahooRetriever().retrieve(zip);
Weather weather = new YahooParser().parser(dataIn);
System.out.println(new WeatherFormatter().format(weather));
}
}
Weather.java:java bean
package org.sonatype.mavenbook.weather;
public class Weather{
private String city;
private String region;
private String country;
private String condition;
private String temp;
private String chill;
private String humidity;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getChill() {
return chill;
}
public void setChill(String chill) {
this.chill = chill;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
}
YahooRetriever.java: 连接到Yahll!weather并返回来自数据源的InputStream
package org.sonatype.mavenbook.weather;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
public class YahooRetriever{
private static Logger log = Logger.getLogger(YahooRetriever.class);
public InputStream retrieve(int zipcode) throws Exception{
log.info("retrieving weather data");
String url="http://weather.yahooapis.com/forecastrss?p=" + zipcode;
URLConnection conn = new URL(url).openConnection();
return conn.getInputStream();
}
}
YahooParser.java:解析来自Yahoo!weather的XML,返回weather对象
package org.sonatype.mavenbook.weather;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.io.SAXReader;
public class YahooParser{
private static Logger log = Logger.getLogger(YahooParser.class);
public Weather parser(InputStream inputStream) throws Exception{
Weather weather = new Weather();
log.info("creating XML Reader");
SAXReader xmlReader = createXmlReader();
Document doc = xmlReader.read(inputStream);
log.info("Parsing XML Response");
weather.setCity(doc.valueOf("/rss/channel/y:location/@city"));
weather.setRegion(doc.valueOf("/rss/channel/y:location/@region"));
weather.setCountry(doc.valueOf("/rss/channel/y:location/@country"));
weather.setCondition(doc.valueOf("/rss/channel/item/y:condition/@text"));
weather.setTemp(doc.valueOf("/rss/channel/item/y:condition/@temp"));
weather.setChill(doc.valueOf("/rss/channel/y:wind/@chill"));
weather.setHumidity(doc.valueOf("/rss/channel/y:atmosphere/@humidity"));
return weather;
}
private SAXReader createXmlReader(){
Map<String,String> uris = new HashMap<String,String>();
uris.put("y", "http://xml.weather.yahoo.com/ns/rss/1.0");
DocumentFactory factory = new DocumentFactory();
factory.setXPathNamespaceURIs(uris);
SAXReader xmlReader = new SAXReader();
xmlReader.setDocumentFactory(factory);
return xmlReader;
}
}
WeatherFormatter.java:接收weather对象,根据Velocity模板生成结果
package org.sonatype.mavenbook.weather;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class WeatherFormatter{
private static Logger log = Logger.getLogger(WeatherFormatter.class);
public String format(Weather weather) throws Exception{
log.info("formatting weather data");
Reader reader = new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("output.vm"));
VelocityContext context = new VelocityContext();
context.put("weather", weather);
StringWriter writer = new StringWriter();
Velocity.evaluate(context, writer, "", reader);
return writer.toString();
}
}
6.添加配置信息
在src/main下建立resources目录,在里面建立log4j.properties和output.vm两个文件
log4j.properties
log4j.rootCategory=INFO,CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.Threshold=INFO log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-4r %-5p %c{1} %x - %m%n
output.vm
*********************************** Current Weather Conditions for: ${weather.city},${weather.region},${weather.country} Temperature:${weather.temp} Condition:${weather.condition} Humidity:${weather.humidity} Wind Chill:${weather.chill} ***********************************
7.运行
mvn exec:java -Dexec.mainClass=org.sonatype.mavenbook.weather.Main
运行结果