Not changing direction, just stepping the game up

The first Apache Flex blog post is here:

Flex settling in at The Apache Software Foundation
This is the beginning of a new era for Flex. On December 31st 2011, our project was accepted as an incubator podling at the Apache Software Foundation. read more..
Advertisements

Unit testing with FlexMojos and displaying Cobertura coverage in Sonar

The great thing about running unit tests with FlexMojos 4 is that it can also generate code coverage report. See it here http://www.sonatype.com/people/2010/04/flex-test-coverage-kept-simple-with-flexmojos/

I just love that feature, because in the past you had to use a modified version of the Flex SDK with an external AIR Application to do that, but now it is very simplified.

I also love using Sonar to gather and display statistics for source code. I thought it would be great to build my project and run unit tests with FlexMojos and then reuse the reports created by it and show this information in Sonar. You are able to reuse the surefire reports using the flex plugin for Sonar, but however this was not possible for the cobertura coverage report . So what I did was to browse the code for this plugin and see how Olivier Gaudin and Evgeny Mandrikov, the guys written it, handle the surefire reports. And so I though that it was going to be easy using the code from the cobertura sonar plugin to implement this feature. And somehow I did.

I’ve added this patch in the Jira, so hopefully in the next version it will be included. Until the official version, you can use my modification (see bellow for download)

Here is how to use it. In your pom.xml you would have something like

<build>  
 <sourcedirectory>src</sourcedirectory>  
 <testsourcedirectory>test</testsourcedirectory>  
  
 <plugins>  
   
  <plugin>  
   <groupid>org.sonatype.flexmojos</groupid>  
   <artifactid>flexmojos-maven-plugin</artifactid>  
   <version>4.0-beta-5</version>  
   <extensions>true</extensions>  
     
   <dependencies>  
    <dependency>  
    <groupid>com.adobe.flex</groupid>  
    <artifactid>compiler</artifactid>  
    <version>4.1.0.16248</version>  
    <type>pom</type>  
    </dependency>  
   </dependencies>  
     
   <configuration>  
    <sourcefile>TestSonar.mxml</sourcefile>  
    <flashplayercommand>C:\FlashPlayer\FlashPlayer.exe</flashplayercommand>  
    <coverage>true</coverage>  
    <coveragereportformat>  
    <param>xml <!-- param-->  
    </coveragereportformat>  
    <testfailureignore>true</testfailureignore>  
   </configuration>  
  </plugin>  
 </plugins>  
</build>  

That snippet would build and test your project. Important here is to specify coverage and coverageReportFormat . The coverageReportFormat is xml, so it can be used later on.

And the properties in the pom.xml for the sonar plugin are

<properties>  
    <sonar.language>flex</sonar.language>  
    <sonar.dynamicanalysis>reuseReports</sonar.dynamicanalysis>  
    <sonar.surefire.reportspath>target\surefire-reports</sonar.surefire.reportspath>  
    <sonar.cobertura.reportpath>target\coverage\coverage.xml</sonar.cobertura.reportpath>  
</properties>

I think everything here is understandable, you specify to use the plugin for flex and reuse the generated reports for surefire and cobertura.

See the full pom.xml here

And to build all up run:

mvn clean install sonar:sonar -Pflex

Have in mind that you should use maven 3 for FlexMojos 4

See the result

So if you can’t wait to try this out, get this patched version, if not you could probably wait for an official release, I hope there will be one soon.

Download the patched version of flex plugin for sonar from here. (Again, this is my modification of the original version, it is not the version provided by Codehaus, Sonar)

Download the test Flex project with Unit tests from here

Improve your code using Sonar with Flex plugin

Bad code leads to bugs, hard understanding, hard maintenance. We should really learn to write good code, and with so much open source tools for code analysis we could improve it one step higher.

Sonar is a tool for code quality analysis. It helps improving software quality using static analysis tools. It targets Java code, but there are plugins for Flex, C, PHP, .Net and other languages. The Flex plug-in specifically uses FlexPMD, FlexMetrics, FlexCPD and FlexMojos.

In this post I will show you the features that FlexPMD gives us within Sonar. I think that this tool is not really known by the Flex developers, I admit that I also didn’t have an idea what it is until recently.
Have you used eclipse for Java developing? I really love when warnings like unused variables and not called methods appear. Well FlexPMD does this for us along with a lot more things. It even can be used inside of Eclipse to show you live reports. There are defined rules that FlexPMD follows to catch issues in the code and bad practices. Great thing is that you can also define your own rules using this flex app

Step 1. So first go and download Sonar. After that download the flex plugin for it. It is a jar file. Now extract the contents of the sonar archive in a desired location, and place the sonar-flex-plugin-x.x.x.jar in extensions\plugins directory of sonar. That’s pretty much what you need to start sonar. By default it uses an embeded Apache Derby database, that you can change to whatever you want in sonar.properties file in conf folder. So now start Sonar. I start it from bin\windows-x86-32\StartSonar.bat as I am a windows user, if you are on other operating system start it from bin\YOUR_SYSTEM\sonar.sh. Have in mind that it takes a while to start so have patience. To assure that it is started open a browser and navigate to http://localhost:9000/

Step 2. Create a flex project. I will create a small test project with one class written really ugly and bad and doesn’t actually do a thing it is here to show you what errors Sonar will find. Pff It doesn’t even deserve to be put it in a code tag and to be styled because I am embarrassed of it 🙂
Here it is:

public class MyTestComponent extends UIComponent  
{  
 private var r:Number;  
   
 private var variableNotUsed:Object;  
   
 override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void  
 {  
  r = Math.random()* 85;  
    
  var child1:UIComponent = new UIComponent();  
  addChild(child1);  
 }  
   
 public function myFunctionWithVeryLongNameAndLotsOfParametersThatDoesNothing(p1:String, p2:Number, p3:Object, p4:Boolean, p5:int, p6:*, p7:Array):void  
 {  
  return;  
 }  
}

Step 3. Run analysis built with Maven. For this step you should have Maven 2 on your computer (I think Maven 3 will also work, but I have tested it with 2). Note A lot of Flex developers think of Maven as the Black ninja, Java developers use for their projects. Maven is a tool that helps managing the building, documentation, testing and reporting for Java projects. With FlexMojos you can even use it for your Flex projects also. It is a lot useful for continuous integration. So my note to the Flex developers: don’t be afraid of Maven, it is here to help us 🙂

Assuming that you have Maven on your computer, as the documentation on the sonar site suggests, add

<profile>  
  <id>flex</id>  
  <pluginrepositories>  
    <pluginrepository>  
      <id>flexpmd.opensource.adobe</id>  
      <releases>  
        <enabled>true</enabled>  
      </releases>  
      <snapshots>  
        <enabled>false</enabled>  
      </snapshots>  
      <name>FlexPMD repository on opensource.adobe.com</name>  
      <url>http://opensource.adobe.com/svn/opensource/flexpmd/maven-repository/release/</url>     
    </pluginrepository>  
  </pluginrepositories>  
</profile>  

this to the settings.xml file of maven located either in $M2_HOME/conf/settings.xml or ${user.home}/.m2/settings.xml

And now in the flex project folder add a new file named pom.xml

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelversion>4.0.0</modelversion>    
    
  <name>Test Sonar Project</name>  
  <groupid>com.tgeorgiev</groupid>  
  <artifactid>sonar.test</artifactid>  
  <version>0.1</version>  
  <packaging>pom</packaging>  
    
  <build>  
    <sourcedirectory>src</sourcedirectory>  
  </build>   
  <properties>  
    <sonar.language>flex</sonar.language>  
    <sonar.dynamicanalysis>false</sonar.dynamicanalysis>  
  </properties>  
</project>  

Now open a console, navigate to the location of your flex project and type “mvn sonar:sonar -Pflex”.

Step 4. After some time of downloading the needed jars for the build and running the analysis task we can check what happened when we open http://localhost:9000/ There should be displayed our project with all the violations that were detected.
For my test project I have
Blocker 12
Critical 0
Major 9
Minor 0
Info 1

And when I select to see the Blocker issues for example I see:

Hmm strange, but it found most of the issues I think are present in this code 🙂

So tell me, do you use Sonar for static analysis of the code, or maybe some other tool? And I’m really interested on how do you use it? Did you integrated it in continuous build or do you check the code once in a while on your computer? Do you use it individually or your whole team uses it.

Seriously, how to position your UIComponent in Flex?

Believe it or not, but recently I struggled to achieve something so simple like positioning a Button by X and Y. What was the case:

We have a Button with X and Y values binded. We also set depth to this button, lets say 1. And we want at some point to change its position. The code for the whole application looks like

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">


<![CDATA[
[Bindable]
public var buttonX:Number;
[Bindable]
public var buttonY:Number;
]]>









It looks pretty straight-forward. But there is a catch. Here is the application. Try to move the button, I dare you 🙂

There are 2 important things that are happening here:

1. By default buttonX and buttonY are NaN. That basically is not a problem, because we will set actual values to them and they will change, but if it wasn’t for
2. When we set depth to an instance of UIComponent, the special layoutFeatures are being initialized. They are responsible for advanced features of the layout such as:
depth, z, rotationX, rotationY, transformX, transformY and so on..

So once these layoutFeatures get initialized, for every new assign of x, y, width, height scale.. it uses the layoutFeatures object of UIComponent to set them. And this time it is not overwriting the values, instead it is doing a translation (when setting x). The actual thing it is being done is : translateBy(value-_x,0,0); where _x is the old x, and value is the new that we are assigning. So when our old value is NaN…
you guessed NaN – whatever_number = NaN

So I wondered whether this is a bug and should be reported to Adobe (if it already isn’t). But I am this type of a guy where I always blame myself, so I think maybe the guilt is mine. So I have to fix my code. The easiest and proper fix is to assign default values of 0 to the properties we are binding … or not using depth at all, who needs it 😉

[Bindable]
public var buttonX:Number = 0;
[Bindable]
public var buttonY:Number = 0;

Animating the perspective projection of a DisplayObject

So as you probably know, in flex 3 we could animate objects only by their numerical properties. Which for most situations is enough, like positioning or resizing component. But sometimes you will want to animate a complex object, and in flex 4 that is possible using arbitrary type interpolation. You can see this great demo on the topic on adobe tv by Chet Haase. Mine example isn’t nothing more special than his, I just decided to do it because I saw few people entering my blog wanting to see an example of using perspective projection other than in my previous post – custom flex 4 layout and because recently I had to do similar animation, but I have done it the “dirty” way (yeah I admit it), so I thought it is time to correct it.

The most important thing is our PPInterpolator and its method interpolate()

public function interpolate(fraction:Number, startValue:Object, endValue:Object):Object
{
    var startPP:PerspectiveProjection = startValue as PerspectiveProjection;
    var endPP:PerspectiveProjection = endValue as PerspectiveProjection;
    
    var currentPP:PerspectiveProjection = new PerspectiveProjection();
    currentPP.fieldOfView = startPP.fieldOfView + fraction * (endPP.fieldOfView - startPP.fieldOfView);
    currentPP.focalLength = startPP.focalLength + fraction * (endPP.focalLength - startPP.focalLength);
    
    var projectionCenterX:Number = startPP.projectionCenter.x + fraction * (endPP.projectionCenter.x - startPP.projectionCenter.x);
    var projectionCenterY:Number = startPP.projectionCenter.y + fraction * (endPP.projectionCenter.y - startPP.projectionCenter.y);
    
    currentPP.projectionCenter = new Point(projectionCenterX, projectionCenterY);
    
    return currentPP;
}

You see that we expect startValue and endValue to be instances of PerspectiveProjection and return a new instance based on these values as a value for the current moment of the animation.

The other thing is as just writing a normal animation, we are just setting the interpolator of the motion path to be the one we created and set the target of the animation the transform property of a group (it could be any other DisplayObject). Have a look at the valueFrom and valueTo, we are passing instances of PespectiveProjection

    
    
    
        
            
                <![CDATA[
                    import com.tgeorgiev.effects.PPInterpolator;
                ]]>
            
            
        
    

The group that is the target of the animation just holds 3 images with different rotations and positions.

That’s all, I suggest you play with the random animate button, for fun 🙂