HelloWorld deploy on Google Application Engine 1.6.4

I have seen a bunch of tutorials on how to deploy on the Google App Engine. Let me tell you my experience as well, no it does not take 5 minutes, it’s more like 15-20 minutes to get HelloWorld app going.

First you need application account, go to the location below, login with your Google account and create your own application

https://appengine.google.com/

I use Eclipse ( Indigo ), so let’s look at how you install the Google Engine / SDK and plugin from there. The App Engine just got update to version 1.6.4, naturally that’s what we will use.

Help -> Install New Software

Use the Google Eclipse Indigo ( ver 3.7 ) feed

http://dl.google.com/eclipse/plugin/3.7

You can skip the Android stuff, just check the other 3 check boxes and start your downloads, you will have to Accept the license etc, it’s self explanatory.

After a few long minutes of downloads Eclipse will ask for a restart to install everything properly and you will be in business.

Create a new project,
File -> New -> Other -> Google -> Web Application Project

This will create a sample Google Application Engine project for you.

Then simply choose the blue (g) icon from the toolbar menu, and choose Deploy to App Engine… You will be asked for account info etc, and you will connect this deployment with the app you created in the beginning. Now watch the Console portion as the info about your deployment are displayed until you get success info. Then you can go to your application URL and see your new project in action. To find the URL you can goto My Applications in the Google app dashboard, it will have links on the right ( instances ) click on the link there and it will take you to your app.

Your URL will be something like

http://yourapp.appspot.com/

Its worth to mention that Google will host your app for free, as long as you don’t exceed certain resource limits. They actually have generous free limits, you can read more about the limits and what else you can buy in terms of resources here. You can actually host your own domain on the Google App Engine as long as it’s not a naked domain, That is you will be able to host www.mydomain.com but you will not be able to host mydomain.com. That’s really because of security, you can find further reading about that here.

That’s all, happy coding !

Tomcat multiple instances on Linux, Ubuntu / Mint

I was trying to figure out how to run multiple instances of Tomcat6 the other day on my Mint Linux. After a bit of searching and poking around I came to a very slick solution. But it took a while to find it, so I figure I will share the quick and dirty here, to get you up going quickly if your searching for the same.

Lets go through the whole thing, install Tomcat6
>sudo apt-get install tomcat6

You might have to set your java path if not set already, for example
>export JAVA_HOME=/usr/java/jdk1.6.0/bin/java
To check the setting
>echo $JAVA_HOME

You probably want to install the examples as well, just to mae sure things are working servlets, jsp etc,
>sudo apt-get install tomcat6-examples

If all is well as you would fully expect, you can start your Tomcat
>sudo sh /etc/init.d/tomcat6 start

And in return you will be able to access your tomcat in your browser at

http://localhost:8080

So lets take a look at how to configure multiple instances on the same linux box. Go to a directory where you want your new tomcat instance located. Then you do something like this
>tomcat6-instance-create myInstance

This will create a new directory called myInstance which will host your new instance of Tomcat. It will have it’s own configuration files, logs, etc. The first thing you probably want to do is to go to the config directory and change the ports in the server.xml file. Once you have the ports changed from the usual 8080 you can start your instance from /myInstance/bin directory.
>sh startup.sh

Just as you would with any other instance of Tomcat and shut down with the shutdown.sh script. Next time you need another instance on another port just create a new one
>tomcat6-instance-create myInstance_8030
and so on and so forth.

All the details can be found in the Ubuntu documentation.

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

PostgreSQL geo locations with PostGIS

I been playing with some geo location data. Naturally when working with the data one needs to save it to a database for later retrieval and selection. If you happen to be using Postgres your in luck. You can add the PostGIS extension that will make your database OpenGIS compatible.
The most important thing is to have geo location aware database when dealing with geo data. That means that you can select objects using proximity right out of the database. It makes easy to figure out how far away different locations are, what are the nearest locations etc. If you don’t have geo location aware database you would have to figure out the proximity in code. Of course that would mean a lot of calculations and CPU cycles.

How I set it up on my Ubuntu / Mint linux box. First install PostGIS on the box then you want to add it to your database as below.

createlang plpgsql yourdatabase
cd /usr/share/postgresql/8.4/contrib/postgis-1.5
psql -d yourdatabase -f postgis.sql
psql -d yourdatabase -f spatial_ref_sys.sql

Then make sure PostGIS has been added to the database.

SELECT PostGIS_full_version()
1.5 USE_GEOS=1 USE_PROJ=1 USE_STATS=1

Couple examples of usage.

To see how far away from my place ( Boulder ) some locations in the database are.
SELECT Distance(geom, SetSRID(MakePoint( 40.0150, -105.2705 ),4326)) FROM location_geo;
Then get the five closest ones to my place
SELECT * FROM location_geo ORDER BY distance(geom, SetSRID(MakePoint( 40.0150, -105.2705 ),4326)) LIMIT 5;

You can even set boundaries, use polygons etc.

It’s time for daily Linux Mint

I have always run my Linux on a hand me down box. My current computer, the one I’m using daily always runs some flavor of Windows. When I buy a new computer as the old one isn’t fast enough I will take the current one and make it my new Linux box. As such the Linux box is always one generation or more behind. That means old hardware that doesn’t even have good graphics.
It is that time again, I need a new computer soon. As I was thinking about it I was thinking how well my Linux desktop will run on the new hand me down window box after all it’s still pretty powerful. Then I thought, I have been saying to myself for years that I should start running Linux as my daily computer. I never felt it’s quite “there”, but with my latest Linux desktop experience on Mint 10 I really think it’s “there”.
I do also know why I think its really there, there were two problems that bothered me in the past. The graphics and the resolution on the desktop were just not good enough. I could never get it right on Ubuntu, after I switched to Mint it was practically setup for me automatically. Something I had been digging for both from control panel config settings and lower lever configuration on Ubuntu, it just didn’t happen. The second thing is that I’m used to the windows keyboard and the numeric keypad works differently on Linux. Yes they have windows compatible mode as well that you can set and your good to go. Once I had both these things going I have been pretty happy on the Mint desktop, pretty productive as well.
I think the time is really here, I’m getting a new daily computer that’s going to run Linux Mint. I will keep the current / old box around for windows for a while, just in case. However I will be running the windows stuff I might still need in a virtual machine on the Linux box. That should take care of any windows needs I might have. I can’t see many off hand, maybe some graphics and video editing. Open office will take care of the usual documents or google docs might do just fine. Although Mono develop is available I will most likely have to run Visual Studio, Mono is always a little bit behind .Net. The good news is that Eclipse works fine on any platform. Frankly there is not much that I have to run on Windows anymore and Linux is getting to be pretty nice and usable desktop. Linux has of course always been really strong as a server and that won’t change.