You are on page 1of 46

JUnit Tutorial

Lars Vogel

Version 1.4

Copyright 2007 - 2011 Lars Vogel

21.08.2011

Revision History Revision 0.1-0.5 JUnit description Revision 0.6 - 1.4 bugfixes and enhancements 10.05.2008 - 21.08.2011 Lars Vogel 03.09.2007 Lars Vogel

Unit testing with JUnit

This tutorial explains unit testing with JUnit 4.x. It explains the creation of JUnit tests and how to run them in Eclipse or via own code.

Table of Contents

1. Introduction 1.1. Unit Testing 1.2. Unit Testing with JUnit 1.3. Installation of JUnit 2. JUnit with Eclipse 2.1. Preparation 2.2. Create a Java class 2.3. Create a JUnit test 2.4. Run your test via Eclipse 2.5. Run your test via code 3. JUnit (more) in Detail 3.1. Static imports with Eclipse

3.2. Annotations 3.3. Assert statements 4. Thank you 5. Questions and Discussion 6. Links and Literature 6.1. JUnit Resources 6.2. vogella Resources

1. Introduction

1.1. Unit Testing

A unit test is a piece of code written by a developer that tests a specific functionality in the code which is tested. Unit tests can ensure that functionality is working and can be used to validate that this functionality still works after code changes.

Unit testing uses also mocking of objects. To learn more about mock frameworks please see EasyMock Tutorial

1.2. Unit Testing with JUnit

JUnit 4.x is a test framework which uses annotation to identify the methods which contain tests. JUnit assumes that all test methods can be performed in an arbitrary order. Therefore tests should not depend other tests. To write a test with JUnit

Annotate a method with @org.JUnit.Test Use a method provides by JUnit to check the expected result of the code execution versus the actual result

You use a tool like Eclipse or the class "org.junit.runner.JUnitCore" to run the test.

1.3. Installation of JUnit

Download JUnit4.x.jar from the JUnit website . The download contains the "junit-4.*.jar" which is the JUnit library. Add this library to your Java project and add it to the classpath. See Eclipse IDE Tutorial to learn how to do this in Eclipse.

2. JUnit with Eclipse

2.1. Preparation

Create a new project "de.vogella.junit.first". We want to create the unit tests in a separate folder. Create therefore a new source folder "test" via right mouse click on your project, select properties and choose the "Java Build Path". Select the tab source code.

Press "Add folder" then then press "Create new folder". Create the folder "test".

The creation of an separate folder for the test is not mandatory. But it is good advice to keep the test coding separate from the normal coding.

2.2. Create a Java class

Create a package "de.vogella.junit.first" and the following class. package de.vogella.junit.first;

public class MyClass {

public int multiply(int x, int y) {

return x / y;

2.3. Create a JUnit test

Select your new class, right mouse click and select New ->JUnit Test case, change the source folder to JUnit. Select "New JUnit 4 test". Make sure you change the source folder to test.

Press next and select the methods which you want to test.

If you have not yet JUnit in your classpath, Eclipse will asked you if it should be added to the classpath.

Create a test with the following code.

package de.vogella.junit.first;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyClassTest {

@Test

public void testMultiply() {

MyClass tester = new MyClass();

assertEquals("Result", 50, tester.multiply(10, 5));

2.4. Run your test via Eclipse

Right click on your new test class and select Run-As-> Junit Test.

The test should be failing (indicated via a red bar). This is due to the fact that our multiplier class is currently not working correctly (it does a division instead of multiplication). Fix the bug and re-run test to get a green light.

If you have several tests you can combine them into a test suite. All test in this test suite will then be executed if you run the test suite. To create a new test suite, select your test classes, right mouse click-> New-> Other -> JUnit -Test Suite

Select next and select the methods you would like to have test created for.

This does currently not work for JUnit4.0 testcases. See Bug Report

Change the coding to the following to make your test suite run your test. If you later develop another test you can add it to @Suite.SuiteClasses package mypackage;

import org.junit.runner.RunWith;

import org.junit.runners.Suite;

@RunWith(Suite.class)

@Suite.SuiteClasses( { MyClassTest.class })

public class AllTests {

2.5. Run your test via code

You can also run your test via your own coding. The class "org.junit.runner.JUnitCore" provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of type "org.junit.runner.Result". This object can be used to retrieve information about the tests and provides information about the failed tests.

Create in your "test" folder a new class "MyTestRunner" with the following coding. This class will execute your test class and write potential failures to the console. package de.vogella.junit.first;

import org.junit.runner.JUnitCore;

import org.junit.runner.Result;

import org.junit.runner.notification.Failure;

public class MyTestRunner {

public static void main(String[] args) {

Result result = JUnitCore.runClasses(MyClassTest.class);

for (Failure failure : result.getFailures()) {

System.out.println(failure.toString());

3. JUnit (more) in Detail

3.1. Static imports with Eclipse

JUnit uses a lot of static methods and Eclipse cannot automatically import static imports. You can make the JUnit test methods available via the content assists.

Open the Preferences via Window -> Preferences and select Java > Editor > Content Assist > Favorites. Add then via "New Member" the methods you need. For example this makes the assertTrue, assertFalse and assertEquals method available.

You can now use Content Assist (Ctrl+Space) to add the method and the import.

I suggest to add at least the following new members.

org.junit.Assert.assertTrue org.junit.Assert.assertFalse org.junit.Assert.assertEquals org.junit.Assert.fail

3.2. Annotations

The following give an overview of the available annotations in JUnit 4.x

Table 1. Annotations

Annotation @Test public void method() @Before public void method()

Description Annotation @Test identifies that this method is a test method. Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class)

@After public void method() @BeforeClass public void method()

Test method must start with test Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database

@AfterClass public void method()

Will perform the method after all tests have finished. This can be used to perform

Annotation

Description clean-up activities for example be used to disconnect to a database

@Ignore

Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included.

@Test(expected=IllegalArgumentException.class) Tests if the method throws the named exception @Test(timeout=100) Fails if the method takes longer then 100 milliseconds

3.3. Assert statements

The following gives an overview of the available test methods:

Table 2. Test methods

Statement fail(String)

Description Let the method fail, might be usable to check that a certain part of the code is not reached.

assertTrue(true);

True

assertsEquals([String message], expected, actual) Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays assertsEquals([String message], expected, actual, Usage for float and double; the tolerance are the number of decimals which tolerance) assertNull([message], object) assertNotNull([message], object) assertSame([String], expected, actual) assertNotSame([String], expected, actual) assertTrue([message], boolean condition) must be the same Checks if the object is null Check if the object is not null Check if both variables refer to the same object Check that both variables refer not to the same object Check if the boolean condition is true.

4. Thank you

Please help me to support this article:

5. Questions and Discussion

Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you.

6. Links and Literature

6.1. JUnit Resources

http://www.junit.org/ JUnit Homepage

6.2. vogella Resources

Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system

Testing with EasyMock - Tutorial

Lars Vogel

Version 0.4

Copyright 2011 Lars Vogel

14.06.2011

Revision History Revision 0.1 created Revision 0.2 - 0.4 bug fixed and enhancements 06.02.2010 - 14.06.2011 Lars Vogel 06.02.2010 Lars Vogel

Testing with EasyMock

This article explains testing with the EasyMock framework within Eclipse. It is based on EasyMock 3.0 but should also work on later versions.

Table of Contents

1. EasyMock and Mock Objects Overview 1.1. Testing and Mock Objects 1.2. EasyMock 2. Using Easy Mock and Junit 3. Thank you 4. Questions and Discussion 5. Links and Literature 5.1. Performance

1. EasyMock and Mock Objects Overview

The following is based on an understanding JUnit . In case your are not familiar with JUnit please check the following JUnit Tutorial .

1.1. Testing and Mock Objects

Unit testing is defined as testing classes or methods in isolation. Java classes usually depend on other classes. A mock object is a dummy interface or class in which you define the dummy output of a certain method call. These objects should be provided to the class which is tested. Therefore the class to be tested should to avoid any hard dependency to external data. The classical example is a mock object for a data provider. In production a real database is used but for testing a mock object simulates the database and ensures that the test conditions are always the same.

To unit test your class you need to simulate /control the other classes. The best way is to provide mocks to the class which should be tested. The can either program these classes manually or use a mock framework to simulate these classes.

1.2. EasyMock

EasyMock is a popular mock framework which can be easily used in conjunction with JUnit . The following demonstrates the usage of EasyMock.

2. Using Easy Mock and Junit

Download EasyMock from the EasyMock Homepage and add the easymock.jar to your classpath. You also need to download Objenesis and Cglib and add there jars to your classpath.

Create a new Java Project JavaMockTest. Create the following classes. The class IncomeCalculator should be tested. The class has the purpose to calculate based on the provided method and position the salary of a person. Obviously the test depends on the provided methods. package income;

public enum Position {

BOSS, PROGRAMMER, SURFER

package income.exceptions;

public class PositionException extends RuntimeException {

private static final long serialVersionUID = 1L;

public PositionException(String message) {

super(message);

package income.exceptions;

public class CalcMethodException extends RuntimeException {

private static final long serialVersionUID = 1L;

public CalcMethodException(String message) {

super(message);

package income.method;

import income.Position;

public interface ICalcMethod {

public abstract double calc(Position position);

package income;

import income.exceptions.CalcMethodException;

import income.exceptions.PositionException;

import income.method.ICalcMethod;

public class IncomeCalculator{

private ICalcMethod calcMethod;

private Position position;

public void setCalcMethod(ICalcMethod calcMethod){

this.calcMethod = calcMethod;

public void setPosition(Position position){

this.position = position;

public double calc (){

if (calcMethod==null){

throw new CalcMethodException("CalcMethod not yet maintained");

if (position==null){

throw new PositionException("Position not yet maintained");

return calcMethod.calc(position);

Using Eclipse JUnit functionality create a new test for IncomeCalulator. In my example I did also create a new source folder "test" before in which I place the test classes.

Here is the test using EasyMock. package income;

import static org.junit.Assert.assertEquals;

import static org.junit.Assert.fail;

import income.exceptions.CalcMethodException;

import income.exceptions.PositionException;

import income.method.ICalcMethod;

import org.easymock.EasyMock;

import org.junit.Before;

import org.junit.Test;

public class IncomeCalculatorTest {

private ICalcMethod calcMethod;

private IncomeCalculator calc;

@Before

public void setUp() throws Exception {

calcMethod = EasyMock.createMock(ICalcMethod.class);

calc = new IncomeCalculator();

@Test

public void testCalc1() {

// Setting up the expected value of the method call calc

EasyMock.expect(calcMethod.calc(Position.BOSS)).andReturn(70000.0).times(2);

EasyMock.expect(calcMethod.calc(Position.PROGRAMMER)).andReturn(50000.0);

// Setup is finished need to activate the mock

EasyMock.replay(calcMethod);

calc.setCalcMethod(calcMethod);

try {

calc.calc();

fail("Exception did not occur");

} catch (PositionException e) {}

calc.setPosition(Position.BOSS);

assertEquals(70000.0, calc.calc());

assertEquals(70000.0, calc.calc());

calc.setPosition(Position.PROGRAMMER);

assertEquals(50000.0, calc.calc());

calc.setPosition(Position.SURFER);

EasyMock.verify(calcMethod);

@Test(expected = CalcMethodException.class)

public void testNoCalc() {

calc.setPosition(Position.SURFER);

calc.calc();

@Test(expected = PositionException.class)

public void testNoPosition() {

EasyMock.expect(calcMethod.calc(Position.BOSS)).andReturn(70000.0);

EasyMock.replay(calcMethod);

calc.setCalcMethod(calcMethod);

calc.calc();

@Test(expected = PositionException.class)

public void testCalc2() {

// Setting up the expected value of the method call calc

EasyMock.expect(calcMethod.calc(Position.SURFER)).andThrow(

new PositionException("Don't know this guy")).times(1);

// Setup is finished need to activate the mock

EasyMock.replay(calcMethod);

calc.setPosition(Position.SURFER);

calc.setCalcMethod(calcMethod);

calc.calc();

The expect method tells easy mock to expect a certain method with certain arguments. andReturn defines the return value of this method. The method times defines how often the Mock object will be called.

The reply method needs to be called to make the Mock object available.

After execution of the test you can call the method verify to check if the Mock Object was called as defined.

3. Thank you

Please help me to support this article:

. Questions and Discussion

Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you.

5. Links and Literature

5.1. Performance

https://www.ibm.com/developerworks/java/library/j-jtp09196/ Java theory and practice: Instrumenting applications with JMX

Java Regex Tutorial

Lars Vogel

Version 1.1

Copyright 2007 - 2011 Lars Vogel

25.06.2011

Revision History Revision 0.1 created Revision 0.2 - 1.1 30.12.2008 - 25.06.2011 Lars Vogel 07.12.2007 Lars Vogel

Java and Regular Expressions

This article gives an overview of the usage of regular expressions in general and describes the usage of regular expressions with Java. It also provides several Java regular expression examples.

Table of Contents

1. Regular Expressions 1.1. Overview 1.2. Usage 1.3. Junit 2. Regular Expressions 2.1. Common matching symbols 2.2. Metacharacters 2.3. Quantifier 3. Using Regular Expressions with String.matches()

3.1. Overview 3.2. Examples 4. Pattern and Matcher 5. Java Regex Examples 5.1. Or 5.2. Phone number 5.3. Check for a certain number range 5.4. Building a link checker 6. Thank you 7. Questions and Discussion 8. Links and Literature

1. Regular Expressions

1.1. Overview

A regular expression define a search pattern for strings. This pattern may match one or several times or not at all for a given string. The abbreviation for regular expression is "regex".

A simple example for a regular expression is a (literal) string. For example the regex "Hello World" will match exactly the phrase "Hello World". Another example for a regular expression is "." (dot) which matches any single character; it would match for example "a" or "z" or "1".

1.2. Usage

Regular expressions can be used to search, edit and manipulate text.

Regular expressions are used in several programming languages, e.g. Java but also Perl, Groovy, etc. Unfortunately each language / program supports regex slightly different.

The pattern defined by the regular expression is applied on the string from left to right. Once a source character has been used in a match, it cannot be reused. For example the regex "aba" will match "ababababa" only two times (aba_aba__).

1.3. Junit

Some of the following examples use JUnit to validate the result. You should be able to adjust them in case if you don't want to use JUnit. To learn about JUnit please see JUnit Tutorial .

2. Regular Expressions

The following is an overview of regular expressions. This chapter is supposed to be a references for the different regex elements.

2.1. Common matching symbols

Table 1.

Regular Expression . ^regex regex$ [abc] [abc][vz] [^abc]

Description

Matches any sign regex must match at the beginning of the line Finds regex must match at the end of the line Set definition, can match the letter a or b or c Set definition, can match a or b or c followed by either v or z When a "^" appears as the first character inside [] when it negates the pattern. This can match any character except a or b or c

[a-d1-7] X|Z XZ $

Ranges, letter between a and d and figures from 1 to 7, will not match d1 Finds X or Z Finds X directly followed by Z Checks if a line end follows

2.2. Metacharacters

The following metacharacters have a pre-defined meaning and make certain common pattern easier to use, e.g. d instead of [0..9].

Table 2.

Regular Expression \d \D \s \S

Description Any digit, short for [0-9] A non-digit, short for [^0-9] A whitespace character, short for [ \t\n\x0b\r\f] A non-whitespace character, for short for [^\s]

Regular Expression \w \W \S+

Description A word character, short for [a-zA-Z_0-9] A non-word character [^\w] Several non-whitespace characters

2.3. Quantifier

A quantifier defines how often an element can occur. The symbols ?, *, + and {} define the quantity of the regular expressions

Table 3.

Regular Expression *

Description

Examples

Occurs zero or more times, is short for {0,}

X* - Finds no or several letter X, .* - any character sequence

+ ? {X}

Occurs one or more times, is short for {1,} Occurs no or one times, ? is short for {0,1} Occurs X number of times, {} describes the order of the preceding liberal

X+ - Finds one or several letter X X? -Finds no or exactly one letter X \d{3} - Three digits, .{10} - any character sequence of length 10 \d{1,4}- \d must occur at least once and at a maximum of four

{X,Y}

.Occurs between X and Y times,

*?

? after a qualifier makes it a "reluctant quantifier", it tries to find the smallest match.

3. Using Regular Expressions with String.matches()

3.1. Overview

Strings in Java have build in support for regular expressions. Stings have three build in methods for regular expressions. These methods do not compile the pattern and are therefore slower then using a pattern and a matcher as described later in this article.

The backslash is an escape character in Java Strings. e.g. backslash has a predefine meaning in Java. You have to use "" to define a single backslash. If you want to define "w" then you must be using "w" in your regex. If you want to use backslash you as a literal you have to type as is also a escape charactor in regular expressions.

Table 4.

Method s.matches("regex") s.split("regex")

Description Evaluates if "regex" matches s. Returns only true if the WHOLE string can be matched Creates array with substrings of s divided at occurance of "regex". "regex" is not included in the result.

s.replace("regex"), "replacement"

Replaces "regex" with "replacement

Create for the following example the Java project "de.vogella.regex.test". package de.vogella.regex.test;

public class RegexTestStrings {

public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";

public static void main(String[] args) {

System.out.println(EXAMPLE_TEST.matches("w.*"));

String[] splitString = (EXAMPLE_TEST.split("s+"));

System.out.println(splitString.length);// Should be 14

for (String string : splitString) {

System.out.println(string);

// Replace all whitespace with tabs

System.out.println(EXAMPLE_TEST.replaceAll("s+", "t"));

3.2. Examples

Create for the following example the Java project "de.vogella.regex.string".

The following class gives several examples for the usage of regular expressions with strings. See the comment for the purpose. package de.vogella.regex.string;

public class StringMatcher {

// Returns true if the string matches exactly "true"

public boolean isTrue(String s){

return s.matches("true");

// Returns true if the string matches exactly "true" or "True"

public boolean isTrueVersion2(String s){

return s.matches("[tT]rue");

// Returns true if the string matches exactly "true" or "True"

// or "yes" or "Yes"

public boolean isTrueOrYes(String s){

return s.matches("[tT]rue|[yY]es");

// Returns true if the string contains exactly "true"

public boolean containsTrue(String s){

return s.matches(".*true.*");

// Returns true if the string contains of three letters

public boolean isThreeLetters(String s){

return s.matches("[a-zA-Z]{3}");

// Simpler from for

//

return s.matches("[a-Z][a-Z][a-Z]");

// Returns true if the string does not have a number at the beginning

public boolean isNoNumberAtBeginning(String s){

return s.matches("^[^d].*");

// Returns true if the string contains a arbitrary number of characters except b

public boolean isIntersection(String s){

return s.matches("([w&&[^b]])*");

// Returns true if the string contains a number less then 300

public boolean isLessThenThreeHundret(String s){

return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*");

And a small JUnit Test to validates the examples. package de.vogella.regex.string;

import org.junit.Before;

import org.junit.Test;

import static org.junit.Assert.assertFalse;

import static org.junit.Assert.assertTrue;

public class StringMatcherTest {

private StringMatcher m;

@Before

public void setup(){

m = new StringMatcher();

@Test

public void testIsTrue() {

assertTrue(m.isTrue("true"));

assertFalse(m.isTrue("true2"));

assertFalse(m.isTrue("True"));

@Test

public void testIsTrueVersion2() {

assertTrue(m.isTrueVersion2("true"));

assertFalse(m.isTrueVersion2("true2"));

assertTrue(m.isTrueVersion2("True"));;

@Test

public void testIsTrueOrYes() {

assertTrue(m.isTrueOrYes("true"));

assertTrue(m.isTrueOrYes("yes"));

assertTrue(m.isTrueOrYes("Yes"));

assertFalse(m.isTrueOrYes("no"));

@Test

public void testContainsTrue() {

assertTrue(m.containsTrue("thetruewithin"));

@Test

public void testIsThreeLetters() {

assertTrue(m.isThreeLetters("abc"));

assertFalse(m.isThreeLetters("abcd"));

@Test

public void testisNoNumberAtBeginning() {

assertTrue(m.isNoNumberAtBeginning("abc"));

assertFalse(m.isNoNumberAtBeginning("1abcd"));

assertTrue(m.isNoNumberAtBeginning("a1bcd"));

assertTrue(m.isNoNumberAtBeginning("asdfdsf"));

@Test

public void testisIntersection() {

assertTrue(m.isIntersection("1"));

assertFalse(m.isIntersection("abcksdfkdskfsdfdsf"));

assertTrue(m.isIntersection("skdskfjsmcnxmvjwque484242"));

@Test

public void testLessThenThreeHundret() {

assertTrue(m.isLessThenThreeHundret("288"));

assertFalse(m.isLessThenThreeHundret("3288"));

assertFalse(m.isLessThenThreeHundret("328 8"));

assertTrue(m.isLessThenThreeHundret("1"));

assertTrue(m.isLessThenThreeHundret("99"));

assertFalse(m.isLessThenThreeHundret("300"));

4. Pattern and Matcher

For advanced regular expressions the classes you java.util.regex.Pattern and java.util.regex.Matcher are used.

You first create a Pattern object which defines the regular expression. This pattern object allows create a Matcher object for a given string. This matcher object then allows you to do regex operations on the string. package de.vogella.regex.test;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegexTestPatternMatcher {

public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";

public static void main(String[] args) {

Pattern pattern = Pattern.compile("w+");

// In case you would like to ignore case sensitivity you could use this

// statement

// Pattern pattern = Pattern.compile("s+", Pattern.CASE_INSENSITIVE);

Matcher matcher = pattern.matcher(EXAMPLE_TEST);

// Check all occurance

while (matcher.find()) {

System.out.print("Start index: " + matcher.start());

System.out.print(" End index: " + matcher.end() + " ");

System.out.println(matcher.group());

// Now create a new pattern and matcher to replace whitespace with tabs

Pattern replace = Pattern.compile("s+");

Matcher matcher2 = replace.matcher(EXAMPLE_TEST);

System.out.println(matcher2.replaceAll("t"));

5. Java Regex Examples

5.1. Or

Task: Write a regular expression which matches a text line if this text line contains either the word "Joe" or the word "Jim" or both. Create a project "de.vogella.regex.eitheror" and the following class. package de.vogella.regex.eitheror;

import org.junit.Test;

import static org.junit.Assert.assertFalse;

import static org.junit.Assert.assertTrue;

public class EitherOrCheck {

@Test

public void testSimpleTrue() {

String s = "humbapumpa jim";

assertTrue(s.matches(".*(jim|joe).*"));

s = "humbapumpa jom";

assertFalse(s.matches(".*(jim|joe).*"));

s = "humbaPumpa joe";

assertTrue(s.matches(".*(jim|joe).*"));

s = "humbapumpa joe jim";

assertTrue(s.matches(".*(jim|joe).*"));

5.2. Phone number

Task: Write a regular expression which matches any phone number. A phone number in this example consists either out of 7 numbers in a row or out of 3 number a (white)space or a dash and then 4 numbers. package de.vogella.regex.phonenumber;

import org.junit.Test;

import static org.junit.Assert.assertFalse;

import static org.junit.Assert.assertTrue;

public class CheckPhone {

@Test

public void testSimpleTrue() {

String pattern = "ddd([,s])?dddd";

String s= "1233323322";

assertFalse(s.matches(pattern));

s = "1233323";

assertTrue(s.matches(pattern));

s = "123 3323";

assertTrue(s.matches(pattern));

5.3. Check for a certain number range

The following example will check if a text contains a number with 3 digits.

Create the Java project "de.vogella.regex.numbermatch" and the following class. package de.vogella.regex.numbermatch;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import org.junit.Test;

import static org.junit.Assert.assertFalse;

import static org.junit.Assert.assertTrue;

public class CheckNumber {

@Test

public void testSimpleTrue() {

String s= "1233";

assertTrue(test(s));

s= "0";

assertFalse(test(s));

s = "29 Kasdkf 2300 Kdsdf";

assertTrue(test(s));

s = "99900234";

assertTrue(test(s));

public static boolean test (String s){

Pattern pattern = Pattern.compile("d{3}");

Matcher matcher = pattern.matcher(s);

if (matcher.find()){

return true;

return false;

5.4. Building a link checker

The following exampleallows to extract all valid links from a webpage. It does not consider links with start with "javascript:" or "mailto:".

Create the Java project "de.vogella.regex.weblinks" and the following class package de.vogella.regex.weblinks;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class LinkGetter {

private Pattern htmltag;

private Pattern link;

private final String root;

public LinkGetter(String root) {

this.root = root;

htmltag = Pattern.compile("<ab[^>]*href="[^>]*>(.*?)</a>");

link = Pattern.compile("href="[^>]*">");

public List<String> getLinks(String url) {

List<String> links = new ArrayList<String>();

try {

BufferedReader bufferedReader = new BufferedReader(

new InputStreamReader(new URL(url).openStream()));

String s;

StringBuilder builder = new StringBuilder();

while ((s = bufferedReader.readLine()) != null) {

builder.append(s);

Matcher tagmatch = htmltag.matcher(builder.toString());

while (tagmatch.find()) {

Matcher matcher = link.matcher(tagmatch.group());

matcher.find();

String link = matcher.group().replaceFirst("href="", "")

.replaceFirst("">", "");

if (valid(link)) {

links.add(makeAbsolute(url, link));

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

return links;

private boolean valid(String s) {

if (s.matches("javascript:.*|mailto:.*")) {

return false;

return true;

private String makeAbsolute(String url, String link) {

if (link.matches("http://.*")) {

return link;

if (link.matches("/.*") && url.matches(".*$[^/]")) {

return url + "/" + link;

if (link.matches("[^/].*") && url.matches(".*[^/]")) {

return url + "/" + link;

if (link.matches("/.*") && url.matches(".*[/]")) {

return url + link;

if (link.matches("/.*") && url.matches(".*[^/]")) {

return url + link;

throw new RuntimeException("Cannot make the link absolute. Url: " + url

+ " Link " + link);

JAXB Tutorial

Lars Vogel

Version 1.3

Copyright 2008 - 2011 Lars Vogel

08.03.2011

Revision History Revision 0.1 created Revision 0.2 - 1.3 bug fixes and enhancements 21.10.2008 - 08.03.2011 Lars Vogel 26.02.2008 Lars Vogel

JAXB Tutorial

This tutorial give an introduction to Java Architecture for XML Binding (JAXB). This tutorial is based on Java 6.0.

This article is based on Java 6.0.

Table of Contents

1. Overview 2. JAXB 2 - Java Architecture for XML Binding 2.1. Overview 2.2. Usage 3. Thank you 4. Questions and Discussion 5. Links and Literature 5.1. Source Code 5.2. Links and Literature 5.3. vogella Resources

1. Overview

Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted to/from XML (specified using a standard set of mappings. JAXB defines a programmer API for reading and writing Java objects to / from XML documents and a service provider which / from from XML documents allows the selection of the JAXB implementation JAXB applies a lot of defaults thus making reading and writing of XML via Java very easy.

The following will explain the JAXB interface, for an introduction into using XML with Java please see Java XML tutorial .

2. JAXB 2 - Java Architecture for XML Binding

2.1. Overview

JAXB uses annotations to indicate the central elements.

Table 1.

Annotation @XmlRootElement(namespace = "namespace") @XmlType(propOrder = { "field2", "field1",.. }) @XmlElement(name = "neuName")

Description Define the root element for a XML tree

Allows to define the order in which the fields are written in the XML file

Define the XML element which will be used. Only need to be used if the neuNeu is different then the JavaBeans Name

2.2. Usage

Create a new Java project called "de.vogella.xml.jaxb".

Create the following domain model with the JAXB annotations. package de.vogella.xml.jaxb.model;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")

// If you want you can define the order in which the fields are written

// Optional

@XmlType(propOrder = { "author", "name", "publisher", "isbn" })

public class Book {

private String name;

private String author;

private String publisher;

private String isbn;

// If you like the variable name, e.g. "name", you can easily change this

// name for your XML-Output:

@XmlElement(name = "bookName")

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getAuthor() {

return author;

public void setAuthor(String author) {

this.author = author;

public String getPublisher() {

return publisher;

public void setPublisher(String publisher) {

this.publisher = publisher;

public String getIsbn() {

return isbn;

public void setIsbn(String isbn) {

this.isbn = isbn;

package de.vogella.xml.jaxb.model;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlElementWrapper;

import javax.xml.bind.annotation.XmlRootElement;

//This statement means that class "Bookstore.java" is the root-element of our example

@XmlRootElement(namespace = "de.vogella.xml.jaxb.model")

public class Bookstore {

// XmLElementWrapper generates a wrapper element around XML representation

@XmlElementWrapper(name = "bookList")

// XmlElement sets the name of the entities

@XmlElement(name = "book")

private ArrayList<Book> bookList;

private String name;

private String location;

public void setBookList(ArrayList<Book> bookList) {

this.bookList = bookList;

public ArrayList<Book> getBooksList() {

return bookList;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getLocation() {

return location;

public void setLocation(String location) {

this.location = location;

Create the following test program for writing and reading the XML file. package test;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.io.Writer;

import java.util.ArrayList;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Marshaller;

import javax.xml.bind.Unmarshaller;

import de.vogella.xml.jaxb.model.Book;

import de.vogella.xml.jaxb.model.Bookstore;

public class BookMain {

private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

public static void main(String[] args) throws JAXBException, IOException {

ArrayList<Book> bookList = new ArrayList<Book>();

// create books

Book book1 = new Book();

book1.setIsbn("978-0060554736");

book1.setName("The Game");

book1.setAuthor("Neil Strauss");

book1.setPublisher("Harpercollins");

bookList.add(book1);

Book book2 = new Book();

book2.setIsbn("978-3832180577");

book2.setName("Feuchtgebiete");

book2.setAuthor("Charlotte Roche");

book2.setPublisher("Dumont Buchverlag");

bookList.add(book2);

// create bookstore, assigning book

Bookstore bookstore = new Bookstore();

bookstore.setName("Fraport Bookstore");

bookstore.setLocation("Frankfurt Airport");

bookstore.setBookList(bookList);

// create JAXB context and instantiate marshaller

JAXBContext context = JAXBContext.newInstance(Bookstore.class);

Marshaller m = context.createMarshaller();

m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

m.marshal(bookstore, System.out);

Writer w = null;

try {

w = new FileWriter(BOOKSTORE_XML);

m.marshal(bookstore, w);

} finally {

try {

w.close();

} catch (Exception e) {

// get variables from our xml file, created before

System.out.println();

System.out.println("Output from our XML File: ");

Unmarshaller um = context.createUnmarshaller();

Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(

BOOKSTORE_XML));

for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {

System.out.println("Book " + (i + 1) + ": "

+ bookstore2.getBooksList().get(i).getName() + " from "

+ bookstore2.getBooksList().get(i).getAuthor());

If you run the BookMain a XML file will be created from the object. Afterwards the file is read again and the object are created again.

You might also like