21 April 2010

IMP and EXP commands

Copying a database

If you want to copy the entire database, the basic steps are as follows:

1. Perform a full export:

exp userid=system/manager file=my_db.dmp log=my_db.log full=y
The FULL=Y parameter forces a full database export. I also make sure to log the output of my export utility to a log file. It becomes a handy reference.
2. FTP the dump file (and log file) to the destination server. Make sure that you FTP in binary mode!

3. Precreate a new database on the destination server.

4. Precreate the tablespaces on the new database to match the same tablespace names of your source database.

5. Import the full database:

imp userid=system/manager file=my_db.dmp log=imp.log full=y
Again, log the output to a file in case there are errors.
Copying a schema

If you only want to copy a schema to the new server, things are basically the same.

1. Perform a schema export:

exp userid=system/manager file=my_db.dmp log=my_db.log owner=SCOTT
The OWNER parameter exports a schema. In my example, that would be the SCOTT schema. Again, I also make sure to log the output of my export utility to a log file.
2. FTP the dump file (and log file) to the destination server. Make sure that you FTP in binary mode!

3. Precreate a new database on the destination server.

4. Precreate the tablespaces on the new database to match the same tablespace names of your source database.

5. Precreate the user in that database.

6. Import the dump file:

imp userid=system/manager file=my_db.dmp log=imp.log fromuser=SCOTT
Again, log the output to a file in case there are errors. The FROMUSER clause tells imp which schema to import. If you wish to change the objects to a new owner, use the TOUSER clause as well.

16 April 2010

Writing a Simple Buildfile







Writing a Simple Buildfile



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 href="CoreTypes/description.html">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.



More information can be found in the
dedicated manual page.



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



Properties are an important way to customize a build process or
to just provide shortcuts for strings that are used repeatedly
inside a build file.



In its most simple form properties are defined in the build file
(for example 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 or in the nested text of tasks that support
them. 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.



With Ant 1.8.0 property expansion has become much more powerful
than simple key value pairs, more details can be
found in the concepts section of this
manual.



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.



By default a path like structure will re-evaluate all nested
resource collections whenever it is used, which may lead to
unnecessary re-scanning of the filesystem. Since Ant 1.8.0 path has
an optional cache attribute, if it is set to true, the path
instance will only scan its nested resource collections once and
assume it doesn't change during the build anymore (the default
for cache still is false). Even if you are using the
path only in a single task it may improve overall performance to set
cache to true if you are using complex nested
constructs.



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" cache="true">
<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="-Xbootclasspath/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.
prefix A fixed string to be placed in front of the
argument. In the case of a line broken into parts, it will be
placed in front of every part. Since Ant 1.8.
No
suffix A fixed string to be placed immediately after the
argument. In the case of a line broken into parts, it will be
placed after every part. Since Ant 1.8.
No


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




Hello World with Ant


Tutorial: Hello World with Ant



This document provides a step by step tutorial for starting java programming with Ant.
It does not contain deeper knowledge about Java or Ant. This tutorial has the goal
to let you see, how to do the easiest steps in Ant.





Content






Preparing the project


We want to separate the source from the generated files, so our java source files will
be in src folder. All generated files should be under build, and there
splitted into several subdirectories for the individual steps: classes for our compiled
files and jar for our own JAR-file.


We have to create only the src directory. (Because I am working on Windows, here is
the win-syntax - translate to your shell):



 

md src


The following simple Java class just prints a fixed message out to STDOUT,
so just write this code into src\oata\HelloWorld.java.



 

package oata;

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}


Now just try to compile and run that:

 

md build\classes
javac -sourcepath src -d build\classes src\oata\HelloWorld.java
java -cp build\classes oata.HelloWorld

which will result in
 

Hello World



Creating a jar-file is not very difficult. But creating a startable jar-file needs more steps: create a
manifest-file containing the start class, creating the target directory and archiving the files.


 

echo Main-Class: oata.HelloWorld>myManifest
md build\jar
jar cfm build\jar\HelloWorld.jar myManifest -C build\classes .
java -jar build\jar\HelloWorld.jar


Note: Do not have blanks around the >-sign in the echo Main-Class instruction because it would
falsify it!





Four steps to a running application


After finishing the java-only step we have to think about our build process. We have to compile our code, otherwise we couldn't
start the program. Oh - "start" - yes, we could provide a target for that. We should package our application.
Now it's only one class - but if you want to provide a download, no one would download several hundreds files ...
(think about a complex Swing GUI - so let us create a jar file. A startable jar file would be nice ... And it's a
good practise to have a "clean" target, which deletes all the generated stuff. Many failures could be solved just
by a "clean build".



By default Ant uses build.xml as the name for a buildfile, so our .\build.xml would be:


 

<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>


Now you can compile, package and run the application via


 

ant compile
ant jar
ant run

Or shorter with


 

ant compile jar run


While having a look at the buildfile, we will see some similar steps between Ant and the java-only commands:









java-only Ant
 

md build\classes
javac
-sourcepath src
-d build\classes
src\oata\HelloWorld.java
echo Main-Class: oata.HelloWorld>mf
md build\jar
jar cfm
build\jar\HelloWorld.jar
mf
-C build\classes
.



java -jar build\jar\HelloWorld.jar
 

<mkdir dir="build/classes"/>
<javac
srcdir="src"
destdir="build/classes"/>
<!-- automatically detected -->
<!-- obsolete; done via manifest tag -->
<mkdir dir="build/jar"/>
<jar
destfile="build/jar/HelloWorld.jar"

basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="oata.HelloWorld"/>
</manifest>
</jar>
<java jar="build/jar/HelloWorld.jar" fork="true"/>






Enhance the build file


Now we have a working buildfile we could do some enhancements: many time you are referencing the
same directories, main-class and jar-name are hard coded, and while invocation you have to remember
the right order of build steps.


The first and second point would be addressed with properties, the third with a special property - an attribute
of the <project>-tag and the fourth problem can be solved using dependencies.




 

<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>



Now it's easier, just do a ant and you will get


 

Buildfile: build.xml

clean:

compile:
[mkdir] Created dir: C:\...\build\classes
[javac] Compiling 1 source file to C:\...\build\classes

jar:
[mkdir] Created dir: C:\...\build\jar
[jar] Building jar: C:\...\build\jar\HelloWorld.jar

run:
[java] Hello World

main:

BUILD SUCCESSFUL




Using external libraries


Somehow told us not to use syso-statements. For log-Statements we should use a Logging-API - customizable on a high
degree (including switching off during usual life (= not development) execution). We use Log4J for that, because


  • it is not part of the JDK (1.4+) and we want to show how to use external libs

  • it can run under JDK 1.2 (as Ant)

  • it's highly configurable

  • it's from Apache ;-)


We store our external libraries in a new directory lib. Log4J can be
downloaded [1] from Logging's Homepage.
Create the lib directory and extract the log4j-1.2.9.jar into that lib-directory. After that we have to modify
our java source to use that library and our buildfile so that this library could be accessed during compilation and run.


Working with Log4J is documented inside its manual. Here we use the MyApp-example from the
Short Manual [2]. First we have to modify the java source to
use the logging framework:



 

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
}
}


Most of the modifications are "framework overhead" which has to be done once. The blue line is our "old System-out"
statement.


Don't try to run ant - you will only get lot of compiler errors. Log4J is not inside the classpath so we have
to do a little work here. But do not change the CLASSPATH environment variable! This is only for this project and maybe
you would break other environments (this is one of the most famous mistakes when working with Ant). We introduce Log4J
(or to be more precise: all libraries (jar-files) which are somewhere under .\lib) into our buildfile:



 

<project name="HelloWorld" basedir="." default="main">
...
<property name="lib.dir" value="lib"/>

<path id="classpath">
<fileset dir="${lib.dir}" includes="**/*.jar"/>
</path>

...

<target name="compile">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
</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>

...

</project>


In this example we start our application not via its Main-Class manifest-attribute, because we could not provide
a jarname and a classpath. So add our class in the red line to the already defined path and start as usual. Running
ant would give (after the usual compile stuff):



 

[java] 0 [main] INFO oata.HelloWorld - Hello World


What's that?


  • [java] Ant task running at the moment

  • 0 sorry don't know - some Log4J stuff

  • [main] the running thread from our application

  • INFO log level of that statement
  • oata.HelloWorld source of that statement
  • - separator

  • Hello World the message


For another layout ... have a look inside Log4J's documentation about using other PatternLayout's.





Configuration files


Why we have used Log4J? "It's highly configurable"? No - all is hard coded! But that is not the debt of Log4J - it's
ours. We had coded BasicConfigurator.configure(); which implies a simple, but hard coded configuration. More
confortable would be using a property file. In the java source delete the BasicConfiguration-line from the main() method
(and the related import-statement). Log4J will search then for a configuration as described in it's manual. Then create
a new file src/log4j.properties. That's the default name for Log4J's configuration and using that name would make
life easier - not only the framework knows what is inside, you too!



 

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%m%n


This configuration creates an output channel ("Appender") to console named as stdout which prints the
message (%m) followed by a line feed (%n) - same as the earlier System.out.println() :-) Oooh kay - but we haven't
finished yet. We should deliver the configuration file, too. So we change the buildfile:



 

...
<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>
...


This copies all resources (as long as they haven't the suffix ".java") to the build directory, so we could
start the application from that directory and these files will included into the jar.





Testing the class


In this step we will introduce the usage of the JUnit [3] testframework in combination with Ant. Because Ant
has a built-in JUnit 3.8.2 you could start directly using it. Write a test class in src\HelloWorldTest.java:



 

public class HelloWorldTest extends junit.framework.TestCase {

public void testNothing() {
}

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

}


Because we dont have real business logic to test, this test class is very small: just show how to start. For
further information see the JUnit documentation [3] and the manual of
junit task.
Now we add a junit instruction to our buildfile:



 

...

<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>


...



We reuse the path to our own jar file as defined in run-target by giving it an ID.
The printsummary=yes lets us see more detailed information than just a "FAILED" or "PASSED" message.
How much tests failed? Some errors? Printsummary lets us know. The classpath is set up to find our classes.
To run tests the batchtest here is used, so you could easily add more test classes in the future just
by naming them *Test.java. This is a common naming scheme.



After a ant junit you'll get:



 

...
junit:
[junit] Running HelloWorldTest
[junit] Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 0,01 sec
[junit] Test HelloWorldTest FAILED

BUILD SUCCESSFUL
...


We can also produce a report. Something that you (and other) could read after closing the shell ....
There are two steps: 1. let <junit> log the information and 2. convert these to something readable (browsable).



 

...
<property name="report.dir" value="${build.dir}/junitreport"/>
...
<target name="junit" depends="jar">
<mkdir dir="${report.dir}"/>
<junit printsummary="yes">
<classpath>
<path refid="classpath"/>
<path refid="application"/>
</classpath>

<formatter type="xml"/>

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

<target name="junitreport">
<junitreport todir="${report.dir}">
<fileset dir="${report.dir}" includes="TEST-*.xml"/>
<report todir="${report.dir}"/>
</junitreport>
</target>



Because we would produce a lot of files and these files would be written to the current directory by default,
we define a report directory, create it before running the junit and redirect the logging to it. The log format
is XML so junitreport could parse it. In a second target junitreport should create a browsable
HTML-report for all generated xml-log files in the report directory. Now you can open the ${report.dir}\index.html and
see the result (looks something like JavaDoc).

Personally I use two different targets for junit and junitreport. Generating the HTML report needs some time and you dont
need the HTML report just for testing, e.g. if you are fixing an error or a integration server is doing a job.







Resources


 

[1] http://www.apache.org/dist/logging/log4j/1.2.13/logging-log4j-1.2.13.zip
[2] http://logging.apache.org/log4j/docs/manual.html
[3] http://www.junit.org/index.htm



http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html

07 April 2010

Unix vi editor help

Cursor movement



  • h - move left

  • j - move down

  • k - move up

  • l - move right

  • w - jump by start of words (punctuation considered words)

  • W - jump by words (spaces separate words)

  • e - jump to end of words (punctuation considered words)

  • E - jump to end of words (no punctuation)

  • b - jump backward by words (punctuation considered words)

  • B - jump backward by words (no punctuation)

  • 0 - (zero) start of line

  • ^ - first non-blank character of line

  • $ - end of line

  • G - Go To command (prefix with number - 5G goes to line 5)


Note: Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.



Insert Mode - Inserting/Appending text



  • i - start insert mode at cursor

  • I - insert at the beginning of the line

  • a - append after the cursor

  • A - append at the end of the line

  • o - open (append) blank line below current line (no need to press return)

  • O - open blank line above current line

  • ea - append at end of word

  • Esc - exit insert mode



Editing



  • r - replace a single character (does not use insert mode)

  • J - join line below to the current one

  • cc - change (replace) an entire line

  • cw - change (replace) to the end of word

  • c$ - change (replace) to the end of line

  • s - delete character at cursor and subsitute text

  • S - delete line at cursor and substitute text (same as cc)

  • xp - transpose two letters (delete and paste, technically)

  • u - undo

  • . - repeat last command



Marking text (visual mode)



  • v - start visual mode, mark lines, then do command (such as y-yank)

  • V - start Linewise visual mode

  • o - move to other end of marked area

  • Ctrl+v - start visual block mode

  • O - move to Other corner of block

  • aw - mark a word

  • ab - a () block (with braces)

  • aB - a {} block (with brackets)

  • ib - inner () block

  • iB - inner {} block

  • Esc - exit visual mode



Visual commands



  • > - shift right

  • < - shift left

  • y - yank (copy) marked text

  • d - delete marked text

  • ~ - switch case



Cut and Paste



  • yy - yank (copy) a line

  • 2yy - yank 2 lines

  • yw - yank word

  • y$ - yank to end of line

  • p - put (paste) the clipboard after cursor

  • P - put (paste) before cursor

  • dd - delete (cut) a line

  • dw - delete (cut) the current word

  • x - delete (cut) current character



Exiting



  • :w - write (save) the file, but don't exit

  • :wq - write (save) and quit

  • :q - quit (fails if anything has changed)

  • :q! - quit and throw away changes



Search/Replace



  • /pattern - search for pattern

  • ?pattern - search backward for pattern

  • n - repeat search in same direction

  • N - repeat search in opposite direction

  • :%s/old/new/g - replace all old with new throughout file

  • :%s/old/new/gc - replace all old with new throughout file with confirmations



Working with multiple files



  • :e filename - Edit a file in a new buffer

  • :bnext (or :bn) - go to next buffer

  • :bprev (of :bp) - go to previous buffer

  • :bd - delete a buffer (close a file)

  • :sp filename - Open a file in a new buffer and split window

  • ctrl+ws - Split windows

  • ctrl+ww - switch between windows

  • ctrl+wq - Quit a window

  • ctrl+wv - Split windows vertically





Another good vim commands cheatsheet and a
vi introduction using the "cheat sheet" method