Seiten

Freitag, 28. Februar 2014

Wildfly/JBoss: How to secure customer passwords

If you are familiar with Wildfly/JBoss you might now that you can easily configure your system to use JAAS database authentication for the login process of your customer. Because it is considered bad practice to store passwords in clear text a hash-algorithm (e.g. SHA256, MD5) can be specified to encrypt them. Further informations can be found under here.

The problem with that approach is that your passwords will be vulnerable to dictionary and rainbowtable attacks (refresh your knowlegde here).
One way to face this problem is to use salted hashed passwords but the standard DatabaseServerLoginModule does not support that. But you can use this extension of the DatabaseServerLoginModule.
The configuration is fairly easy:

Wildfly/JBoss Konfiguration

1. Create module
Create the new module de.rtner.security.main and configure the module.xml like this
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="de.rtner.security">
    <resources>
        <resource-root path="PBKDF2-1.0.4.jar"/>
        <resource-root path="SaltedDatabaseLoginModule-1.0.4.jar"/>
    </resources>
   <dependencies>
        <module name="javax.api"/>
        <module name="javax.servlet.api"/>
        <module name="org.jboss.as.web-common"/>
        <module name="org.jboss.logging"/>
        <module name="org.picketbox"/>
        <module name="sun.jdk"/>
    </dependencies>
</module>
Both declared jars must also be present in that folder.

2. Update module.xml of picketbox.

Every custom login module has to be declared as a dependencies in the module.xml of picketbox. So just add this line:
<module name="de.rtner.security"/>
3. Update standalone.xml
<login-module code="de.rtner.security.auth.spi.SaltedDatabaseServerLoginModule" flag="required" module="de.rtner.security">
 <module-option name="dsJndiName" value="java:jboss/datasources/ExampleDS"/>
 <module-option name="principalsQuery" value="select password from User where login=?"/>
 <module-option name="rolesQuery" value="select role, 'Roles' from UserRole where login=?"/>
 <module-option name="hmacAlgorithm" value="HMacSHA256"/>
 <module-option name="formatter" value="de.rtner.security.auth.spi.PBKDF2HexFormatter"/>
 <module-option name="engine" value="de.rtner.security.auth.spi.PBKDF2Engine"/>
 <module-option name="engine-parameters" value="de.rtner.security.auth.spi.PBKDF2Parameters"/>
</login-module>

The password encryption can be done with the following function.
private String createPbKdF2Passwort(String password) throws NoSuchAlgorithmException
{
 PBKDF2Formatter formatter = new PBKDF2HexFormatter();
 SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
 byte[] salt = new byte[8];
 sr.nextBytes(salt);
 int iterations = 1000;
 PBKDF2Parameters p = new PBKDF2Parameters("HmacSHA256", "ISO-8859-1", salt, iterations);
 PBKDF2Engine e = new PBKDF2Engine(p);
 p.setDerivedKey(e.deriveKey(password));
 return formatter.toString(p);
}

Have fun coding.

Donnerstag, 20. Februar 2014

are you missing the ? operator from project coin?

How to get rid of 90% boiler plate code from NPE-save model - surfing?
What I am meaning with modell surfing? For example you have a class DemoClassA.
Inside DemoClassA you have an instance of DemoClassB.
Inside DemoClassB you have an instance of DemoClassC. And so on..

You need something like the following.

String value = demoClassA.getDemoClassB().getDemoClassC().getValue();
The bad thing is if your valid model could have ClassB or ClassC with null. You only have to show the value inside your GUI if the complete getter - cascade will be valid. The first would be something like this.

  
 DemoClassB valueB = demoClassA.getDemoClassB();
 if(demoB != null){
    DemoClassC demoC = demoB.getDemoClassC();
    if(demoC != null){
     String value = demoC.getValue();
    }
 }
A lot of booooring code. Project Coin had something with Wildcards.
 
 String value = demoClassA?.getDemoClassB()?.getDemoClassC()?.getValue();
 
This is really nice, but it was not accepted. So I had do something like this for myself.
One main point will be that the objects are ready initialized and I could not change the source code from this part. Other languages as plain Java are not allowed. No other frameworks, no AOP and something like this. Puuhh.. what else?
I was thinking about the newsletter nr 180 (http://www.javaspecialists.eu/archive/Issue180.html) from Heinz Kabutz. He explained how to generate static Proxy Classes. This was a good point to start from.
The key concept is the generating of Proxy Classes on the fly if they are needed. Via Reflection the real Subject is analysed and the Proxy generated. He is instanciating the new proxy class and the real subject with the default constructor. For my project this was not helpfull, because the model was grown over the last 10 years. Nearly no default constructor is available and the project owner was building something like a RMI Lazy Loading inside the persistent model. This model itself is used directly inside Swing.. hmmmmm nothing was I really want to use...
Changing the old code is very time consuming.
On the other side I was writing a lot of this if != null code.
So I decided to write a Proxy that I can use on initialized objects. This must be recursive to get the NPE save getter cascades. Based on Heinz code, I started to write a VirtualProxySourceGeneratorOnExistingObject to stop the instance creation on the real Subject.
public class VirtualProxySourceGeneratorOnExistingObject extends VirtualProxySourceGenerator {

    public VirtualProxySourceGeneratorOnExistingObject(
            Class subject, Class realSubject) {
        super(subject, realSubject, Concurrency.OnExistingObject);
    }
    protected void addRealSubjectCreation(PrintWriter out,  String name, String realName) {
        out.printf(" public %s realSubject;%n", name);
        out.println();
        out.printf(" private %s realSubject() {%n", name);
        out.println(" return realSubject;");
        out.println(" }");
    }
}  
After this I changed the VirtualProxySourceGeneratorto use this VirtualProxySourceGeneratorOnExistingObject and changed it in a way that a getter method will generate a new Proxy for the next realSubject.
public abstract class VirtualProxySourceGenerator {

    protected final Class subject;
    protected final Class realSubject;
    private final String proxy;
    private CharSequence charSequence;
    private Concurrency type;

    public VirtualProxySourceGenerator(
            Class subject, Class realSubject, Concurrency type) {
        this.subject = subject;
        this.realSubject = realSubject;
        this.type = type;
        this.proxy = makeProxyName(subject, type);

    }

    private static String makeProxyName(Class subject, Concurrency type) {
        return "$$_" + subject.getName().replace('.', '_') +
                "Proxy_" + Integer.toHexString(System.identityHashCode(
                subject.getClassLoader())) + "_" + type;
    }

    public String getProxyName() {
        return proxy;
    }

    public CharSequence getCharSequence() {
        if (charSequence == null) {
            StringWriter sw = new StringWriter();
            generateProxyClass(new PrintWriter(sw));
            charSequence = sw.getBuffer();
        }
        //System.out.println("charSequence = " + charSequence.toString());
        return charSequence;
    }

    private void generateProxyClass(PrintWriter out) {
        addClassDefinition(out);
        addProxyBody(out);
        out.close();
    }

    private void addProxyBody(PrintWriter out) {
        addRealSubjectCreation(out, subject.getName(), realSubject.getName());
        addProxiedMethods(out);
        out.println("}");
    }

    protected abstract void addRealSubjectCreation(PrintWriter out, String name, String realName);


    private void addClassDefinition(PrintWriter out) {
        addImports(out);
        out.printf("public class %s %s %s {%n",
                proxy, getInheritanceType(subject), subject.getName());
    }

    private String getInheritanceType(Class subject) {
        return subject.isInterface() ? "implements" : "extends";
    }

    protected void addImports(PrintWriter out) {

    }

    private void addToStringIfInterface(PrintWriter out) {
        if (subject.isInterface()) {
            out.println();
            out.println(" public String toString() {");
            out.println(" if(realSubject() == null ) return \"NullObjectHolder in \" + this.getClass() ;");
            out.println(" return realSubject().toString();");
            out.println(" }");
        }
    }

    private void addProxiedMethods(PrintWriter out) {
        for (Method m : subject.getMethods()) {
            addProxiedMethod(out, m);
        }
        addToStringIfInterface(out);
    }

    private void addProxiedMethod(PrintWriter out, Method m) {
        if (Modifier.isFinal(m.getModifiers())) return;
        addMethodSignature(out, m);
        addMethodBody(out, m);   //NPE da val ger getter gefuellt wird

        final Class returnType = m.getReturnType();
        if (returnType == void.class) out.printf(");%n }%n");
        else {
            out.printf(");%n");  //end of orig method.. start proxy additional stuff
            final boolean aFinal = Modifier.isFinal(returnType.getModifiers());
            if (!returnType.isPrimitive() && !returnType.isArray() && ! aFinal ){
                final String typeName = returnType.getTypeName();
                final String proxyGenerator = "org.rapidpm.module.se.commons.proxy.ProxyGenerator";
                final String concurrency = "org.rapidpm.module.se.commons.proxy.Concurrency";
                out.printf(" if (val == null) { System.out.println(\" val == null for method  + " +m.getName()+ "\");} %n");
                out.printf(typeName + " proxyObj = " + proxyGenerator+ ".make("+typeName+".class, "+typeName+".class, " +concurrency+"."+type.toString()+"); %n");

                if (type.equals(Concurrency.OnExistingObject)){
                    out.printf("try { %n");
                    out.printf("    proxyObj.getClass().getDeclaredField(\"realSubject\").set(proxyObj, val);  %n");
                    out.printf("} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {  %n");
                    out.printf("    e.printStackTrace(); %n");
                    out.printf("}  %n");
                }
                out.printf(" return proxyObj; %n");
            } else {
                out.printf(" return val; %n");
            }
                out.printf("%n}%n");
        }
    }

    private void addMethodSignature(PrintWriter out, Method m) {
        out.printf("%n public %s", Util.prettyPrint(m.getReturnType()));
        out.printf(" %s(", m.getName());
        addParameterList(out, m);
        out.printf(") {%n ");
    }

    private void addParameterList(PrintWriter out, Method m) {
        Class[] types = m.getParameterTypes();
        for (int i = 0; i < types.length; i++) {
            String next = i == types.length - 1 ? "" : ", ";
            out.printf("%s p%d%s", Util.prettyPrint(types[i]), i, next);
        }
    }

    private void addMethodBody(PrintWriter out, Method m) {
        addMethodBodyDelegatingToRealSubject(out, m);
    }

    private void addMethodBodyDelegatingToRealSubject(PrintWriter out, Method m) {
        //hole result
        final Class returnType = m.getReturnType();
        if (returnType == void.class) out.printf("realSubject().%s(", m.getName());
        else if(m.getName().equals("toString")){
            out.println("String val;");
            out.println(" if(realSubject() == null ) val = \"NullObjectHolder in \" + this.getClass() ; ");
            out.printf(" else val = realSubject().%s(", m.getName());
        } else if(m.getName().startsWith("get") && ! returnType.isPrimitive()){
            String name;
            if (returnType.isArray()) name = returnType.getSimpleName();
            else name = returnType.getName();
            out.println(name + " val;");
            out.println(" if(realSubject() == null ) val = null ; ");
            out.printf(" else val = realSubject().%s(", m.getName());   
        } else {
            String name;
            if (returnType.isArray()) name = returnType.getSimpleName();
            else name = returnType.getName();
            out.println(name + " val;");
            out.printf("val = realSubject().%s(", m.getName());  

        }
        addMethodCall(out, m);
    }

    private void addMethodCall(PrintWriter out, Method m) {
        Class[] types = m.getParameterTypes();
        for (int i = 0; i < types.length; i++) {
            String next = i == types.length - 1 ? "" : ", ";
            out.printf("p%d%s", i, next);
        }
    }
}
The result is really cool. see the following code ;-)
       DemoClassA demoClassA = new DemoClassA();
        demoClassA.demoClassB = null;

        final String value = proxy(demoClassA).getDemoClassB().getDemoClassC().getValue();
        System.out.println("value = " + value);

You can navigate the full path. no NPE! No boiler plate code!
@Test
    public void testGenerator00X() throws  Exception {
        DemoClassA demoClassA = new DemoClassA();
        demoClassA.demoClassB = null;

        final String value = proxy(demoClassA).getDemoClassB().getDemoClassC().getValue();
        System.out.println("value = " + value);

    }

private DemoClassA proxy(DemoClassA demoClassA) {
        final Class<DemoClassA> aClass = (Class<DemoClassA>) demoClassA.getClass();
        final DemoClassA demo = ProxyGenerator.make(aClass, aClass, Concurrency.OnExistingObject);

        final Class<? extends DemoClassA> aClassProxy = demo.getClass();
        try {
            aClassProxy.getDeclaredField("realSubject").set(demo,demoClassA );
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        }
        return demo;
    }
You can now use every getter.. not NPE. Only the result will be an null. This was exactly what I needed to get only the valid values from the model if they are available. This means, that you could proxy an object after you have initialized it. The full source code is available under : https://bitbucket.org/rapidpm/modules on the develop branch. I will merge it into the version 2.0 as generic pattern and CDI managed...

Montag, 17. Februar 2014

CDI EJB-Remote Context for wildfly

This article shows how ejb remote clients can be configured and connected in a more dynamic way.

Within wildfly (current version 8.0.0.Final) there are several possibilities to connect ejb remote clients. Descriptions can be found on:

The Problem


You have an application for two (or more) tenants which are identical but are deployed on different machines. Customers should be able to switch between those tenants without restarting the application. Additionally the code itself should not depend on tenant specific code.
As far as i know this would be necessary with the standard approach (jboss-ejb-client.properties) given above.

A Solution


After some consideration i have identified the following five components which are needed to implement this feature.
  • Component that creates WildFly ejb remote connections
  • Component that produces the JNDI-Context
  • Component that holds the selected tenant-key for the client
  • Component that maps the tenant-keys to connection properties
  • CDI-Modul Qualifier

Putting them together leads to the following UML:



To keep the example as simple as possible i have decided to use the ejb-remote-quickstart example and extend it with the jndicontext module. The current implementation uses a simple property file which holds the following data.
tenant1.host=localhost
tenant1.port=8080
tenant1.username=test
tenant1.password=test
tenant1.noanonymous=false

tenant2.host=192.168.0.104
tenant2.port=8080
tenant2.username=test
tenant2.password=test
tenant2.noanonymous=false

The Fazit


The resulting service locator just has to use the JndiSession (in this example the RemoteEJBClient) which technically holds the tenant key and can be set from the GUI.
public class RemoteEJBClient {
    @Inject @JndiContextAnno
    Instance<Context> contextInstance;

    @Inject
    JndiSession jndiSession;
    //...snip
    private RemoteCalculator lookupRemoteStatelessCalculator() throws NamingException {
        Context context = contextInstance.get();
        //...snip
    }
}

public class CDIBootStrapper {
    public static void main(String[] args) throws Exception
    {
        WeldContainer weld = new Weld().initialize();
        RemoteEJBClient client = weld.instance().select(RemoteEJBClient.class).get();

        client.getJndiSession().setTenantKey("tenant1");
        client.invokeStatelessBean();

        client.getJndiSession().setTenantKey("tenant2");
        client.invokeStatelessBean();
    }
)
So the code looks very clean and in comparison to jboss-ejb-client.properties way more functional.
The sources can be found on https://bitbucket.org/abischof/injectablejndicontext.
Have fun coding... ;)

Donnerstag, 13. Februar 2014

Raspberry Wildfly Cluster for less than 300€

So WildFly 8 is final now.
In this article i like to show how you can create a development/testing wildly cluster with raspberry pis and only one power supply.

I have bought:
  • 5x Raspberry Pis (Model B) with Wireless USB-Adapters
  • 1x 10-Port USB 2.0 Hub
  • 5x USB to Micro USB Adpapter

The Raspberries are configured with Raspbian Wheezy (wlan auto), JDK 8 and Wildfly 8 Final.
In this combination you have to remove the '-server' from the domain.sh otherwise WildFly won't start.

The WildFly Configuration can be made within 5 minutes.
  1. Master
    1. Create management user admin (./add-user.sh)
    2. Create a management slave user for each of your pi slaves (./add-user.sh)
      • Remember the secret value at the end of this process for each slave (e.g.<secret value="MTIzNDU=" />)
    3. Bind the interfaces to the public interface (e.g. 192.168.0.103) 
  2. Slave
    1. Configure host.xml with the slave name of 1.1
      • <host name="slave1" xmlns="urn:jboss:domain:2.0">
    2. Configure the server identity
      • <server-identities> <secret value="MTIzNDU="/> </server-identities>
    3. Bind the interfaces to master and public interface (e.g. 192.168.0.104)
      • To simply the typing i have written a small script that takes the master-ip and the bind-ip
      • #MasterAdress
        MASTER_ADDRESS=$1
        
        # Bind Addresses
        BIND_ADDRESS=$2
        
        JBOSS_BIND_ADDRESS_MANAGEMENT=$BIND_ADDRESS
        JBOSS_BIND_ADDRESS=$BIND_ADDRESS
        JBOSS_BIND_ADDRESS_UNSECURE=$BIND_ADDRESS
        
        sudo ./domain.sh -Djboss.bind.address.unsecure=$JBOSS_BIND_ADDRESS_UNSECURE -Djboss.bind.address.management=$BOSS_BIND_ADDRESS_MANAGEMENT -Djboss.bind.address=$JBOSS_BIND_ADDRESS -Djboss.domain.master.address=$MASTER_ADDRESS
Ready. Now you can deploy any archive either to main-server-group (just a domain) or other-server-group (full cluster).

Montag, 10. Februar 2014

JDK8/Streams are cool? Here is the answer. ;-)

Today I was preparing a few slides for my next JUG talk. For this if started with a normal piece of code like the following.
  
    public List<List<Integer>> generateDemoValueMatrix() {
        final List<List<Integer>> resultMatrix = new ArrayList<>();
        final Random random = new Random();
        for(int anzahlKurven = 0; anzahlKurven <ANZAHL_KURVEN; anzahlKurven++){
            final List<Integer> result = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                final int nextInt = random.nextInt(100);
                result.add(nextInt);
            }
            resultMatrix.add(result);
        }
        return resultMatrix;
    }

Next step would be the creation of two methods...
  
    public List<List<Integer>> generateDemoValueMatrix() {
        final List<List<Integer>> result = new ArrayList<>();
        for(int anzahlKurven = 0; anzahlKurven <ANZAHL_KURVEN; anzahlKurven++){
            final List<Integer> demoValuesForY = generateDemoValuesForY();
            result.add(demoValuesForY);
        }
        return result;
    }
    public List<Integer> generateDemoValuesForY() {
        final Random random = new Random();
        final List<Integer> result = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final int nextInt = random.nextInt(100);
            result.add(nextInt);
        }
        return result;
    }
Ok, look´s like always... booooring.... So I started with Streams..
    public List<List<Integer>> generateDemoValueMatrix() {
        return Stream
                .generate(this::generateDemoValuesForY)
                .limit(ANZAHL_KURVEN)
                .collect(Collectors.toList());
    }
    public List<Integer> generateDemoValuesForY(){
        final Random random = new Random();
        return Stream
                .generate(() -> {
                    return random.nextInt(100);
                })
                .limit(10)
                .collect(Collectors.toList());
    }
Not really better.. only new syntax.. now reducing the syntax..
    public List<List<Integer>> generateDemoValueMatrix() {
        return Stream
                .generate(this::generateDemoValuesForY)
                .limit(ANZAHL_KURVEN)
                .collect(Collectors.toList());
    }
    public List<Integer> generateDemoValuesForY(){
        final Random random = new Random();
        return Stream
                .generate(() -> random.nextInt(100))
                .limit(10)
                .collect(Collectors.toList());
    }

But Random offer something new.
    public List<List<Integer>> generateDemoValueMatrix() {
        return Stream
                .generate(this::generateDemoValuesForY)
                .limit(ANZAHL_KURVEN)
                .collect(Collectors.toList());
    }
    public List<Integer> generateDemoValuesForY(){
        return new Random()
                .ints(0, 100)
                .limit(10)
                .boxed()
                .collect(Collectors.toList());
    }
Combining both methods..
    public List<List<Integer>> generateDemoValueMatrix() {
        final Random random = new Random();
        return Stream.generate(
                    () -> Stream.generate(
                            () -> random.nextInt(100))
                            .limit(10)
                            .collect(Collectors.toList())
                )
                .limit(ANZAHL_KURVEN)
                .collect(Collectors.toList());
    }
OK, not short enough.. we could it better..
    public List<List<Integer>> generateDemoValueMatrix() {
        return Stream.generate(
                () -> new Random()
                        .ints(0, 100)
                        .limit(10)
                        .boxed()
                        .collect(Collectors.toList())
                ).limit(ANZAHL_KURVEN)
                .collect(Collectors.toList());
    }
Uuuppsss.. static imports possible.. ;-)
    public List<List<Integer>> generateDemoValueMatrix() {
        return generate(() -> new Random()
                .ints(0, 100)
                .limit(10).boxed().collect(toList())
        ).limit(ANZAHL_KURVEN).collect(toList());
    }
Now compare with the first and decide ;-) Streams are cool ? I think so!!

Lego Mindstorms EV3 Components: Infrared Sensor - Part 2

In this second part on the mindstorm's infrared sensor we will focus on the remote control and the ability of the remote sensor to recognize commands from that remote control respectively. There are multiple buttons on that remote control and we will control the robot by pressing different buttons.

The robot

We will use the robot from the first part as it already uses the infrared sensor. The mindstorm's remote control looks like the following:


There are two buttons on the left (red) and two buttons on the right (blue). There is a fifth button at the top center which is (in contrast to all other buttons) a toggling button. So if you press it one time, the remote control sends a signal continuously until the button is pressed a second time. Before taking the photo I pressed that button one time to activate the green signal led. We will use that toggle button on the next part of the infrared sensor articles.
The red slider at the bottom center is for selecting a frequency channel. You can select four channels and the current channel is shown in the red circle under the toggling button.

The parcours

There is the robot and there is the remote control. The aim is to press different buttons on the remote control to control and move the robot. We will use the two buttons on the left to let the robot rotate left/right, respectively the two buttons on the right to let the robot move forwards/backwards. When more than one button is pressed, the program should exit.


The infrared sensor API

There are two relevant modes for the infrared sensor. The distance mode and the seek mode. We used the former implicitly in the last article and we will use it in this one because it offers the possibility to receive commands from the infrared remote control. The latter can be used to receive the position and the distance of the remote control to the robot (the next tutorial will use the seek mode).

It's very easy to receive a command from the remote control. The only method we will use is infraredSensor.getRemoteCommand(0);
This will return an integer value which represents the pressed button on the remote control (e.g. the left upper button on the remote control will return 1). The parameter of the method is also an integer value which represents the frequency channel which we use on the remote control. You can select one of four different channels (via the red slider on the remote control). In this case we use channel 0 (which is called channel 1 on the remote control).

That's it. We don't need RangeFinderAdaptors, RangeFeatureDetectors or anything like that this time. So let's directly jump to the finished code and see how it works.

The code

There are two classes. The Main-class and an InfraredSignalCheckerThread, which extends Thread and contains the logic for received commands from the remote control.

Let's start with the Main-Class:

import lejos.hardware.Button;
import lejos.hardware.motor.Motor;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3IRSensor;
import lejos.robotics.navigation.DifferentialPilot;

public class Main {

    protected final static double NINETY_DEGREES = 90.0;
    protected final static double PILOT_SPEED = 100.0;
    protected final static int PILOT_ACCELERATION = 500;
    protected final static double WHEEL_DIAMETER = 30.0f;
    protected final static double DISTANCE_BETWEEN_WHEELS = 170.0;

    public static void main(String[] args) throws InterruptedException {

        final DifferentialPilot pilot = new DifferentialPilot(WHEEL_DIAMETER, DISTANCE_BETWEEN_WHEELS, Motor.C, Motor.B);
        final EV3IRSensor infraredSensor = new EV3IRSensor(SensorPort.S2);
        final InfraredSignalCheckerThread checkerThread = new InfraredSignalCheckerThread(infraredSensor, pilot);

        configurePilot(pilot);
        checkerThread.start();
        Button.waitForAnyPress();
    }

    private static void configurePilot(final DifferentialPilot pilot) {
        pilot.setAcceleration(PILOT_ACCELERATION);
        pilot.setRotateSpeed(PILOT_SPEED);
        pilot.setTravelSpeed(PILOT_SPEED);
    }
}

If you've (hopefully) read our last article on the infrared sensor, you will recognize that the Main-class became a bit smaller this time. We don't have to configure anything on the infrared sensor.
First we create instances for the pilot and the infrared sensor again. The new thing is the InfraredSignalCheckerThread which extends Thread. This class contains all the logic for received commands. The logic is implemented in a Thread-extending class because we want to listen continuously for any received commands. The created instance of the InfraredSignalCheckerThread needs the infraredSensor-object of course and it needs the pilot (because we will control/move the robot corresponding to the pressed button on the remote control).

After we created the instances we configure the pilot and start the checkerThread. That's it. Let's have a look at the InfraredSignalCheckerThread-class now.

The InfraredSignalCheckerThread-class:

import lejos.hardware.sensor.EV3IRSensor;
import lejos.robotics.navigation.DifferentialPilot;

public class InfraredSignalCheckerThread extends Thread {

    private EV3IRSensor infraredSensor;
    private DifferentialPilot pilot;

    public InfraredSignalCheckerThread(final EV3IRSensor infraredSensor, final DifferentialPilot pilot){
        this.infraredSensor = infraredSensor;
        this.pilot = pilot;
    }

    @Override
    public void run() {
        while(true){
            final int remoteCommand = infraredSensor.getRemoteCommand(0);
            switch (remoteCommand){
                case 0:
                    pilot.quickStop();
                    break;
                case 1:
                    pilot.rotateLeft();
                    break;
                case 2:
                    pilot.rotateRight();
                    break;
                case 3:
                    pilot.forward();
                    break;
                case 4:
                    pilot.backward();
                    break;
                default:
                    System.out.println("button combination pressed..exiting...");
                    System.exit(0);
            }
        }
    }
}

Let's have a look at the run-method. As you can see we have an infinite loop. In that loop we get an integer command from the method infraredSensor.getRemoteCommand(0). The given parameter (0) means that the infrared sensor should listen at frequency channel 0 (remember the red slider on the remote control for selecting a channel).
So now the thread is checking for any commands on channel 0 continuously. As next we check which command was sent. The different buttons send different integer values. Here is the documentation from within the EV3IRSensor-class:

/** The button values are:
* 1 TOP-LEFT
* 2 BOTTOM-LEFT
* 3 TOP-RIGHT
* 4 BOTTOM-RIGHT
* 5 TOP-LEFT + TOP-RIGHT
* 6 TOP-LEFT + BOTTOM-RIGHT
* 7 BOTTOM-LEFT + TOP-RIGHT
* 8 BOTTOM-LEFT + BOTTOM-RIGHT
* 9 CENTRE/BEACON
* 10 BOTTOM-LEFT + TOP-LEFT
* 11 TOP-RIGHT + BOTTOM-RIGHT
* (0 means no buttons pressed)
*/

So, as you can see if no button is pressed on the remote control the method will return 0. The four buttons we want to use return 1, 2, 3 and 4.
Knowing these return values the switch statement becomes very easy to understand. If no button is pressed the robot shouldn't move. If the top left button is pressed the robot should rotate to the left and so on, we just call the corresponding methods of the DifferentialPilot-class to control the motors. If more than one button is pressed at a time the program should exit.

The result

And here is the result (watch on youtube for better quality):



Some words on complications that I had while writing the program: After starting the CheckerThread I had to wait around 30 seconds before pressing a button on the remote control. I have no explaination for that but when I pressed any button earlier the robot moved very jerkily. I tried different workarounds like Thread.sleep() and Delay.ms() in the main-method and the checker-thread. I also tried a timer in the CheckerThread which printed a message on the console to tell the user that the program isn't yet ready if he tried to press any button during those first 30 seconds. But none of these attempts worked.

Freitag, 7. Februar 2014

FXController with CDI managed DynamicObjectAdapter - Part 2

Based on my blog article part 1 we want to integrate the DynamicObjectAdapter into an JavaFX application. To remember: We have an interface called DemoLogic with two methods. add(..) and sub(..) The implementation is really simple, but at runtime we could switch the implementation partially. For this we needed an adapter.
The biggest tdifference compared to the default CDI decorator was, that we need no definition inside the beans.xml. The implementation is smaller and no need for Qualifiers and other biolder-plate code.
This DemoLogic we want to use now inside an JavaFX application. For this we ned first an fxml.file called DemoPane.fxml. Here we will define a few elements.
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.CheckBox?>
<fx:root type="javafx.scene.layout.AnchorPane"
            xmlns:fx="http://javafx.com/fxml">
    <children>
        <VBox>
            <children>
                <Button fx:id="button" text="Hello World" />
                <CheckBox fx:id="checkbox" text="switch context"/>
                <TextField fx:id="textFieldA"/>
                <TextField fx:id="textFieldB"/>
                <Label fx:id="label"/>
            </children>
        </VBox>

    </children>

</fx:root>
With the button we will activate the calculation, with the checkbox we will switch the context. To have a small as possible implementation, there is no error checking.
The next will be the controller called DemoController. This is a normal JavaFX Controller, but CDI managed. How to get this? Well there is a good blog article here ;-) CDI JavaFX bootstrapping.
Inside the DemoController we will get an Instance of the DemoLogic and the Context.
@Inject
    @DynamicDecoratorTest
    Instance<DemoLogic> demoLogicInstance;

    @Inject
    Context context;
The full implementation will be like the following.
@DynamicDecoratorTest
public class DemoController implements Initializable{

    @FXML public TextField textFieldA;
    @FXML public TextField textFieldB;
    @FXML public Button button;
    @FXML public Label label;
    @FXML public CheckBox checkbox;

    @Inject
    @DynamicDecoratorTest
    Instance<DemoLogic> demoLogicInstance;

    @Inject
    Context context;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        button.setText("klick me");
        button.setOnAction(actionEvent -> {

            final DemoLogic demoLogic = demoLogicInstance.get();

            final String textFieldAText = textFieldA.getText();
            final Integer a = Integer.valueOf(textFieldAText);

            final String textFieldBText = textFieldB.getText();
            final Integer b = Integer.valueOf(textFieldBText);

            final int result = demoLogic.add(a, b);
            label.setText(result+"");

        });

        checkbox.setOnAction(actionEvent -> {
            context.original = checkbox.isSelected();
        });
    }
}
Inside the method initialize you will find the connection between the GUI logic and the business logic. This is now clean devided.
To test this I was using Arquillian. LAter we will see how we could do this with TestFX. We are working on the CDI Support.
@RunWith(Arquillian.class)
public class DemoLogicTest {
    @Deployment
    public static JavaArchive createDeployment() {
        return ShrinkWrap.create(JavaArchive.class)
                .addPackages(true, "org.rapidpm.demo")
                .addPackages(true, "junit.org.rapidpm.demo")
                .addPackages(true, "demo")
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    }

    @Inject @DynamicDecoratorTest
    Instance<DemoController> demoControllerInstance;
    @Inject
    Context context;

    static final FXMLLoader loader = new FXMLLoader();

    @Test
    public void testDemoLogicJavaFXTest() throws Exception {
        loader.setControllerFactory(param -> demoControllerInstance.get());
        Application.launch(DemoApp.class);
    }


    public static class DemoApp extends Application {
        @Override
        public void start(Stage stage) throws Exception {

            final URL resource = getClass()
                    .getClassLoader()
                    .getResource("DemoPane.fxml");
            loader.setLocation(resource);
            final DemoController controller = (DemoController) loader
                    .getControllerFactory()
                    .call(DemoController.class);
            try {

                loader.setController(controller);
                loader.setRoot(new AnchorPane());
                final Parent root = (Parent) loader.load();

                stage.setScene(new Scene(root));
                stage.setTitle("Custom Control");
                stage.setWidth(300);
                stage.setHeight(200);
                stage.show();
            } catch (IOException exception) {
                throw new RuntimeException(exception);
            }

        }

        public static void main(String[] args) {
            launch(args);
        }
    }
}

You never need the decorator from CDI anymore. ;-)

Dienstag, 4. Februar 2014

TestFX a must for jUnit Tests inside JavaFX environments!

You have written jUnit Tests for JavaFX applications? 
You want to simulate user interactions?

If you are starting from scratch this will be a long task.
But the Team from TestFX is working on a solution.
TestFX (https://github.com/SmartBear/TestFX) is an OpenSource framework from Henrik Olsson (SmartBear) with the goal to be an easy-to-use framework for testing JavaFX.

This framework is ready for Java8 and supports JavaFX 2.
With this you are able to test featured JavaFX based GUIs.

No License needed, no costs, complete OpenSource and extensible.

The fluent and clean API is simple to use for the interaction with the controls. No special wrapper must be implemented, no boilerplate code is needed to test a simple control. Extend the jUnit Test-class and create an instance of your JavaFX control.

That´s all you need. After this you are able to interact directly with the instance you created.
TestFX will give you a lot of service methods to interact and verify the behavior of the tested control.
And, if something goes wrong, you will get an screenshot of the failed test.

One of the really big advantages is the easy possibility to extend TestFX by yourself. The framework is clean and well structured.
The support for Hamcrest Matchers and Lambdas will give you all you need to build complex tests.

There is only one more thing....
...  we are working on the CDI support for TestFX.

stay tuned and happy coding.

Montag, 3. Februar 2014

One way to deadlock a JBoss AS 7

Take a standard JBoss AS 7 and create/deploy a simple remote stateless session bean with two methods. One of them should be asynchronous. As shown in the following example the asynchronous method creates a little bit of load and the second one simulates a login.
public interface IMyBean
{
 Future<Void> doNothing();
 void login();
}
@Stateless
@Remote(IMyBean.class)
public class MyBean implements IMyBean
{
 @Override
 @Asynchronous
 public Future<Void> doNothing()
 {
  //Creates Load
  int lo = 0;
  for (int i = 0; i < 5000; i++)
  {
   lo += i;
  }
  System.out.println("nothing done");
  return new AsyncResult<Void>(null);
 }
 @Override
 public void login()
 {
  System.out.println("logged in");
 }
}
In the next step besides 10 EJB-Remote-Clients which access the asynchronous method parallel we create an additional client which repeatly tries to login. (Note: Classpath contains jboss-ejb-client.properties and jboss-client.jar)
public class HangTest
{
 public static void main(String args[]) throws NamingException
 {
  //EJB-Remote-Access
  Properties jndiProps = new Properties();
  jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
  Context context = new InitialContext(jndiProps);
  final IMyBean myBean = (IMyBean) context.lookup("ejb:/hangtest/MyBean!IMyBean");

  //Create and start asynchronous method threads
  final List<Thread> threadList = new ArrayList<>();
  for (int i = 0; i < 10; i++)
  {
   Thread thread = new Thread()
   {
    @Override
    public void run()
    {
     try
     {
      myBean.doNothing().get();
     }
     catch(Exception e)
     {
      e.printStackTrace();
     }
     finally
     {
      threadList.remove(this);
     }
    }
   };
   threadList.add(thread);
   thread.start();
  }

  //Repeated Login
  while(!threadList.isEmpty())
  {
   System.out.println("Try login...");
   myBean.login();
  }
 }
}
The code above works as expected which means that random server messages ("nothing done", "logged in") are printed out and that the login client can login. It also can be executed as many times as you want without a change in behavior.
BUT if you increase the number of asynchronous method clients for example to 20-30 (depending on your computer) then nothing is printed out and the login client can not login anymore. The JBoss or - to be more specific - some components of it are in a deadlock (Note: JBoss shutdown does not work anymore). So what has happened?

To answer this question we have to look into the standalone.xml, especially in the subsystem "urn:jboss:domain:ejb3". This section contains ejb3-related configurations and among them threadpools. In this context it is important that the default threadpool is shared between asynchronous calls, timers and ejb-remote.
<subsystem xmlns="urn:jboss:domain:ejb3:1.2">
...
 <async thread-pool-name="default"/>
 <timer-service thread-pool-name="default">
  <data-store path="timer-service-data" relative-to="jboss.server.data.dir"/>
        </timer-service>
 <remote connector-ref="remoting-connector" thread-pool-name="default">
  <thread-pools>
   <thread-pool name="default">
    <max-threads count="10"/>
    <keepalive-time time="100" unit="milliseconds"/>
   </thread-pool>
  </thread-pools>
   </remote>
</subsystem>

So if you stumble upon that problem either increase the max-thread count property or even better seperate the thread-pools for asynchronous and ejb-remote components.