Set timeout on Web Service proxy generated by Flex Builder

Flex Builder has a pretty nifty WSDL tool to generate support classes to access a Web Service.
Some of the code generated looks rather sloppy though, but then that is the case with most code generation tools.

One glaring omission seems to be that there is no way to set a request timeout when using the Service class generated.
What further adds to confusion is that the underlying Service class in fact extends mx.rpc.AbstractWebService and hence mx.rpc.AbstractService which has a requestTimeout property. Setting that property has no effect however.

To set a timeout on the request, you need to modify the Flex Builder generated class.

Find the method that actually makes the call to the remote server, and set the requestTimeout value on the AsyncRequest being created

private function call(operation:WSDLOperation, args:Object, token:AsyncToken, headers:Array=null):void
{    
  var enc:SOAPEncoder = new SOAPEncoder();
  …    
  var inv:AsyncRequest = new AsyncRequest();    
  inv.requestTimeout = _asyncRequestTimeout;
  …    
  inv.invoke(message,processRes);
}

And add an asyncRequestTimeout property to the service class

private var _asyncRequestTimeout:int;
public function set asyncRequestTimeout(asyncRequestTimeout:int):void        
{            
  _asyncRequestTimeout = asyncRequestTimeout;        
}

You could also use the asyncRequest property in AbstractService instead of creating your own property, but this way if somebody overwrites the generated class without adding these changes, the compiler will flag it as an error.
And a compile time error is always better than a runtime bug, isn’t it?

Creating a Viewport in Android

I was writing a simple PacMan like game for Android, and needed to scroll the game area shown as the user moves inside it. In J2ME, you will use LayerManager.setViewWindow to create this kind of Viewport like behaviour. In Android, this can be achieved by using methods in Canvas and View classes.

Here is a simple program demonstrating how to do it –

public class AViewport extends Activity
{

 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView( new PortView( this ) );

 }

 private class PortView extends View
 {
 // the length and width of a single square
 private int tileSide = 50;
 // the number of squares along x-axis and y-axis
 private int numTiles = 15;

 int fieldWidth = numTiles * tileSide;
 int fieldHeight = numTiles * tileSide;

 private int halfViewWidth;
 private int halfViewHeight;
 private int maxTranslateX;
 private int maxTranslateY;

 int viewWidth = 200;
 int viewHeight = 200;

 private int circleX;
 private int circleY;
 private int diameter = 50;

 private ShapeDrawable one;
 private ShapeDrawable two;

 private ShapeDrawable circle;
 Rect rect = new Rect();
 private Paint p;

 public PortView( Context context )
 {
 super( context );
 one = new ShapeDrawable( new RectShape() );
 two = new ShapeDrawable( new RectShape() );
 circle = new ShapeDrawable( new OvalShape() );
 one.getPaint().setColor( 0x88FF8844 );
 two.getPaint().setColor( 0x8844FF88 );
 circle.getPaint().setColor( 0x99000000 );
 p = new Paint();
 setFocusable( true );
 }

 @Override
 protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec )
 {
 int width = Math.min( fieldWidth, MeasureSpec.getSize( widthMeasureSpec ) );
 int height = Math.min( fieldHeight, MeasureSpec.getSize( heightMeasureSpec ) );

 viewWidth = width;
 viewHeight = height;
 halfViewWidth = width/2;
 halfViewHeight = height/2;
 maxTranslateX = fieldWidth - width;
 maxTranslateY = fieldHeight - height;

 setMeasuredDimension( width, height );
 }

/*
 _______________________________________
 | ______________                        |
 ||              |                       |
 ||              |vH                     |
 ||              |                       |
 ||______________|                       |
 |       vW                              |fH
 |       .(x1, y1)         ______________|
 |                        |              |
 |                        |              |
 |<---------------------->|              |
 |     maxTranslateX      |______________|
 |_______________________________________|
 fW

 We start translating once x,y goes past x1 (viewWidth/2),y1 (viewHeight/2).
 Movement along x-axis is x - x1, to the maximum of maxTranslateX (fieldWidth - viewWidth).
 The movement along y-axis is calculated similarly.
*/
 @Override
 protected void onDraw( Canvas canvas )
 {
 super.onDraw( canvas );

 canvas.save();

 if ( circleX > halfViewWidth )
 {
 int translateX = Math.min( circleX - halfViewWidth, maxTranslateX );
 canvas.translate( -translateX, 0 );
 }

 if ( circleY > halfViewHeight )
 {
 int translateY = Math.min( circleY - halfViewHeight, maxTranslateY );
 canvas.translate( 0, -translateY );
 }

 drawBoard( canvas );
 drawCircle( canvas );
 canvas.restore();
 }

 private void drawBoard( Canvas canvas )
 {
 int num = 1;
 boolean useTwo = false;
 for ( int row = 0; row < numTiles; row++ )
 {
 int y = row * tileSide;
 for ( int col = 0; col < numTiles; col++ )
 {
 int x = col * tileSide;
 Drawable d = useTwo ? two : one;
 d.setBounds( x, y, x + tileSide, y + tileSide );
 d.draw( canvas );
 canvas.drawText( "" + num, x + 10 , y + 20, p );
 ++num;
 useTwo = !useTwo;
 }
 }
 }

 private void setRect()
 {
 rect.set( circleX, circleY, circleX + diameter, circleY + diameter );
 }

 private void drawCircle( Canvas canvas )
 {
 setRect();
 circle.setBounds( rect );
 circle.draw( canvas );
 }

 @Override
 public boolean onKeyDown( int keyCode, KeyEvent keyEvent )
 {
 boolean handled = true;
 switch ( keyCode )
 {
 case KeyEvent.KEYCODE_DPAD_DOWN:
 if ( circleY <= fieldHeight - diameter - 5 ) circleY += 5;
 break;
 case KeyEvent.KEYCODE_DPAD_UP:
 if( circleY >= 5) circleY -= 5;
 break;
 case KeyEvent.KEYCODE_DPAD_LEFT:
 if( circleX >= 5 ) circleX -= 5;
 break;
 case KeyEvent.KEYCODE_DPAD_RIGHT:
 if( circleX <= fieldWidth - diameter -5 ) circleX += 5;
 break;
 default: handled = false;
 }
 if ( handled )
 {
 invalidate();
 }
 return handled;
 }
 }
}

See the Android API docs of View.onMeasure() and Canvas.translate() methods to understand the code used to create the Viewport.

Code Amnesia context sensitive code search

Code Amnesia looks like a really interesting project.

It allows you to search online for code snippets from within your IDE. The cool thing is that the search is context sensitive. It takes into account the code you are currently editing, which means it can merge the selected snippet into your code.

I don’t think I could use it much in my current work. But, if I was working as a consultant, often working on new projects that used different frameworks, I can see this being a real time and sanity saver.

This is a fairly new project, and only supports Intellij IDEA at the moment. It will be interesting to see what it leads too.

Android on Intellij Idea – run activity on emulator

The official Android plugin is only for Eclipse, but thankfully Android provides Ant support for those of us who prefer other IDEs (http://developer.android.com/guide/developing/other-ide.html).

I use Intellij IDEA, and the main problem for me was that, after building the application using the Ant build script created by activitycreator tool, you have to manually reload the application in the emulator.

This is easily fixed by tweaking the generated Ant build file.
Add the following target to the build.xml –

 <!-- Main activity -->
<property name="main-activity" value="MyMainActivity" />

 <!-- Run the main Activity after reinstall -->
 <target name="run" depends="reinstall">
 <echo>Running ${application-package}.${main-activity} on default emulator...</echo>
 <exec executable="${adb}" failonerror="true">
 <arg value="shell" />
 <arg value="am" />
 <arg value="start" />
 <arg value="-a" />
 <arg value="android.intent.action.MAIN" />
 <arg value="-n" />
 <arg value="${application-package}/${application-package}.${main-activity}" />
 </exec>
 </target>

MyMainActivity is, of course, your main activity. Remember to change the build file if you rename or change the main activity.

I also changed the default target to run, and after loading build.xml as an Ant build file in IDEA, I assigned it a shortcut key.
I also made these changes to ANDROID_SDK/tools/lib/build.template, so from now on, when I create a new Android project, it is already set up this way. If you are editing the template file, use –

 <!-- Main activity -->
<property name="main-activity" value="ACTIVITY_NAME" />

This will automatically pick up the class name you specify on the command line when running activitycreator.

Object equality in Java

The first time I paid attention to the equals() method was when preparing for SCJP exam, where you have to know what the output of some lines of code will be. That was simple enough – follow the logic of the code, and make sure that you are not accidentally overloading equals instead of overriding it.

A few years later, I revisited equals() ( and hashcode() ) when reading Joshua Bloch’s Effective Java. Chapter 3, “Methods Common to All Objects” shows how to, and why you should, properly implement equals() method. This must be required reading for every Java programmer, even if you ever only write CRUD applications in Struts, and are never going to use any of it.

Recently, I read Angelika Langer‘s article on this subject. If, like me, you have read the Effective Java book, and think that you know all that you need to about Object equality, think again!

Angelika Langer and Klaus Kreft disect various approaches to implementing equals() – Secrets of equals().

The gist of it is that although implementing equals() for a final class, or a class with a final equals() method is reasonably straightforward, there is no one correct way of doing that with mixed-type comparisons allowed between objects of different types in the same class hierarchy.
The second thing to keep in mind is that if you are overriding a class that implements equals(), and you override the equals() method you have to pay particular attention to whether the superclass’s equals() method allows mixed-type comparisons or not –

If the designer of such a non-final class decides in favor of implementing equals() using instanceof , then no subclass can ever add fields and override equals() without violating the transitivity requirement of the equals() contract.
If the designer decides in favor of implementing equals() using getClass() , then no subclass object will ever be comparable to a superclass object and trivial extensions may not make a lot of sense.

There is a follow up article showing one way of Implementing equals() To Allow Mixed-Type Comparison.

Creating a daily log in Evernote from Quicksilver

Recently I started using Evernote, and I am loving it so far.
If you are looking for a way to organize the “stuff” on your computer, check it out.

One of the things I am trying to use it for is to keep a daily log of things I do, so that, at the end of the day or the week, I can check how productive (or not) I have been.

Taking inspiration from this story on Mac OS X Hints ;), and with some help from the kind folks at Evernote developer forum, I put together this simple script to create a note in my daily diary from Quicksilver –


property nb : "Daily Diary"

using terms from application "Quicksilver"
 on process text qtxt
 my CreateDailyEvernote(qtxt)
 end process text
end using terms from

on CreateDailyEvernote(txt)
 set t to do shell script "date +'%Y/%m/%d'"
 tell application "Evernote"
 set foundNotes to find notes "notebook:"" & nb & """ & " intitle:"" & t & """
 set found to ((length of foundNotes) is not 0)
 if not found then
 create note with text txt title t notebook nb
 end if
 activate
 end tell
end CreateDailyEvernote

This will create a note with title as current date in the format yyyy/mm/dd in “Daily Diary” notebook.
At the moment, Evernote Mac scripting API does not allow appending text to an existing note.
Once that is added (a very helpful Andrew McGeachie at the Evernote developer forum has already created a feature request for that), this would be a perfect way for me to keep a log of everything I do during the day.

Groovy with spice – curried closures

Groovy rocks!

I have used Groovy swing builder before to layout some basic Swing UIs, but recently I used it for the first time for some real scripting. It was a script to do some database maintenance, and I was amazed at how easy, fun and productive Groovy can be.

What surprised me most was how easy it was to refactor as I went along. I had assumed that it will be inherently more difficult to modify it without static typing and full IDE support. Not the case at all, although it was a single script, and so things might be different if it is a Groovy program spread over multiple scripts.

Incidentally, the Codehaus Groovy Closures page has the easiest to understand explanation of what curried functions are –

You can fix the values for one or more arguments to a closure instance using the curry() method from the Closure type. In fact, this action is often referred to as currying in functional programming circles, and the result is generally referred to as a Curried Closure. Curried closures are very useful for creating generic closure definitions, and then creating several curried versions of the original with differing parameters bound to them.

I had glanced over curried functions in past, and it always looked like something that I will have to sit down and write some code to fully understand. But this explanation just clicked instantly. Thanks to whoever wrote this; I am sure I will find a use for it again soon.

Some programming blog recommendations

First one up is Brian Oxley’s blog, which I have been reading for a while now. He writes only occasionally, but almost all his posts have solid, relevant content. Exactly the kind of technical blog I like to read.

Chris Ashton is the newest entry on my blogroll, informative and entertaining.
He mostly uses C++ C# when talking about programming, but all the posts I read were programming language neutral.
Here’s something from his post on brainstorming that made me laugh out –

Today I’m able to articulate exactly what bugged me about that meeting, namely: there were no customers in that room. Or outside of it, for that matter. All we had was a bunch of devs pulling shit out of their asses and trying to pretend that someday, somewhere a customer might want to have this hypothetical product with all these features, even so much as to pay real money for it. We had this illusion that we were super creative geniuses and coming up with all these new ideas, but really we were just wanking. Hell, the ideas weren’t all that novel anyways.

Spot on, mate.

And finally, recently rediscovered thanks to Brian, is Ivan Moore’s Programming in the small series. Short sweet nuggets of programming wisdom. Check it out!