September 6, 2015

Simple Login Module in JBoss EAP 6 for Testing

Introduction

When testing locally or in integration tests, it is convenient to use a simple login module. Source code.

Configuration

<subsystem xmlns="urn:jboss:domain:security:1.2">
    <security-domains>
        ...
        <security-domain name="simple-policy" cache-type="default">
            <authentication>
                <login-module code="org.jboss.security.auth.spi.SimpleServerLoginModule" flag="required"/>
            </authentication>
        </security-domain>
    </security-domains>
</subsystem>

Test Web App

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
 
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Secure Content</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>

        <auth-constraint>
            <role-name>user</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>simple-policy</realm-name>
    </login-config>

    <security-role>
        <role-name>user</role-name>
    </security-role>
</web-app>

WEB-INF/jboss-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <context-root>/example-webapp</context-root>
    <security-domain>java:/jaas/simple-policy</security-domain>
</jboss-web>

August 23, 2015

How to Set Default JVM on Ubuntu

If your system has more than one version of Java, configure which one your system uses by entering the following command in a terminal window

$ sudo update-alternatives --config java

August 12, 2015

How to Log SQL Statements, Parameters and Cache in Hibernate?

Introduction

Current implementation of Hibernate are:

  • Hibernate 4.2 implements JPA 2.0 (EE 6)
  • Hibernate 4.3+ implements JPA 2.1 (EE 7)

Logging

Do not set logging level in persistence.xml (hibernate.show_sql, hibernate.format_sql), instead use Log4J for changing logging level.

# Log all hibernate SQL DML statements as they are executed
log4j.logger.org.hibernate.SQL=TRACE
# Log all hibernate JDBC parameters
log4j.logger.org.hibernate.type=TRACE
# Log all hibernate second-level cache activity
log4j.logger.org.hibernate.cache=TRACE

You can put this in you src/test/resources/log4j.properties if you want more logging when writing or debugging your test cases.

Reference

August 11, 2015

What is Docker and Why is it Hot?

What is Docker?

It is the possible replacement for Virtualization.

What is the Difference between Virtualization and Docker?

Below is a good picture from https://www.docker.com/whatisdocker.
Docker Diagram Docker Diagram

So the difference between Virtualization and Docker is that everything runs locally on the same server, without the Virtualization overhead.

Example. Lets download a ready image from the Docker Hub (https://hub.docker.com/). You can either browse the Docker Hub via web browser or via command line.

$ sudo docker search tomcat
...
NAME                                        DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
tomcat                                      Apache Tomcat is an open source implementa...   203       [OK]       
consol/tomcat-7.0                           Tomcat 7.0.57, 8080, "admin/admin"              12                   [OK]
consol/tomcat-8.0                           Tomcat 8.0.15, 8080, "admin/admin"              10                   [OK]
...

Lets pick the official docker image. The first time you run a new Docker Image, it will download it and that will take a little while.

$ sudo docker run -it --rm -p 8888:8080 tomcat:8.0
...
10-Aug-2015 18:52:33.409 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
10-Aug-2015 18:52:33.413 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
10-Aug-2015 18:52:33.413 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 658 ms

And now try it by open http://localhost:8888.

So what happened? We started a new process.

$ ps -aux | grep -i docker
...
root     29569  0.0  0.0 222512 10728 pts/25   Sl+  21:19   0:00 docker run -it --rm -p 8888:8080 tomcat:8.0
...

And a new tomcat process.

$ ps -aux | grep -i java
...
root     29578  1.7  1.2 7172840 200552 pts/1  Ssl+ 21:19   0:04 /usr/bin/java -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/local/tomcat/endorsed -classpath /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat -Dcatalina.home=/usr/local/tomcat -Djava.io.tmpdir=/usr/local/tomcat/temp org.apache.catalina.startup.Bootstrap start
...

And for network. A new virtual bridge was created, which is basically a virtual router.

$ ifconfig
...
docker0   Link encap:Ethernet  HWaddr 56:84:7a:fe:97:99
...

Why is Docker Better?

  • Lower licensing costs. You only need ONE license for the virtualized server for ALL its virtual guests.
  • More RAM and CPU. With Docker all process runs on the server directly. No virtualization layer that steals resources.
  • Less disks. A virtual guest is at least 20 GB and a Docker image is around 300 MB, since no duplication of OS and all its libraries are needed.

How Does Docker Work?

Docker makes use of proven mature Linux technologies:

  • CPU and RAM - cgroups. With cgroups you can restrict how much a process can use of the CPU and RAM, much like the same way CPU and RAM is handled in virtualization.
  • Disks - namespaces. With namespaces you can isolate local file system and divide it much like a network filesystem.
  • Network - virtual ethernet bridge.

Common Docker Commands

# Lists all docker process
$ sudo docker ps -a

# Print detailed information of a Docker proccess
$ sudo docker inspect <ContainerID>

# List all local Docker images
$ sudo docker images

# Run Docker image
$ sudo docker run -p <host_port1>:<container_port1> -p <host_port2>:<container_port2>

# Search for a ready Docker image at Docker Hub (https://registry.hub.docker.com/)
$ sudo docker search <SearchString>

Installation on Ubuntu 14.04

Install docker.

$ sudo apt-get install docker.io

Test the installation.

$ sudo docker run hello-world
Hello from Docker.
This message shows that your installation appears to be working correctly.
...

Reference

July 17, 2015

Getting Started with Mockito

Introduction

To create effective unit test, they should be fast. But also you might need to mock object out to be able to write unit tests. The most common library to use for mocking is mockito.

Example: Mock expected results

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testIterator() throws Exception {
        Iterator mock = mock(Iterator.class);
        when(mock.next()).thenReturn("Hello").thenReturn("World");
        assertThat("Hello World", is(equalTo(mock.next() + " " + mock.next())));
    }

Example: Mock expected result with input

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testArrayList() throws Exception {
        ArrayList mock = mock(ArrayList.class);
        when(mock.get(1)).thenReturn("Foo");
        assertThat("Foo", is(equalTo(mock.get(1))));
    }

Example: Mock expected results with any input

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testArrayListAny() throws Exception {
        ArrayList mock = mock(ArrayList.class);
        when(mock.get(anyInt())).thenReturn("Foo");
        assertThat("Foo", is(equalTo(mock.get(1))));
    }

Example: Mock and expect exception

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test(expected = IOException.class)
    public void testOutputStream() throws Exception {
        OutputStream mock = mock(OutputStream.class);
        doThrow(new IOException()).when(mock).close();
        mock.close();
    }

Example: Mock and verify that metods were invoked

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testOutputStreamVerify() throws Exception {
        OutputStream mock = mock(OutputStream.class);
        BufferedOutputStream fos = new BufferedOutputStream(mock);
        fos.close();
        verify(mock).close();
    }

Using Hamcrest with JUnit 4

Introduction

The latest JUnit 4 comes with a transitive dependency of hamcrest. What hamcrest brings to the table is to increase the readability of the test code. This is important because codes are often more read than written.

Example

@Test
public void testEqualTo() throws Exception {
    assertThat(Foo.hello(), is(equalTo("Hello World")));
}

Core

The starting point is org.junit.Assert.assertThat(T actual, Matcher matcher) and the matcher methods in org.hamcrest.CoreMatchers.*:

  • allOf()
  • any()
  • anyOf()
  • anything()
  • describedAs()
  • equalTo()
  • instanceOf()
  • is()
  • not()
  • notNullValue()
  • nullValue()
  • sameInstance()

allOf()

allOf() is a simple assertion that just says all of the matcher arguments must be true.

@Test
public void testAllOf() throws Exception {
    assertThat(Foo.hello(), is(allOf(notNullValue(), instanceOf(String.class), equalTo("Hello World"))));
}

any()

This matcher just checks that the actual result is a class of a certain type.

@Test
public void testAny() throws Exception {
    assertThat(Foo.hello(), is(any(String.class)));
}

anyOf()

If any of the matchers are true this assertion will pass.

@Test
public void testAnyOf() throws Exception {
    assertThat(Foo.hello(), is(anyOf(nullValue(), instanceOf(String.class), equalTo("Goodbye"))));
}

anything()

This matcher will always evaluates to true.

describedAs()

This allows you to override the default description for a matcher.

equalTo()

See above.

instanceOf()

Checks that you have an instance of a particular type.

is()

See above.

not()

Just reverses the outcome of a matcher.

@Test
public void testNot() throws Exception {
    assertThat(Foo.hello(), is(not("Bar")));
}

notNullValue()

Simply does a null check

nullValue()

Assert a null value.

sameInstance()

Assert two Objects are ==, i.e. NOT equals()

@Test
public void testSameInstance() throws Exception {
    assertThat(2 + 2, is(sameInstance(4)));
    assertThat(new Integer(2 + 2), is(not(sameInstance(new Integer(4)))));
}