posts - 32,comments - 8,trackbacks - 0
Dr. Oops 上任第一天


我会写各种java技术的quick start.

网上似乎有用的资料一大堆,但是每次跟着follow,总是有各种各样的问题。我都快烦了。于是打算自己写一个系列,专门讲解quick start


Dr. Oops's Rule

1. 不要问我为什么,跟着做,能成功,剩下的自己慢慢研究了。

2. 不要认为版本最新就是好!(非常重要!再次强调!)。在Java这个乱78糟的世界,个个都想出头,新版本满天飞。记住:最好的工具是能够运行的工具。
posted @ 2007-08-29 08:53 张辰 阅读(149) | 评论 (0)编辑 收藏
Flash 与后台交互方式包括了:
1. LoadVars(xml) 实际上就是flash里面一个对象,类似一个连接器。新建之后,通过sendAndLoad获取、设置值。和httpposter一样
var data_lv = new LoadVars(); 
2. flash remoting. flash需要安装components;后台服务器需要OpenAMF。
gateway_conn = NetServices.createGatewayConnection(); myService = gateway_conn.getService("myservice", this); 
3. webservice 也是在flash里面初始化一个ws的对象,然后调用。var ws:WebService = new WebService(ws_url);
4. XMLSocket 主要是即时通讯 var socket:XMLSocket = new XMLSocket();
5. 直接开flash的socket
http://androider.javaeye.com/blog/268933
在一个AMF交互的例子中,服务器建立一个MAP对象,例如:
   HashMap map=new HashMap();  
   map.put("Event", "人物移动");  
   map.put("user", "闪刀浪子");  
   map.put("x", 100);  
   map.put("y", 100);    
这样flash就可以获取这个对象:var obj:Object=new Object();  
posted @ 2010-06-17 14:15 张辰 阅读(397) | 评论 (2)编辑 收藏


1. Spring IoC容器的意义

使用BeanFactory,根据制定的xml, 动态生成对象然后加载。

只要是从BeanFactory获取的对象,都会根据xml进行装配。


2. Spring MVC

在web.xml配置了DispatcherServlet,让所有请求都被这个servlet拦截。同时配置了这个servlet的初始化对象。
。init-param = /WEB-INF/Config.xml ->
。viewResolver::org.springframework.web.servlet.view.InternalResourceViewResolver
。urlMapping::org.springframework.web.servlet.handler.SimpleUrlHandlerMapping

这个urlMapping的目标,可能是被spring接管的对象,例如SimpleFormController

当配置了DispactcherServlet之后,通过设置合适的初始化对象,能够实现某种MVC模式。



3. spring + blazeds 集成
http://static.springsource.org/spring-flex/docs/1.0.x/reference/html/ch02s02.html

在web.xml配置了2个dispatcherservlet
。*.service === /WEB-INF/remoting-servlet.xml
。/messagebroker/* === /WEB-INF/flex-config.xml 表示把blazeds的请求映射到messagebroker


。第一个servlet继续配置了urlMapping
==HessianServiceExporter可将一个普通bean导出成远程服务 这样这些被映射出来的service可以通过url访问。
问题:这些service有固定的方法,比如execute,那么这些方法如何被调用了?代码上看,是被command调用了。
回答:见第二个配置

。第二个servlet同样配置了urlMapping;还包括
..MessageBrokerHandlerAdapter
..RemotingDestinationExporter -> callDisptacherService -> CallDispatcher -> Command.execute
问题:那么CallDispatcher的Call是如何调用的?
回答:在Flash的xml文件里面指定调用了。

 


这样故事就全部被串起来了。

首先blazeds是个servlet,被封装过后,能够解析flash传输的amf格式。

通过spring的配置,flash的请求被转移到了messagebroker = blazeds,同时这个messagebroker依赖了特定的bean,例如callHandler. 这些handler又依赖了service 的属性,这个属性就是我可以控制的,同时被flash调用的。

例如

 



what is web.xml :: listener 
它能捕捉到服务器的启动和停止! 在启动和停止触发里面的方法做相应的操作!
一定是httpServlet
http://zhidao.baidu.com/question/39980900


如何加载services-config.xml

MessageBrokerFactoryBean将会去寻找BlazeDS的配置文件(默认位置为/WEB-INF/flex/services-config.xml)
posted @ 2010-06-17 09:33 张辰 阅读(430) | 评论 (2)编辑 收藏

本文讲解一个不规范的spring quick start.

1. 下载spring的插件包,什么版本之类的不用管了。反正能用。
spring.jar http://www.boxcn.net/shared/yg306zac1h
common-logging.jar http://www.boxcn.net/shared/ix93ziqljv

2. 进入eclipse,File - New - Java Project.
projectname = spring001 ===> Next
在新建导向的第二页,是Java Settings, 选择Libraries -> Add External JARS -> 添加上面2个jar
finish

3. 进入Package Explorer, 在src下新建一个class.
Package = com.java114.spring.test
Name = HelloWordSpring
再复选框:public static void main(String[] args) 钩上

4. 在HelloWordSpring.java 输入以下的代码
package com.java114.spring.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class HelloWordSpring
{
    
private String msg;

    
public void setMsg(String msg)
    {
        
this.msg = msg;
    }

    
public void sayHello()
    {
        System.out.println(msg);
    }

    
public static void main(String[] args)
    {
        Resource res 
= new ClassPathResource("com/java114/spring/test/bean.xml");
        BeanFactory factory 
= new XmlBeanFactory(res);
        HelloWordSpring hello 
= (HelloWordSpring) factory.getBean("helloBean");
        hello.sayHello();
    }

}

5. 在和HelloWordSpring.java 相同目录下面,再新建一个xml文件,名字是bean.xml, 内容如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
 
<bean id="helloBean" class="com.java114.spring.test.HelloWordSpring">
  
<property name="msg" value="simple spring demo"/>
 
</bean>
</beans>
为什么这样写,我也不知道,不管他。

6. 鼠标右键选择HelloWordSpring.java, 选择Run As - Java Applications, 得到结果:
2010-6-16 21:39:47 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/java114/spring/test/bean.xml]
simple spring demo

posted @ 2010-06-16 20:13 张辰 阅读(232) | 评论 (0)编辑 收藏
比较难的一部分

前提条件:
axis安装路径 C:\ericsson\javaextend\axis-1_4
项目名称:axisdemo
已经有的类:com.service.myService.java
配置文件:server-config.wsdd

1. 在项目添加java2wsdl目录

2.目录下面添加build.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project name="Generate WSDL from JavaBeans as Web Services" default="j2w-all" basedir=".">
    
<property name="build.dir" value="../build/classes" />
    
<property name="axis.dir" location="C:\ericsson\javaextend\axis-1_4" />
    
<path id="classpath.id">
        
<fileset dir="${axis.dir}/lib">
            
<include name="*.jar" />
        
</fileset>
        
<pathelement location="${build.dir}" />
    
</path>
    
<taskdef name="axis-java2wsdl" classname="org.apache.axis.tools.ant.wsdl.Java2WsdlAntTask" loaderref="axis">
        
<classpath refid="classpath.id" />
    
</taskdef>
    
<target name="j2w-all">
        
<antcall target="j2w-JavaBeanWS" />
    
</target>
    
<target name="j2w-JavaBeanWS">
        
<axis-java2wsdl classname="com.service.myService" classpath="${build.dir}" methods="getusername" output="myService.wsdl" location="http://localhost:8080/axisdemo/services/myService" namespace="http://localhost:8080/axisdemo/services/myService" namespaceImpl="http://localhost:8080/axisdemo/services/myService">
        
</axis-java2wsdl>
    
</target>
</project>
注意:build.dir / axis.dir / j2w-javabeanws几个地方的内容要修改。

3. 右键点击build.xml,运行ant,就可以看到生成了myService.wsdl

4.现在要把这个wsdl转化成为java,新建目录:wsdl2java

5. 新建一个build.xml,内容:
<?xml version="1.0" encoding="UTF-8"?>
<project name="wsclient" default="all" basedir=".">
    
<property name="axis.home" location="C:\ericsson\javaextend\axis-1_4" />
    
<property name="options.output" location="../wsdl2java" />
    
<path id="axis.classpath">
        
<fileset dir="${axis.home}/lib">
            
<include name="**/*.jar" />
        
</fileset>
    
</path>
    
<taskdef resource="axis-tasks.properties" classpathref="axis.classpath" />
    
<target name="-WSDL2Axis" depends="init">
        
<mkdir dir="${options.output}" />
        
<axis-wsdl2java output="${options.output}" url="${options.WSDL-URI}" verbose="true" />
    
</target>
    
<target name="init">
        
<echo>Warning: please update the associated WSDL file(s) in the folder wsdl before running the target!</echo>
        
<echo>Warning: Just run the target(s) related with your developing work!</echo>
        
<echo>
        
</echo>
    
</target>
    
<target name="all">
        
<antcall target="myService" />
    
</target>
    
<target name="myService">
        
<antcall target="-WSDL2Axis">
            
<param name="options.WSDL-URI" location="../java2wsdl/myService.wsdl" />
        
</antcall>
    
</target>
</project>
注意修改的地方:axis.home

6.build ant,在wsdl2java目录下面多出来了4个类:
myService.java
MyServiceService.java
myServiceServiceLocator.java
MyServiceSoapBindingStub.java
全部拷贝到src目录下面

7.在src目录下面添加类:
package com.axistest;

import localhost.axisdemo.services.myService.MyService;
import localhost.axisdemo.services.myService.MyServiceServiceLocator;

public class myServiceTestorByStubs
{
    
public static void main(String[] args) throws Exception
    {
        MyServiceServiceLocator Service 
= new MyServiceServiceLocator();
        MyService port 
= Service.getmyService();
        String response 
  port.getusername(邹萍");
        System.out.println(response);
    }
}

8.最后运行java application就完成了


posted @ 2008-12-18 11:03 张辰 阅读(366) | 评论 (0)编辑 收藏
reference:
 part1


1. in package explorer, change myService.java:
package com.service;
public class myService {
public String getusername(String name){
        
return "Hello "+name+",this is an Axis Web Service";
    }
}
and ctrl+1 to solve the package problem( or you can create dir and move file yourself)

2.in WebContent/WEB-INF/, create server-config.wsdd
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<handler type="java:org.apache.axis.handlers.http.URLMapper" name="URLMapper"/>    
   
<service name="myService" provider="java:RPC">
        
<parameter name="className" value="com.service.myService"/>
        
<parameter name="allowedMethods" value="getusername"/>
    
</service> 
<transport name="http">
 
<requestFlow>
    
<handler type="URLMapper"/>
 
</requestFlow>
</transport>
</deployment>

3. in src/, create myServiceTestorByWSDD.java
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class myServiceTestorByWSDD {
public tatic void main(String[] args) throws ServiceException,MalformedURLException, RemoteException {
        String endpoint 
= http://localhost:8080/oopsaxis1/services/myService;
        Service service 
= new Service();                // 创建一个Service实例,注意是必须的!
        Call call = (Call) service.createCall();   // 创建Call实例,也是必须的!
        call.setTargetEndpointAddress(new java.net.URL(endpoint));// 为Call设置服务的位置
        call.setOperationName("getusername");              // 注意方法名与JavaBeanWS.java中一样!!
        String res = (String) call.invoke(new Object[] { "pixysoft" });       // 返回String,传入参数
        System.out.println(res);
}
}

4. open tomcat, and :http://localhost:8080/oopsaxis1/servlet/AxisServlet,you can see:
And now Some Services
myService (wsdl) 
getusername 

5. right click myServiceTestorByWSDD.java, run as java application.


done!

posted @ 2008-12-17 13:51 张辰 阅读(248) | 评论 (0)编辑 收藏

reference:

http://www.cnblogs.com/cy163/archive/2008/11/28/1343516.html

pre-condition:
1.install eclipse
2.install tomcat plugin

process:
1.download axis lib: http://ws.apache.org/axis

2. set classpath:
1.AXIS_HOME
D:\Java\axis-1_4(这是我的Axis路径)
2.AXIS_LIB
%AXIS_HOME%\lib
3.AXIS_CLASSPATH
%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar;%AXIS_LIB%\wsdl4j-1.5.1.jar;%AXIS_LIB%\activation.jar;%AXIS_LIB%\xmlrpc-2.0.jar
4.CLASSPATH
.;%JAVA_HOME%\lib\tools.jar;%JAVA_HOME%\lib\dt.jar; %AXIS_CLASSPATH%;
5.在你的%TOMCAT_HOME%\common\lib下需要加入三个包 activation.jar、mail.jar、tools.jar,注意这三个包是必须的,尽管tools.jar很常见,但这也是运行Axis所必须的包。


3.FIle - new - dynamic web project
projectname: oopsaxis1
target runtime: apache tomcat V5.5


4. oopsaxis1/WebContent/WEB-INF/lib,add lib from %AXIS_HOME%\lib
axis.jar/axis-ant.jar/commons-log.jar...

5.oopsaxis1/WebContent/WEB-INF/web.xml,  replace by %AXIS_HOME%\webapps\axis\WEB-INF\web.xml

6.oopsaxis1/src, add java file:
public class myService
{
    
public String getusername(String name)
    {
        
return "Hello " + name + ",this is an Axis DII Web Service";
    }
}


7.copy myService to oopsaxis1/WebContent, and rename to myService.jws

8. right click myService.jws, run as - run on server, you can see:
http://localhost:8080/oopsaxis1/myService.jws
There is a Web Service here
Click to see the WSDL 
click the link, you can see the wsdl


9. in eclipse - package explorer - src, new class:
package com.oopsaxis;

import java.net.MalformedURLException;
import java.rmi.RemoteException;

import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

public class myServiceTestorByjws
{
    
public static void main(String[] args) throws ServiceException,
            MalformedURLException, RemoteException
    {
        String endpoint 
= http://localhost:8080/oopsaxis1/myService.jws;
        String name 
= " pixysoft";
        Service service 
= new Service();
        Call call 
= (Call) service.createCall();

        call.setTargetEndpointAddress(
new java.net.URL(endpoint));
        call.addParameter(
"param1", XMLType.XSD_STRING, ParameterMode.IN);
        call.setOperationName(
"getusername");
        call.setReturnType(XMLType.XSD_STRING);
        String ret 
= (String) call.invoke(new Object[] { name });
        System.out.println(
"返回结果:" + ret);
    }
}

10. right click myServiceTestorByjws, run as java application,you get:
返回结果:Hello pixysoft,this is an Axis DII Web Service

done!
posted @ 2008-12-17 13:40 张辰 阅读(249) | 评论 (0)编辑 收藏

Using Ant

Writing a Simple Buildfile

Ant's buildfiles are written in XML. Each buildfile contains one project and at least one (default) target. Targets contain task elements. Each task element of the buildfile can have an id attribute and can later be referred to by the value supplied to this. The value has to be unique. (For additional information, see the Tasks section below.)

Projects

A project has three attributes:

Attribute Description Required
name the name of the project. No
default the default target to use when no target is supplied. No; however, since Ant 1.6.0, every project includes an implicit target that contains any and all top-level tasks and/or types. This target will always be executed as part of the project's initialization, even when Ant is run with the -projecthelp option.
basedir the base directory from which all path calculations are done. This attribute might be overridden by setting the "basedir" property beforehand. When this is done, it must be omitted in the project tag. If neither the attribute nor the property have been set, the parent directory of the buildfile will be used. No

Optionally, a description for the project can be provided as a top-level <description> element (see the description type).

Each project defines one or more targets. A target is a set of tasks you want to be executed. When starting Ant, you can select which target(s) you want to have executed. When no target is given, the project's default is used.

Targets

A target can depend on other targets. You might have a target for compiling, for example, and a target for creating a distributable. You can only build a distributable when you have compiled first, so the distribute target depends on the compile target. Ant resolves these dependencies.

It should be noted, however, that Ant's depends attribute only specifies the order in which targets should be executed - it does not affect whether the target that specifies the dependency(s) gets executed if the dependent target(s) did not (need to) run.

Ant tries to execute the targets in the depends attribute in the order they appear (from left to right). Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it:

<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

Suppose we want to execute target D. From its depends attribute, you might think that first target C, then B and then A is executed. Wrong! C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D.

In a chain of dependencies stretching back from a given target such as D above, each target gets executed only once, even when more than one target depends on it. Thus, executing the D target will first result in C being called, which in turn will first call B, which in turn will first call A. After A, then B, then C have executed, execution returns to the dependency list of D, which will not call B and A, since they were already called in process of dependency resolution for C and B respectively as dependencies of D. Had no such dependencies been discovered in processing C and B, B and A would have been executed after C in processing D's dependency list.

A target also has the ability to perform its execution if (or unless) a property has been set. This allows, for example, better control on the building process depending on the state of the system (java version, OS, command-line property defines, etc.). To make a target sense this property, you should add the if (or unless) attribute with the name of the property that the target should react to. Note: Ant will only check whether the property has been set, the value doesn't matter. A property set to the empty string is still an existing property. For example:

<target name="build-module-A" if="module-A-present"/>
<target name="build-own-fake-module-A" unless="module-A-present"/>

In the first example, if the module-A-present property is set (to any value, e.g. false), the target will be run. In the second example, if the module-A-present property is set (again, to any value), the target will not be run.

Only one propertyname can be specified in the if/unless clause. If you want to check multiple conditions, you can use a dependend target for computing the result for the check:

<target name="myTarget" depends="myTarget.check" if="myTarget.run">
<echo>Files foo.txt and bar.txt are present.</echo>
</target>
<target name="myTarget.check">
<condition property="myTarget.run">
<and>
<available file="foo.txt"/>
<available file="bar.txt"/>
</and>
</condition>
</target>

If no if and no unless attribute is present, the target will always be executed.

Important: the if and unless attributes only enable or disable the target to which they are attached. They do not control whether or not targets that a conditional target depends upon get executed. In fact, they do not even get evaluated until the target is about to be executed, and all its predecessors have already run.

The optional description attribute can be used to provide a one-line description of this target, which is printed by the -projecthelp command-line option. Targets without such a description are deemed internal and will not be listed, unless either the -verbose or -debug option is used.

It is a good practice to place your tstamp tasks in a so-called initialization target, on which all other targets depend. Make sure that target is always the first one in the depends list of the other targets. In this manual, most initialization targets have the name "init".

If the depends attribute and the if/unless attribute are set, the depends attribute is executed first.

A target has the following attributes:

Attribute Description Required
name the name of the target. Yes
depends a comma-separated list of names of targets on which this target depends. No
if the name of the property that must be set in order for this target to execute. No
unless the name of the property that must not be set in order for this target to execute. No
description a short description of this target's function. No

 

A target name can be any alphanumeric string valid in the encoding of the XML file. The empty string "" is in this set, as is comma "," and space " ". Please avoid using these, as they will not be supported in future Ant versions because of all the confusion they cause. IDE support of unusual target names, or any target name containing spaces, varies with the IDE.

Targets beginning with a hyphen such as "-restart" are valid, and can be used to name targets that should not be called directly from the command line.

Tasks

A task is a piece of code that can be executed.

A task can have multiple attributes (or arguments, if you prefer). The value of an attribute might contain references to a property. These references will be resolved before the task is executed.

Tasks have a common structure:

<name attribute1="value1" attribute2="value2" ... />

where name is the name of the task, attributeN is the attribute name, and valueN is the value for this attribute.

There is a set of built-in tasks, along with a number of optional tasks, but it is also very easy to write your own.

All tasks share a task name attribute. The value of this attribute will be used in the logging messages generated by Ant.

Tasks can be assigned an id attribute:
<taskname id="taskID" ... />
where taskname is the name of the task, and taskID is a unique identifier for this task. You can refer to the corresponding task object in scripts or other tasks via this name. For example, in scripts you could do:
<script ... >
task1.setFoo("bar");
</script>
to set the foo attribute of this particular task instance. In another task (written in Java), you can access the instance via project.getReference("task1").

Note1: If "task1" has not been run yet, then it has not been configured (ie., no attributes have been set), and if it is going to be configured later, anything you've done to the instance may be overwritten.

Note2: Future versions of Ant will most likely not be backward-compatible with this behaviour, since there will likely be no task instances at all, only proxies.

Properties

A project can have a set of properties. These might be set in the buildfile by the property task, or might be set outside Ant. A property has a name and a value; the name is case-sensitive. Properties may be used in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value. For example, if there is a "builddir" property with the value "build", then this could be used in an attribute like this: ${builddir}/classes. This is resolved at run-time as build/classes.

In the event you should need to include this construct literally (i.e. without property substitutions), simply "escape" the '$' character by doubling it. To continue the previous example:

  <echo>$${builddir}=${builddir}</echo>
will echo this message:
  ${builddir}=build/classes

 

In order to maintain backward compatibility with older Ant releases, a single '$' character encountered apart from a property-like construct (including a matched pair of french braces) will be interpreted literally; that is, as '$'. The "correct" way to specify this literal character, however, is by using the escaping mechanism unconditionally, so that "$$" is obtained by specifying "$$$$". Mixing the two approaches yields unpredictable results, as "$$$" results in "$$".

Built-in Properties

Ant provides access to all system properties as if they had been defined using a <property> task. For example, ${os.name} expands to the name of the operating system.

For a list of system properties see the Javadoc of System.getProperties.

In addition, Ant has some built-in properties:

basedir             the absolute path of the project's basedir (as set
with the basedir attribute of <project>).
ant.file            the absolute path of the buildfile.
ant.version         the version of Ant
ant.project.name    the name of the project that is currently executing;
it is set in the name attribute of <project>.
ant.java.version    the JVM version Ant detected; currently it can hold
the values "1.2", "1.3", "1.4" and "1.5".

There is also another property, but this is set by the launcher script and therefore maybe not set inside IDEs:

ant.home            home directory of Ant

Example Buildfile

<project name="MyProject" default="dist" basedir=".">
<description>
simple example build file
</description>
<!-- set global properties for this build -->
<property name="src" location="src"/>
<property name="build" location="build"/>
<property name="dist"  location="dist"/>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="compile" depends="init"
description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}"/>
</target>
<target name="dist" depends="compile"
description="generate the distribution" >
<!-- Create the distribution directory -->
<mkdir dir="${dist}/lib"/>
<!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
<jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
</project>

Notice that we are declaring properties outside any target. As of Ant 1.6 all tasks can be declared outside targets (earlier version only allowed <property>,<typedef> and <taskdef>). When you do this they are evaluated before any targets are executed. Some tasks will generate build failures if they are used outside of targets as they may cause infinite loops otherwise (<antcall> for example).

We have given some targets descriptions; this causes the projecthelp invocation option to list them as public targets with the descriptions; the other target is internal and not listed.

Finally, for this target to work the source in the src subdirectory should be stored in a directory tree which matches the package names. Check the <javac> task for details.

Token Filters

A project can have a set of tokens that might be automatically expanded if found when a file is copied, when the filtering-copy behavior is selected in the tasks that support this. These might be set in the buildfile by the filter task.

Since this can potentially be a very harmful behavior, the tokens in the files must be of the form @token@, where token is the token name that is set in the <filter> task. This token syntax matches the syntax of other build systems that perform such filtering and remains sufficiently orthogonal to most programming and scripting languages, as well as with documentation systems.

Note: If a token with the format @token@ is found in a file, but no filter is associated with that token, no changes take place; therefore, no escaping method is available - but as long as you choose appropriate names for your tokens, this should not cause problems.

Warning: If you copy binary files with filtering turned on, you can corrupt the files. This feature should be used with text files only.

Path-like Structures

You can specify PATH- and CLASSPATH-type references using both ":" and ";" as separator characters. Ant will convert the separator to the correct character of the current operating system.

Wherever path-like values need to be specified, a nested element can be used. This takes the general form of:

    <classpath>
<pathelement path="${classpath}"/>
<pathelement location="lib/helper.jar"/>
</classpath>

The location attribute specifies a single file or directory relative to the project's base directory (or an absolute filename), while the path attribute accepts colon- or semicolon-separated lists of locations. The path attribute is intended to be used with predefined paths - in any other case, multiple elements with location attributes should be preferred.

As a shortcut, the <classpath> tag supports path and location attributes of its own, so:

    <classpath>
<pathelement path="${classpath}"/>
</classpath>

can be abbreviated to:

    <classpath path="${classpath}"/>

In addition, one or more Resource Collections can be specified as nested elements (these must consist of file-type resources only). Additionally, it should be noted that although resource collections are processed in the order encountered, certain resource collection types such as fileset, dirset and files are undefined in terms of order.

    <classpath>
<pathelement path="${classpath}"/>
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
<pathelement location="classes"/>
<dirset dir="${build.dir}">
<include name="apps/**/classes"/>
<exclude name="apps/**/*Test*"/>
</dirset>
<filelist refid="third-party_jars"/>
</classpath>

This builds a path that holds the value of ${classpath}, followed by all jar files in the lib directory, the classes directory, all directories named classes under the apps subdirectory of ${build.dir}, except those that have the text Test in their name, and the files specified in the referenced FileList.

If you want to use the same path-like structure for several tasks, you can define them with a <path> element at the same level as targets, and reference them via their id attribute--see References for an example.

A path-like structure can include a reference to another path-like structure (a path being itself a resource collection) via nested <path> elements:

    <path id="base.path">
<pathelement path="${classpath}"/>
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
<pathelement location="classes"/>
</path>
<path id="tests.path">
<path refid="base.path"/>
<pathelement location="testclasses"/>
</path>
The shortcuts previously mentioned for <classpath> are also valid for <path>.For example:
    <path id="base.path">
<pathelement path="${classpath}"/>
</path>
can be written as:
    <path id="base.path" path="${classpath}"/>

Path Shortcut

In Ant 1.6 a shortcut for converting paths to OS specific strings in properties has been added. One can use the expression ${toString:pathreference} to convert a path element reference to a string that can be used for a path argument. For example:

  <path id="lib.path.ref">
<fileset dir="lib" includes="*.jar"/>
</path>
<javac srcdir="src" destdir="classes">
<compilerarg arg="-Xbootstrap/p:${toString:lib.path.ref}"/>
</javac>

Command-line Arguments

Several tasks take arguments that will be passed to another process on the command line. To make it easier to specify arguments that contain space characters, nested arg elements can be used.

Attribute Description Required
value a single command-line argument; can contain space characters. Exactly one of these.
file The name of a file as a single command-line argument; will be replaced with the absolute filename of the file.
path A string that will be treated as a path-like string as a single command-line argument; you can use ; or : as path separators and Ant will convert it to the platform's local conventions.
pathref Reference to a path defined elsewhere. Ant will convert it to the platform's local conventions.
line a space-delimited list of command-line arguments.

It is highly recommended to avoid the line version when possible. Ant will try to split the command line in a way similar to what a (Unix) shell would do, but may create something that is very different from what you expect under some circumstances.

Examples

  <arg value="-l -a"/>

is a single command-line argument containing a space character, not separate commands "-l" and "-a".

  <arg line="-l -a"/>

This is a command line with two separate arguments, "-l" and "-a".

  <arg path="/dir;/dir2:\dir3"/>

is a single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

References

Any project element can be assigned an identifier using its id attribute. In most cases the element can subsequently be referenced by specifying the refid attribute on an element of the same type. This can be useful if you are going to replicate the same snippet of XML over and over again--using a <classpath> structure more than once, for example.

The following example:

<project ... >
<target ... >
<rmic ...>
<classpath>
<pathelement location="lib/"/>
<pathelement path="${java.class.path}/"/>
<pathelement path="${additional.path}"/>
</classpath>
</rmic>
</target>
<target ... >
<javac ...>
<classpath>
<pathelement location="lib/"/>
<pathelement path="${java.class.path}/"/>
<pathelement path="${additional.path}"/>
</classpath>
</javac>
</target>
</project>

could be rewritten as:

<project ... >
<path id="project.class.path">
<pathelement location="lib/"/>
<pathelement path="${java.class.path}/"/>
<pathelement path="${additional.path}"/>
</path>
<target ... >
<rmic ...>
<classpath refid="project.class.path"/>
</rmic>
</target>
<target ... >
<javac ...>
<classpath refid="project.class.path"/>
</javac>
</target>
</project>

All tasks that use nested elements for PatternSets, FileSets, ZipFileSets or path-like structures accept references to these structures as shown in the examples. Using refid on a task will ordinarily have the same effect (referencing a task already declared), but the user should be aware that the interpretation of this attribute is dependent on the implementation of the element upon which it is specified. Some tasks (the property task is a handy example) deliberately assign a different meaning to refid.

Use of external tasks

Ant supports a plugin mechanism for using third party tasks. For using them you have to do two steps:
  1. place their implementation somewhere where Ant can find them
  2. declare them.
Don't add anything to the CLASSPATH environment variable - this is often the reason for very obscure errors. Use Ant's own mechanisms for adding libraries:
  • via command line argument -lib
  • adding to ${user.home}/.ant/lib
  • adding to ${ant.home}/lib
For the declaration there are several ways:
  • declare a single task per using instruction using <taskdef name="taskname" classname="ImplementationClass"/>
    <taskdef name="for" classname="net.sf.antcontrib.logic.For" /> <for ... />
  • declare a bundle of tasks using a properties-file holding these taskname-ImplementationClass-pairs and <taskdef>
    <taskdef resource="net/sf/antcontrib/antcontrib.properties" /> <for ... />
  • declare a bundle of tasks using a xml-file holding these taskname-ImplementationClass-pairs and <taskdef>
    <taskdef resource="net/sf/antcontrib/antlib.xml" /> <for ... />
  • declare a bundle of tasks using a xml-file named antlib.xml, XML-namespace and antlib: protocoll handler
    <project xmlns:ac="antlib:net.sf.antconrib"/> <ac:for ... />
If you need a special function, you should
  1. have a look at this manual, because Ant provides lot of tasks
  2. have a look at the external task page in the manual (or better online)
  3. have a look at the external task wiki page
  4. ask on the Ant user list
  5. implement (and share) your own
posted @ 2008-12-05 13:41 张辰 阅读(363) | 评论 (0)编辑 收藏
1. 在src目录下面添加文件:HelloWorldTest.java
public class HelloWorldTest extends junit.framework.TestCase {

    
public void testNothing() {
    }
    
    
public void testWillAlwaysFail() {
        fail(
"An error message");
    }
    
}

2.在lib目录下面添加junit.jar类

3.修改build.xml文件如下:
<project name="HelloWorld" basedir="." default="main">

    
<property name="src.dir" value="src" />

    
<property name="build.dir" value="build" />
    
<property name="classes.dir" value="${build.dir}/classes" />
    
<property name="jar.dir" value="${build.dir}/jar" />
    
<property name="lib.dir" value="lib" />
    
<path id="classpath">
        
<fileset dir="${lib.dir}" includes="**/*.jar" />
    
</path>

    
<property name="main-class" value="oata.HelloWorld" />



    
<target name="clean">
        
<delete dir="${build.dir}" />
    
</target>

    
<target name="compile">
        
<mkdir dir="${classes.dir}" />
        
<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath" />
        
<copy todir="${classes.dir}">
            
<fileset dir="${src.dir}" excludes="**/*.java" />
        
</copy>

    
</target>

    
<target name="jar" depends="compile">
        
<mkdir dir="${jar.dir}" />
        
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            
<manifest>
                
<attribute name="Main-Class" value="${main-class}" />
            
</manifest>
        
</jar>
    
</target>

    
<target name="run" depends="jar">
        
<java fork="true" classname="${main-class}">
            
<classpath>
                
<path refid="classpath" />
                
<path id="application" location="${jar.dir}/${ant.project.name}.jar" />
            
</classpath>
        
</java>

    
</target>
    
<target name="junit" depends="jar">
        
<junit printsummary="yes">
            
<classpath>
                
<path refid="classpath" />
                
<path refid="application" />
            
</classpath>

            
<batchtest fork="yes">
                
<fileset dir="${src.dir}" includes="*Test.java" />
            
</batchtest>
        
</junit>
    
</target>

    
<target name="clean-build" depends="clean,jar" />

    
<target name="main" depends="clean,run" />

</project>


注:修改地方如下:
    

    
<target name="run" depends="jar">
        
<java fork="true" classname="${main-class}">
            
<classpath>
                
<path refid="classpath"/>
                
<path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
            
</classpath>
        
</java>
    
</target>
    
    
<target name="junit" depends="jar">
        
<junit printsummary="yes">
            
<classpath>
                
<path refid="classpath"/>
                
<path refid="application"/>
            
</classpath>
            
            
<batchtest fork="yes">
                
<fileset dir="${src.dir}" includes="*Test.java"/>
            
</batchtest>
        
</junit>
    
</target>

    



6运行,得到结果:
...
junit:
    [junit] Running HelloWorldTest
    [junit] Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 0,01 sec
    [junit] Test HelloWorldTest FAILED

BUILD SUCCESSFUL
...
posted @ 2008-12-04 15:03 张辰 阅读(247) | 评论 (0)编辑 收藏
1.在上文基础上,修改源代码 HelloWorld.java

package oata;

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class HelloWorld {
    
static Logger logger = Logger.getLogger(HelloWorld.class);

    
public static void main(String[] args) {
        BasicConfigurator.configure();
        logger.info(
"Hello World");          // the old SysO-statement
    }
}

2. 在javademo目录下面添加lib目录,里面添加log4j的jar文件

3.修改build.xml,
<project name="HelloWorld" basedir="." default="main">

    
<property name="src.dir" value="src" />

    
<property name="build.dir" value="build" />
    
<property name="classes.dir" value="${build.dir}/classes" />
    
<property name="jar.dir" value="${build.dir}/jar" />
    
<property name="lib.dir" value="lib" />
    
<path id="classpath">
        
<fileset dir="${lib.dir}" includes="**/*.jar" />
    
</path>
<property name="main-class" value="oata.HelloWorld" />



    
<target name="clean">
        
<delete dir="${build.dir}" />
    
</target>

    
<target name="compile">
        
<mkdir dir="${classes.dir}" />
        
<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>

    
</target>
    
<target name="jar" depends="compile">
        
<mkdir dir="${jar.dir}" />
        
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            
<manifest>
                
<attribute name="Main-Class" value="${main-class}" />
            
</manifest>
        
</jar>
    
</target>
    
<target name="run" depends="jar">
        
<java fork="true" classname="${main-class}">
            
<classpath>
                
<path refid="classpath" />
                
<path location="${jar.dir}/${ant.project.name}.jar" />
            
</classpath>
        
</java>

    
</target>

    
<target name="clean-build" depends="clean,jar" />

    
<target name="main" depends="clean,run" />

</project>

4. 运行ant
posted @ 2008-12-04 14:22 张辰 阅读(209) | 评论 (0)编辑 收藏
1.接上文,在javademo下面新建文件 build.xml
<project>

    
<target name="clean">
        
<delete dir="build"/>
    
</target>

    
<target name="compile">
        
<mkdir dir="build/classes"/>
        
<javac srcdir="src" destdir="build/classes"/>
    
</target>

    
<target name="jar">
        
<mkdir dir="build/jar"/>
        
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
            
<manifest>
                
<attribute name="Main-Class" value="oata.HelloWorld"/>
            
</manifest>
        
</jar>
    
</target>

    
<target name="run">
        
<java jar="build/jar/HelloWorld.jar" fork="true"/>
    
</target>

</project>

2.运行:
ant compile
ant jar
ant run
看到结果

注意:要在系统环境里面设置PATH到ant的bin目录

3.更加简便的打包:修改build.xml,为:
<project name="HelloWorld" basedir="." default="main">

    
<property name="src.dir"     value="src"/>

    
<property name="build.dir"   value="build"/>
    
<property name="classes.dir" value="${build.dir}/classes"/>
    
<property name="jar.dir"     value="${build.dir}/jar"/>

    
<property name="main-class"  value="oata.HelloWorld"/>



    
<target name="clean">
        
<delete dir="${build.dir}"/>
    
</target>

    
<target name="compile">
        
<mkdir dir="${classes.dir}"/>
        
<javac srcdir="${src.dir}" destdir="${classes.dir}"/>
    
</target>

    
<target name="jar" depends="compile">
        
<mkdir dir="${jar.dir}"/>
        
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            
<manifest>
                
<attribute name="Main-Class" value="${main-class}"/>
            
</manifest>
        
</jar>
    
</target>

    
<target name="run" depends="jar">
        
<java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
    
</target>

    
<target name="clean-build" depends="clean,jar"/>

    
<target name="main" depends="clean,run"/>

</project>
posted @ 2008-12-04 11:50 张辰 阅读(380) | 评论 (0)编辑 收藏
仅列出标题  下一页