Archive for the ‘Java’ Category.

Android Beer timer Widget

A friend of mine said he wanted a beer app for the Android, really what’s that ? It goes something like this, a beer glass on your Android desktop. The beer glass fills up from 9am to 5pm, once it’s full, well then it’s time to stop working and go out for a beer. On the weekends the glass is always full of course. This would have to be a widget on the desktop so the image / icon can be changed on a timer through the day. Since I hadn’t written an Android widget before, I told my friend, no problem I will write it for you.

Lets declare the widget in the manifest, the service and the alarm receiver as well.

<receiver android:name=“.FxBeerWidget” android:label=“Beer time widget”>
  <intent-filter>
    <action android:name=“android.appwidget.action.APPWIDGET_UPDATE” />
  </intent-filter>
  <meta-data android:name=“android.appwidget.provider” android:resource=“@xml/beerwidgetlayout” />
</receiver>
<service android:name=“.CxUpdateWidgetService” />
<receiver android:name=“.CxBeerAlarmReceiver” />

Then in the AppWidgetProvider we use AlarmManager to update our receiver

// Setup receiver that will call the widgetService     
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent2 =  PendingIntent.getBroadcast(context, 0,
      new Intent(context, CxBeerAlarmReceiver.class),  PendingIntent.FLAG_CANCEL_CURRENT);
// Use inexact repeating which is easier on battery (system can phase events and not wake at exact times)
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 500, (60*1000), pendingIntent2);

Note that you have to be mindful of the resources you are using and use a long interval. If the person using the phone is playing a game for example when the timer goes off. You do not want to take much resources in order for his game to keep playing smoothly. In our case it’s a simple check and a quick update of a icon if needed.

The CxBeerAlarmReceiver is a BroadcastReceiver which when woken up will start the CxUpdateWidgetService which is a IntentService. The CxUpdateWidgetService will take care of updating the widgets.

public static void updateAllWidgets(Context context)
{
  //
  final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
  final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, FxBeerWidget.class));

  // Remote view for the widget
  RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.beerwidget );
       
  // Setup the beer main Activity as Intent
  Intent beerIntent = new Intent();
  beerIntent.setClass( context, FxMain.class);
  beerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  // Setup pending intent, when widget clicked show main screen
  PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, beerIntent, 0);
  views.setOnClickPendingIntent(R.id.Widget, pendingIntent);
        
  // Time status
  int iCurrentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
  // Format it in clock like format, leading zero
  views.setTextViewText( R.id.lbStatus, CxUtil.getTimeString() );
       
  // Update image only if needed
  int plusNum = whichIcon( iCurrentHour);
  CxLog.d( CxLog.TOKEN, “updating beer image, currhour=” + iCurrentHour + “, plusNum=” + plusNum   );
       
  // Set the current image
  views.setImageViewResource( R.id.widgetImage, R.drawable.beer72_0  + plusNum );
       
  // Associate the update views – Loop all id’s
  for(int i=0; i<appWidgetIds.length; ++i)
     AppWidgetManager.getInstance(context).updateAppWidget( appWidgetIds[i], views );
}

Note that the user can have more than more widget running, there could be one on each desktop, etc. The for loop will take care of that and update all of the widgets. Another cotcha is that you will have to set the click intent for the widget each time the update function is called. Otherwise it will get disconnected from the widget and clicking the widget will not open the FxMain screen.

Here is the Widget if you like to download and install on your Android – BeerTimeWidget

Here is how it looks in action.

Java log4J

I had the need to log from a java project I just created. Never used log4J before but heard good things. Man do I love it when things are simple and that’s just what log4J is. Download and extract the jar, in my case log4j-1.2.16.jar add it to your classpath and your off to the races. When reading the install document, they have what you need to get up and running ASAP a small HelloWorld that will get you going.

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
   
public class Hello
{
      private static final Logger logger = Logger.getLogger(Hello.class);
      public static void main(String argv[])
      {
        BasicConfigurator.configure();
        logger.debug(“Hello world.”);
        logger.info(“What a beatiful day.”);
      }
}

Create the file from the sample and compile
> javac Hello.java
and run it
> java Hello

It will give the following output
0 [main] DEBUG Hello – Hello world.
6 [main] INFO Hello – What a beatiful day.

Yes, super simple, of course it has all the bells and whistles you might need. Like logging just for a specific class or just at a certain level, log to file etc, etc,

UPDATE
Then you can create xml file and configure the appenders from there, below is a sample of console appender and then a file appender. To set it in code, you can use the following.

PropertyConfigurator.configureAndWatch( “log4j_config.xml” );

That will instruct log4J to monitor your configuration file. If you want to change the configuration on the fly all you need to do is to change your configuration file, log4J checks for changes every 60 seconds. You can also call with additional parameter setting your own frequency.

# Set root logger level and appenders
log4j.rootLogger=INFO, console, rollingFile

# Console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss,SS} %-4r [%t] %-5p %c %x – %m%n

# Rolling file appender
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=mylog.log
log4j.appender.rollingFile.MaxFileSize=5MB
log4j.appender.rollingFile.MaxBackupIndex=20
log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss,SS} %-4r [%t] %-5p %c %x – %m%n

Java Postgres connection sample

I had to setup Postgres on my linux box, configure and make sure it was working. Since that was the case I started the install, then wrote a very simple Java program to connect and retrieve some data from one of the database tables. The install is simple and pretty easy to google. Once your Postrgres database is up and running you should be able to connect to it. You will need a java Postgres database driver, the one I downloaded was the postgresql-9.1-901.jdbc4.jar then add the jar to your project. And finally to make sure your database is accessible from a program you can use the sample below.

//
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

// Simple test class to prove connection to Postgres database
public class Main
{

        public Main()
                { super(); }

        public static void main(String[] args)
        {
       
                System.out.println(” Postgres Test”);
                Connection myConn = null;
               
                try
                {
                        // The driver
                        Class.forName(“org.postgresql.Driver”);
                        System.out.println(“PostgreSQL JDBC Driver Registered!”);
               
                        myConn = DriverManager.getConnection( “jdbc:postgresql://127.0.0.1:5432/testDb”,
                                        “testUser”, “myPassword” );

                        // Connected ?
                        if (myConn != null)
                                System.out.println(“Successfully connected to Postgres Database”);
   
                        // Get data from the database
                Statement stGetCount = myConn.createStatement();
            ResultSet rs = stGetCount.executeQuery(“SELECT * from  cars”);
           
            while( rs.next() )
            {
                System.out.println(“result=” + rs.getString(1) + “,” + rs.getString(2) + “,” + rs.getString(3) );
            }
        }
        catch( Exception ex )
        {
            ex.printStackTrace();
        }
        finally
        {
                try{myConn.close();}catch(Exception IDontCare ){}
        }

        }
       
}  // EOC
 

TeamCity Twitter plugin, part 2

I had to fix an old plugin I made some time back, I did actually post about it here Java Authenticated POST. So why bring it up again, a good question I say. As Twitter changed their authentication sometime late last year ( Nov 2010 ? ). All programs using the old authentication stopped working. I hadn’t had / given myself time to look at the broken plugin. What the TeamCity twitter plugin does it to tweet when the TeamCity server starts and ends builds. If you follow that account you get notified on Twitter without having to open up your email box to see how your builds are doing.
I went googling about the new authentication and found a nice snippet on StackOverflow The snippet uses Twitter4J library to make the task really simple, check them out. The best part is that Twitter4J only needs Java 1.4 to run. That’s great as my TeamCity server only has Java 1.5 and not the newer 1.6, further as an added bonus their core jar is only 280k, that’s all I needed. Below is my code modified from the StackOverflow sample. It works fine if you are only posting to one account. The tokens and keys can be found on your Twitter app page. If you need to post for different users from your application then your code needs to take that into account. If you want the source of the plugin or all 3 plugins I have created, you can run over to GitHub and pick it up. I made it public domain, open source, whatever you want to call it.

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.*;;

   // Updates the twitter account
   public static void sendTweet( String psText )
   {
           try
           {
                        // Configuration
                        ConfigurationBuilder confbuilder = new ConfigurationBuilder();
                        confbuilder.setOAuthAccessToken(CxGlobal.ACCESS_TOKEN_KEY)
                        .setOAuthAccessTokenSecret(CxGlobal.ACCESS_TOKEN_SECRET)
                        .setOAuthConsumerKey(CxGlobal.CONSUMER_KEY)
                        .setOAuthConsumerSecret(CxGlobal.CONSUMER_SECRET);
                                               
                        // get the interaction object
                        Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance();
                        // send
                        twitter4j.Status status = twitter.updateStatus( psText );
                        //
                        //System.out.println("*** Response=" + status.getText() );
           }
           catch( Exception ex )
           {
               System.out.println( “***ERROR=” + stack2string( ex ));
               LOG.info( “***ERROR=” + stack2string( ex ) );
           }
   }

Edit, the 3 plugins have now been added to the official TeamCity PlugIn page

Android code sample

I wanted to try some smart phone development. I started with Mac OsX in a VirtualBox got the Os installed on the virtual machine, but it wouldn’t boot for me after install. As I was fiddling with that on my Windows box to do iPhone development I thought this is way harder than it’s supposed to be.

Then I thought let’s see how this compares to doing Android development. Went to the Android SDK site and got the SDK which integrates with Eclipse very easily. The installs are just a few clicks of a button and your all set. Of course they have a Hello world sample that you will have running in Android emulator in matter of minutes. The install instructions show how to setup different devices under the emulator etc.

Now what about something more than just Hello world, the SDK comes bundled with all kind of samples, both controls and graphics along with more elaborate Google maps location based samples. It has plenty of stuff to get you going. The great thing is that the code is plain old Java so if you have done any Java or C# development you will feel right at home.

I wanted to do something basic before going into any real development. My idea is to create a simple calculator to calculate handicap score. I used to play pool and we would have a simple handicap system that needed to be referenced to calculate the race between two people that have been matched up.

When Android project is created in Eclipse it will create a bunch of files, resources, manifest, etc. and the main Activity class. The Hello world sample creates control dynamically in code but that can be hard to maintain when your project increases in size. The way to do it is to declare the controls in a XML resource file and then reference it in code. I didn’t see a editor to handle the controls visually but I’m sure there are some out there.

For a simple app the XML is found under res/layout/main.xml in my case it will look like this.

<?xml version=“1.0” encoding=“utf-8”?>
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
    android:layout_width=“fill_parent”
    android:layout_height=“fill_parent”>

    <TextView
        android:id=“@+id/lbPlayer1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:text=“Handicap Player1:”/>

    <EditText
        android:id=“@+id/txPlayer1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbPlayer1”/>

    <TextView
        android:id=“@+id/lbPlayer2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txPlayer1”
        android:text=“Handicap Player2:”/>

    <EditText
        android:id=“@+id/txPlayer2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbPlayer2”/>

    <Button
        android:id=“@+id/btOk”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txPlayer2”
        android:layout_alignParentRight=“false”
        android:layout_marginLeft=“10dip”
        android:text=“Calculate” />

    <TextView
        android:id=“@+id/lbMustWin1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/btOk”
        android:text=“Number of games Player1 must win:”/>

    <EditText
        android:id=“@+id/txMustWin1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbMustWin1”/>

    <TextView
        android:id=“@+id/lbMustWin2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txMustWin1”
        android:text=“Number of games Player2 must win:”/>

    <EditText
        android:id=“@+id/txMustWin2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbMustWin2”/>

       
</RelativeLayout>

Things to notice are the id’s of the controls they need to be unique and how the layout is done for each control you specify where it should show up relative to other controls. That way the manager rendering your view can order them and it will look pretty good.

As I mentioned before the code is in java.

//
package hello.world;
//
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class helloActivity extends Activity implements OnClickListener
{

        /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // The usual
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
       
        // Wire up click event
        Button button = (Button)findViewById(R.id.btOk);
        button.setOnClickListener(this);
    }
   
   
    // Implement the OnClickListener callback
    public void onClick(View v)
    {
        // Input from user
        String sPlayer1 = ((EditText)this.findViewById( R.id.txPlayer1)).getText().toString().trim();
        String sPlayer2 = ((EditText)this.findViewById( R.id.txPlayer2)).getText().toString().trim();
       
        // Turn into doubles
        double[] players = {0,0};
        players[0] = Double.parseDouble( sPlayer1 );
        players[1] = Double.parseDouble( sPlayer2 );
       
        // Calculate
        calculate( players );
       
        // Set the results
        ((EditText)this.findViewById( R.id.txMustWin1 )).setText( “” + (int)players[0] );
        ((EditText)this.findViewById( R.id.txMustWin2 )).setText( “” + (int)players[1] );
    }
     
    // Calculates handicap
    private static void calculate( double[] pdaPlayers )
    {
        // STRONGER is lower handicap
        // See who is better rated coming in,
        boolean bStrongerFirst =  pdaPlayers[0] < pdaPlayers[1];
        // Holds results
        double strong_race, weak_race;

        if( bStrongerFirst )
        {
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[1] ));
            strong_race = weak_race + Math.round( pdaPlayers[1] – pdaPlayers[0] );
            // set the slots before returning
            pdaPlayers[0] = strong_race;
            pdaPlayers[1] = weak_race;
        }
        else
        {
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[0] ));
            strong_race = weak_race + Math.round( pdaPlayers[0] – pdaPlayers[1] );
            //  Set the slots before returning
            pdaPlayers[0] = weak_race;
            pdaPlayers[1] = strong_race;
        }
    }

}  // EOC
 

The onCreate function is the main function of the activity, to get button click event it will be setup there. The rest is straight forward and activated when the user clicks the button. The controls are addressed by R.id.xxxx which is the resource id’s given to each control in the layout XML. The R mapping is created when the project is compiled. For this simple sample, the user input is retrieved and used to calculate handicap which is then presented back to the user in controls below.

The app running in Android emulator
androidhandicap1

Update
—–
I just didn’t find the visual editor, it’s there in Eclipse it shows as tab when you open up the xml file. It’s very primitive one might be better off to use DroidDraw

Selenium browser UnitTesting from TeamCity

I just setup browser testing framework utilizing Selenium from TeamCity project. The usual suspects are involved, Gallio, MBUnit, Nant and even C# Unittests.

The usual scenario when it comes to automating browser testing is that the QA / testers will create some scripts to run a browser against your website. Somehow those tests are usually not maintained very well and often are run by hand. There is not much value in browser testing scripts if you have to run them by hand.

As I needed browser testing on one of the projects I’m on I decided to look into using more of a automated setup to run the browser tests. There seem to be two big players Waitn and Selenium, Selenium lends itself to broader range of testing, naturally we will go with Selenium.

Here is the scenario I want, the tester installs a recorder on his computer, in this case a FireFox plugin. The tester records the tests and runs them in the browser using the plugin tool. Once the tester is happy with the tests the tester checks them into the repository. After check-in tester lets a developer know that there are new or changed tests. The developer takes the script and turns it into C# UnitTest, simply has Selenium convert it to UnitTest code. Then the developer takes and updates or adds the tests that resulted from the scripts and checks it into the repository. The conversion step could be automated in the future once Selenium supports that. The next step is to run it from TeamCity and after it runs you get email with the results.

So let’s take a closer look at what is needed. We need the UnitTest to be able to run against different servers using different browsers. We will pass values from TeamCity to the Nant script that is responsible for compiling and running the tests. This is how your test C# configuration file might look like.

<!– Selenium RC properties–>
    <add key=“SeleniumAddress” value=“localhost” />
    <add key=“SeleniumPort” value=“4444” />
    <add key=“SeleniumSpeed” value=“0” />
   
    <!– Browser targets –>
    <add key=“BrowserType” value=“*firefox” />
    <add key=“BrowserUrl” value=“http://10.9.169.198/” />
    <add key=“BaseUrlPath” value=“IPCA.Dev/” />

Then the base test class will look something like this.

[FixtureSetUp]
        public virtual void TestFixtureSetup()
        {
            // Read from config
            msBrowserType = getConfigSetting(“BrowserType”, msBrowserType );
            msBrowserUrl = getConfigSetting(“BrowserUrl”, msBrowserUrl);
            msBasePath = getConfigSetting(“BaseUrlPath”, msBasePath);
            //
            msSeleniumAddress = getConfigSetting( “SeleniumAddress”, msSeleniumAddress );
            miSeleniumPort = int.Parse(getConfigSetting(“SeleniumPort”, miSeleniumPort.ToString()) );
            msSeleniumSpeed = getConfigSetting( “SeleniumSpeed”, msSeleniumSpeed );
           
           
            // Start up the selenium session, using config values
            selenium = new DefaultSelenium(msSeleniumAddress, miSeleniumPort, msBrowserType, msBrowserUrl);
            selenium.Start();
            // Clean errors
            verificationErrors = new StringBuilder();

            // sets the speed of execution of GUI commands
            selenium.SetSpeed(msSeleniumSpeed);
        }

        [TearDown]
        public void TeardownTest()
        {
            try
            {
                selenium.Stop();
            }
            catch (Exception)
            {
                // Ignore errors if unable to close the browser
            }
            Assert.AreEqual(“”, verificationErrors.ToString());
        }

And a sample Selenium C# Unittest

//
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
//
using Gallio.Framework.Assertions;
using MbUnit.Framework;
//
using Selenium;

namespace SeleniumTests
{
    [TestFixture]
    public class LoginPage : WebTestBase
    {

        [Test]
        public void TheLoginPageTest()
        {
            selenium.Open( this.msBasePath + “TestLogin.aspx”);
            selenium.Click(“lbAdmin”);
            selenium.WaitForPageToLoad(“50000”);
            selenium.Click(“loginLink”);
            selenium.WaitForPageToLoad(“50000”);
            try
            {
                Assert.IsTrue(selenium.IsTextPresent(“my responsibilities regarding permissible access”));
            }
            catch (AssertionException e)
            {
                verificationErrors.Append(e.Message);
            }
            selenium.Click(“ctl00_pageContent_btnSubmit”);
            selenium.WaitForPageToLoad(“50000”);
            try
            {
                Assert.IsTrue(selenium.IsTextPresent(“Total Unassigned Web”));
            }
            catch (AssertionException e)
            {
                verificationErrors.Append(e.Message);
            }
        }
    }
}

After the Nant script compiles the tests and is getting ready to run the UnitTests it needs to startup the Selenium engine. Make sure to spawn in order for the Selenium engine to exist on another thread than your tests.

<property name=“SeleniumExec” value=“java” />
  <property name=“SeleniumPath” value=“C:\apps\selenium\selenium-server-1.0.3\” />
  <property name=”SeleniumParams” value=”-jar ${SeleniumPath}selenium-server.jar” />

    <!– Start selenium –>
    <exec   program=”${SeleniumExec}
      commandline=”
${SeleniumParams}” workingdir=”${path.base}${WebTest}
      spawn=”
true” failonerror=”true” verbose=”true
       />

    <!– Give it a sec to load –>
    <sleep milliseconds=”3000” />

In order to run the tests using different browsers, change the configuration file of the tests before run.

<!– Run tests in Firefox browser –>
    <xmlpoke
        file=“${path.base.test}${assembly.test.config}”
        xpath=“/configuration/appSettings/add[@key=’BrowserType’]/@value”
        value=“*firefox”
        verbose=“true”/>

    <call target=“runTests” />

<target name=“runTests”
    description=“runs tests using Gallio.” >

   
    <echo message=“*** Start runTests: “/>

      <gallio
        result-property=“exitCode”
        failonerror=“false”
        report-types=“Html;Xml”
        report-directory=“${artifacts}”
        report-name-format=“gallioresults”
        show-reports=“false”
        application-base-directory=“${path.base.test}”
            >

          <!– Specify the tests assemblies  –>
          <files>
            <include name=“${path.base.test}${assembly.test}”/>
          </files>
        </gallio>

        <!–
            Set error for email injector to pick it up and GlobalFailBuildMessage for
            the end target to fail the build after cleanup
          –>

        <if test=“${int::parse(exitCode)!=0}”>
          <property name=“GlobalFailBuildMessage” value=“*** One or more tests failed. Please check the log for more details” dynamic=“true” />
          <echo message=“EmailInjectMsg=${GlobalFailBuildMessage}” />
        </if>

    <echo message=“*** End runTests: “/>
  </target>

And after the run of the Unittests Selenium needs to be shut down

<!– Stop Selenium server –>
      <get  src=“http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer”
        dest=“shutdown.txt”  failonerror=“false”
      />

As I had a need to setup different configurations in TeamCity to run against different locations on the webserver I used a couple of Nant variables that are passed on the command line from TeamCity, like you normally would do when running Nant script -D:BaseUrlPath=/Test/ etc.

<echo message=“*** Location variables passed from TeamCity”/>
    <echo message=“*** BrowserUrl=${BrowserUrl} “/>
    <echo message=“*** BaseUrlPath=${BaseUrlPath} “/>

Of course you get the Gallio UnitTest report as well

gallio_report

With this setup once we deploy to a server we can run all the browser tests on it using different browsers with one click of a button from TeamCity.