Sunday, November 03, 2013

GTA; The Lost and the Damned Final Thoughts

Even though it was a product of +Rockstar Games  I thought I would never play and never like GTA: The Lost and Damned because I found the characters repulsive, depraved, degenerate and unlikable, and the protagonist - Johnny Klebitz - was voiced by an overcompensating wannabe tough guy with a very forced "gravel voice".

After playing and completing it though, I have to say I really like it. My initial critiques still stand, but the overall story, pacing and gameplay is perfect for busy people who enjoy the engaging narrative of a full Grand Theft Auto game without the investment of time needed to unlock all the cool toys and see the entire city.

Now I was never a fan of the whole death metal, leather jacket, biker scene so it was a bit difficult for me to get into the story and start caring about the characters even with such an exciting and edgy trailer...



 But once I did my regrets were zero.

I'd describe this as a perfect day-off experience. Long and involved enough to keep you occupied all day but short enough to allow you to get to the conclusion of the story before the sun sets.

Wednesday, October 30, 2013

Running Play 2.1.x App as Windows Service (Fat Free Version)


In this post, I'll show you how to run your Play 2.1.x app silently as a background service and give you a couple tools you can use to ease the administration process for your app. All of this without the use of third party tools.










For this tutorial we will use the Zentasks sample application that came bundled with the framework. This tutorial assumes that:

  • The zentasks project folder is located in C:\apps\zentasks
  • The Java executable is located at C:\Program Files\Java\jdk1.7.0_25\bin\

Adjust these directories to suit your needs. Let's get started.

The Problem


You have several apps that you need to deploy in a production Windows environment, but you hate having the pesky command prompt window visible in the background when you run play start for each application. You want your apps to run silently as Windows services on startup.

The Solution


Create a standalone distribution of your app by opening a command window and running

cd c:\apps\zentasks
play clean dist

In the dist folder of the application directory, you should see an archive named zentasks-1.0-SNAPSHOT.zip Extract the contents of that archive to the current folder.

In my case the location of my app is C:\apps\zentasks and the location of the folder I just extracted from the archive is C:\apps\zentasks\dis\zentasks-1.0-SNAPSHOT.

To run my app invisibly, I take advantage of the javaw.exe application bundled with my Java installation. This file does exactly what java.exe does but it does it in the background without showing a console window.

Note before continuing: Either turn off evolutions or set them to automatic in the application.conf file. You can do that by following the example here. Once that's done, run play dist again.

In a command prompt window I then run the following commands:
cd c:\apps\zentasks\dist\zentasks-1.0-SNAPSHOT
javaw -cp lib\* play.core.server.NettyServer

You'll notice that the command runs and returns you to the command prompt. Give it a couple seconds and go to http://locahost:9000 (or whatever port you set the app to run on) and see if your app is running. It should be.



Once you have that sorted out, let's move on. We're going to create two batch files for starting and stopping the application. Once these files are created we can also place them in the Startup folder on our Start menu to have them execute when Windows starts up.

Batch File #1: Start.bat


Open a Notepad document and paste in the following:
cd .
start "" "C:\Program Files\Java\jdk1.7.0_25\bin\javaw.exe" -cp lib\* play.core.server.NettyServer

Substitute the correct paths where necessary and save the file as start.bat in your application's dist\zentasks-1.0-SNAPSHOT directory.

To test the file, open task manager and kill the javaw.exe process,



then go to your application's dist\zentasks-1.0-SNAPSHOT directory and delete the RUNNING_PID file. Now double-click start.bat, wait a couple seconds then go to http://localhost:9000 to check if your app is up. It should be.

Batch File #2: Stop.bat

If starting your app in production mode is now that easy, then stopping it should be too.

Again, open a new Notepad document and paste in the following:
set /p pid=<RUNNING_PID
taskkill /PID %pid% /F
DEL RUNNING_PID

That information goes on three separate lines. Save the file as stop.bat, place it in your app's dist\zentasks-1.0-SNAPSHOT directory and when you run it, it should kill the javaw process that your app is running on and delete the RUNNING_PID file as well. To ensure that your app has been shut down, go to http://localhost:9000 and observe that your app is down. At the end of it all your directory structure is supposed to look as follows:

* zentasks  
 *-- dist      
 *-- zentasks-1.0-SNAPSHOT          
 *-- lib          
 *-- RUNNING_PID          
 *-- start.bat          
 *-- stop.bat 

You can now take this folder and plop it down on your production server worry-free. Yay!

Q&A 

But what about my configuration options? What if I want to change the port that the application is running on?
 Simple. In start.bat include -Dhttp.port=xxxx or any other configuration options before the -cp argument. E.g:

start "" "C:\Program Files\Java\jdk1.7.0_25\bin\javaw.exe" -Dhttp.port=9001 -Dconfig.resource=prod.conf -cp ...

Is starting the application this way safe?
As far as I can tell, yes. The long and short of the story is that the command you place in the start.bat file is what is essentially run when you execute play start plus or minus a few directory and Java option changes. +James Ward and the +Play Framework team are free to correct me on this if I'm wrong.

Where will the logs and other necessary files be created? A directory for logs will be created in the dist\zentasks-1.0-SNAPSHOT folder and an application.log file will be placed there. File system h2 databases will be placed in the dist\zentasks-1.0-SNAPSHOT folder.

Where does the application read configuration items from in this mode?
In the lib directory of dist\zentasks-1.0-SNAPSHOT  there is a file named zentasks_2.10-1.0-SNAPSHOT.jar If you were to extract the contents of this file, you'd see all the evolutions and *.conf files your created up to the point in time you ran the play dist command.

I hope this was helpful to you. Thanks to +James Ward and the amazing +Play Framework team for all their hard work, and as always thank you for reading.

Wednesday, October 16, 2013

Scheduling Jobs In Play 2

In this tutorial, I'll show you how to schedule asynchronous jobs in the Play! Framework version 2.1.3.

The Play! Framework has moved away from using Job classes with Crontab-like annotations for application level task scheduling. In place of the old model we find heavy use of the Akka system, which operates a bit differently and can take some getting used to if you're accustomed to the CRON/Quartz way of doing things.

Let's get started!

After creating our application, we need to create a Global.java file in the app/ directory. Place the following in the file:

import play.Application;
import play.GlobalSettings;
import play.libs.Akka;
import scala.concurrent.duration.FiniteDuration;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Global extends GlobalSettings {
    @Override
    public void onStart(Application app) {
      //Magic goes here
   }
       
}

The above is nothing too complex. It's a file that contains code that will be executed upon starting the application. The important piece is the onStart method that has the @Override annotation. That's where we're going to place our scheduling code.

Before continuing, you should probably take a look at what the Play devs have to say about the use of their Akka scheduler before I give my personal explanation.

Place the following in the onStart method of the Global.java file we just created.

FiniteDuration delay = FiniteDuration.create(0, TimeUnit.SECONDS);
FiniteDuration frequency = FiniteDuration.create(5, TimeUnit.SECONDS);

Runnable showTime = new Runnable() {
   @Override
   public void run() {
      System.out.println("Time is now: " + new Date());
   }
};

Akka.system().scheduler().schedule(delay, frequency, showTime, Akka.system().dispatcher());

The above simply allows us to log the current time to the console ever 5 seconds. Not very useful, but it's a start. Run the application and see for yourself.

schedule() Arguments Explained

Before we continue we should probably get a firm grip of the schedule(...) method signature.

delay - How long after the application starts should I wait before running my code?
frequency - After I've run my code the first time, how often should I repeat it?
showTime - A runnable containing the code that is to be run after the delay and at the defined frequency.
Akka.system.dispatcher() - Not entirely sure what this is, but it's needed as the last argument.

Neither of the first two arguments can be changed from within the Runnable body. The delay (and frequency) must be calculated on application start correctly and in such a way that the timing of the job is not affected by application restarts.

Defining a Proper Schedule

Now that we've covered the basics, let's move on to creating a useful schedule. The schedule that we'll create will run a task at 4PM every day.

The first step is to determine the delay i.e. how long the scheduler should wait to execute our task once the application has started. The challenge here is that the calculation of the delay must accommodate random application restarts. Say, for example, we start our application at 8AM, the job should wait roughly 6 hours before it starts, but if at 3PM the need arises for us to restart the application, the delay should be recalculated to 1 hour. We will calculate this delay in seconds for better precision.

I'll be using the Calendar class, but feel free to use JodaTime if you're more comfortable. So let's augment our previous code snippet to calculate this delay:
Long delayInSeconds;

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 16);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date plannedStart = c.getTime();
Date now = new Date();
Date nextRun;
if(now.after(plannedStart)) {
   c.add(Calendar.DAY_OF_WEEK, 1);
   nextRun = c.getTime();
} else {
   nextRun = c.getTime();
  }
 delayinSeconds = (nextRun.getTime() - now.getTime()) / 1000; //To convert milliseconds to seconds.

Code explanation:
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 16);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date plannedStart = c.getTime();

Use a Calendar object and set it's time to 4PM of the current day, then create a date object to store the current date and the intended start time based on the modified Calendar object.
Date now = new Date();
Date nextRun;
if(now.after(plannedStart)) {
   c.add(Calendar.DAY_OF_WEEK, 1);
   nextRun = c.getTime();
} else {
   nextRun = c.getTime();
  }

Find out the current date and time (now) and create a new Date object (nextRun) that will store the date and time of the next code execute.If the time now is after the time we planned to start the job, then we'll set the time that the job should execute to be tomorrow at 4PM. If not then we're on schedule and the nextRun will be today at 4PM.
delayInSeconds = (nextRun.getTime() - now.getTime()) / 1000; //To convert milliseconds to seconds.


Next we do some simple subtraction to find out how many seconds between now and the next time the code should run. This is our delay... In seconds, of course.

From here on it's gravy. Simply substitute the delayInSeconds value for the integer value in the FiniteDuration delay variable and change the frequency to 1 day as follows:


FiniteDuration delay = FiniteDuration.create(delayInSeconds, TimeUnit.SECONDS);
FiniteDuration frequency = FiniteDuration.create(1, TimeUnit.DAYS);
Runnable showTime ...
Altogether Now!

Long delayInSeconds;

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 16);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date plannedStart = c.getTime();
Date now = new Date();
Date nextRun;
if(now.after(plannedStart)) {
   c.add(Calendar.DAY_OF_WEEK, 1);
   nextRun = c.getTime();
} else {
   nextRun = c.getTime();
  }
 delayInSeconds = (nextRun.getTime() - now.getTime()) / 1000; //To convert milliseconds to seconds.

FiniteDuration delay = FiniteDuration.create(delayInSeconds, TimeUnit.SECONDS);
FiniteDuration frequency = FiniteDuration.create(1, TimeUnit.DAYS);
Runnable showTime = new Runnable() {
            @Override
            public void run() {
                System.out.println("Time is now: " + new Date());
            }
        };

Akka.system().scheduler().schedule(delay, frequency, showTime, Akka.system().dispatcher());

Now every day at 4PM your application will remind you of the time. Awesome.

Thanks very much to +James Ward and this magnificent post for helping me wrap my head around this tricky concept. Thanks to the +Typesafe folks for all their hard work with the +Play Framework , and as always thank you for reading.








Wednesday, October 02, 2013

How to Install Play 2 War: The Bare Minimum

In this post, I'll show you how to install the Play 2 War extension. This article describes the installation and configuration procedure for Play 2.1.x applications.

From the author: 
This project is a module for Play framework 2 to package your apps into standard WAR packages. It can be used with Servlet 3.0 and 2.5 containers (Tomcat 6/7, Jetty 7/8/9, JBoss 5/6/7, ...)
Step 1: Add the Plugin to plugins.sbt

Navigate to \project and open the plugins.sbt file. Add the following line to the end of the file:

addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.0")

Note: Be sure to include an empty line between this line and the previous addSbtPlugin statement.

Step 2: Add Play2War keys to Build.scala

In the same folder as plugins.sbt, you'll find the file Build.scala. Open this file and follow the template below for modifying it. Items in bold are the new lines that were added. Items in italics are items that can be modified to suit your application's needs.

import sbt._
import Keys._
import play.Project._
import com.github.play2war.plugin._

object ApplicationBuild extends Build {

  val appName         = "your_app_name"
  val appVersion      = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    javaCore,
    javaJdbc,
    javaEbean
  )

  val main = play.Project(appName, appVersion, appDependencies)
  .settings(Play2WarPlugin.play2WarSettings: _*).settings(
    // Add your own project settings here  
Play2WarKeys.servletVersion := "3.0"
  ).settings(
Play2WarKeys.targetName := Some("war_file_name")
  )


}

Tip: The full list of Play2WarKeys and their expected data types can be found here.

Step 3: Resolve Dependencies and Build the WAR

Open a command terminal and cd into your project's directory. Once there, run the following commands:

play
clean
dependencies
war

Once the war command has completed you can look in \target to see the generated WAR file. You can then take this file and deploy it to your servlet container of choice.

Why Would I Want to Use This Plugin?

That's a great question especially seeing that Play comes with its own high performance web server built in. My answer to that question is if you work in a Windows-centric environment like mine, you become acquainted with the "shortcomings" of the Play framework when it comes to production deployment in a Windows environment. Unlike Linux where you can easily set your application to run as a service in the background on startup, Windows forces you to resort to all sorts of .bat magic that leaves you with a bunch of command line windows popping up and having to stay open for the duration of the application's life.

So for a cleaner, less cluttered production server that other members of your team can appreciate, I recommend using a Servlet container like Tomcat that can be installed as Windows service and set to run on startup. No more .bat magic and no more freaking out when the server admin says he restarted the server a couple hours ago and now the folks in HR can't access the employee registration application.

Closing Remarks

In all, the installation of this extension was easy once you figured out how to switch mental context to deal with the different syntaxes for each file that has to be manipulated. I find that in some cases the author of the documentation could have gone into a little more detail in addressing the little gotchas with each file type. For example the need for an empty space between lines in the plugins.sbt file. Thankfully the Play command was smart enough to point this out to me when I tried to start the application and it was an easy fix.

That being said, though the installation of this particular plugin was not all that difficult, I would still like to see some more abstraction in the plugin installation process. I think the guys over at +Typesafe could take a very interesting page out of the Rails book in this regard.

That's it for now. I hope this article was useful.


Wednesday, September 25, 2013

Styling Apps In Android - Not for the Faint of Heart

If it's one thing I would like to see in future Android APIs is more support for the artistic side of app creation.

Coming from a Web/CSS background, I was expecting things like drop shadows, gradients, rounded corners, selective border colours etc. to be relatively easy to implement. As it turns out, it's not. For example, getting rounded corners on an ImageView involves a fair amount of coding (as illustrated here: http://stackoverflow.com/questions/16208365/create-circular-image-view-in-android). It's especially hurtful when doing the same in iOS is so headslappingly simple http://stackoverflow.com/questions/7705879/ios-create-a-uiimage-or-uiimageview-with-rounded-corners I just wish making my apps look cool was a much easier process.


Anyway, if anybody feels the same way, knows of easier ways to achieve aesthetic gold or if the styling and graphics APIs are supposed to get a reboot anytime soon, sound off in the comments below. 

Sunday, August 25, 2013

Play Framework 2.x - Taking the Plunge


So after many months of kicking and screaming against being forced into the new 2.x.x branch of the Play! Framework I finally decided to take a weekend and learn the damn thing and get it over with.





Pros

Much more powerful and feature packed than the 1.x branch
In addition to some serious code optimizations and refactorings, things like an interactive console, built in H2 in-memory database browser and a built-in LESS and CoffeeScript compiler are just a few of the bells and whistles added on that really add to the development experience.

The Scala templating language is not as scary as it sounds
...And that's coming from a Java developer. Yes, I really enjoyed using this templating system even though some things took a couple minutes to really sink in. Parameter groups? What's that?

The new ebean ORM 
Though I've only used it to complete the Zen Tasks tutorial, i'm seeing that it requires a lot less hand-holding in the JPA annotation department. Give it a @ManyToOne annotation in one class and you don't need to go to the related class and set up the mappings. It's something I haven't seen done anywhere else (except Rails, I think) and it's nice to see it available here in sweet ol' Java. 


Cons

Not as friendly, free form an "playful" as the 1.x branch. 
Doing the simplest of things requires a lot more typing, planning and thought now. Gone are the days when I could have just done this:

public static void updateUser(User user) {
 user.save();
 render();
}

Now I have to do:

public static void updateUser() {
 Form userForm = form(User.class).bindFromRequest();
 User u = userForm.get();
 u.save();
 ok(views.html.users.updateUser.html);
}

This approach provides certain advantages, but it really takes away from the appeal and fun I had with the 1.x approach.

Documentation is a bit lacking
I wish the documentation could have been organized better and be more detailed a la 1.x. Certain sections like Forms and Action Composition could use a little attention.

Searching for help turns into a hunt
Searching for help online usually returns 1.x or 2.x Scala results. This is not helpful to a 2.x Java developer.

Other Thoughts

I've been a big fan of the +Play Framework since I walked away from Rails over a year ago. I haven't looked back since. Part of what made me fall so madly in love with it was it's power without being verbose; elegant simplicity without the need for me to get embroiled in XML files and the like. I could have hardly believed it was Java I was using!

As of late though, it's become a bit heavier and less of a tool that I could use to knock out a prototype in no time flat. Don't get me wrong, it's still miles better than Spring or Struts (shudder), but it's just not as free form and delightful as it was when it was younger. I do understand, though, that some of its "agility" was sacrificed to introduce better optimized code and more powerful technologies, so I guess I'll just file this under the price of progress.


For those of you wondering why I took a weekend, this included getting comfortable with +IntelliJ IDEA and wrangling with the many technical issues that came up with the Scala and Play2 plugins. IntelliJ is a marvelous IDE and has proved me wrong in believing that Eclipse was the be all and end all of Java IDEs, but I think the Play 2 plugin could use some work. It won't, for example, let me reference a template via index.render(...), so I have to do views.html.index.render(...) or import views.html.index before I can call the render method. It's a minor issue, but majorly annoying when I'm trying to dance my way across the keyboard to project completion.

Conclusion

In closing I'd like to say that Play 2 is not the horrid, complex mess I thought it was. Sure it's a bit different and sure i'll have to wave goodbye to some of my old habits, but the framework has been made better and future proofed for tomorrows web application developers. I really appreciate all the hard work that +James Ward and the team at Typesafe have been doing. 

Here's hoping that Play 3.0 will be backwards compatible!




Sunday, May 26, 2013

Why I Am Choosing the Playstation 4

It's almost that time again, folks - the time where we choose our allegiances for the next generation of the console wars, while berating and ridiculing anyone else who chooses a system different to the one we chose.

Now before I begin, I must declare that this post is not titled why you should choose the Playstation 4, but why I am making it my companion for my next romp in the Elysian fields of console gaming.

Why the Playstation 4?

One word: Exclusives. I am most interested in the properties that are tied to the Sony brand than any other platform. Why buy an Xbox or an absurdly powerful PC when I will only end up quaking nervously to find out if Hideo Kojima will ever release his next game for anything other than Sony Playstation. It simply doesn't make sense.



When that next MGS/Uncharted/The Last of Us drops, I want it IMMEDIATELY.

What's Wrong with the Xbox?

Nothing at all. As a matter of fact, I have never owned an Xbox to find out what are some things I may not like about it. As for whether or not I will even consider picking up an Xbox later down the line, it's a possibility should there be a piece of IP that is just that good that I absolutely have to have it.

Currently though, Halo just isn't my thing and the new Xbox One's slew of living room features just don't make a compelling enough case for me to pick this thing up on day one.

You Fool! PC is Where It's At!

And you maybe right, more so in this console generation than ever. For those of you who aren't acquainted with each system's technical specifications, these new systems are basically just PCs with a smaller form factor and features that make them more suitable for your living room than for editing PowerPoint presentations.

Be that as it may, I have a very awful taste in my mouth regarding PC ports of last generation's games. I found that far too often I had to become this great PC hackboy to get some of my favourite games to work well. When it wasn't replacing particle files to fix visual glitches, it was simply a case of poor PC optimization on behalf of the developers. I'm looking at you GTA 4.

Worse yet, all of my PS2 faves like Vice City and San Andreas just didn't carry over well once I started getting more modern hardware for my PC. I actually had to install a video card "hack tool" to get them to play properly on my Radon 6670. Not to mention the laughable support for more recent joypads.

These are issues that console gamers simply don't have to worry about, but were my nightmare almost every time I installed a game that was ported from the consoles to PC.

Sure you can throw the argument about better graphics and modding ability at me, but the truth is I never really cared for mods and I remember enjoying Vice City immensely on the PS2 in all it's buggy and glitchy glory. I'm prepared to sacrifice a bit of visual fidelity for the sake of a hassle-free gaming experience.

Now it may be safe to conclude that the source of all of the last generation's PC ports were so terrible due to the Playstation 3's Cell processor and that this generation's ports may be much better due to the fact that both consoles are using more standardized PC-like hardware, but that remains to be seen.

I may still end up build a gaming PC to catch the odd game or two that are "tremendously better on PC" but i'll be taking my time with that project.

In conclusion/TLDR:
  • I'm choosing the PS4 because I like the exclusives.
  • I'm not choosing the Xbox One because I don't really care for that platform's exclusives.
  • I'm not choosing PC (from the get-go) because of the terrible console ports of last generation.
  • You are free to decide which one you want to go with.




Thursday, January 17, 2013

Today I Fed A Man

Walking in to my new neighbourhood convenience store, I caught a whisper of a beggar asking me for some change. I mostly ignored him and continued on.

While inside the store his voice ricocheted around the inside of my head like a vindictive stray bullet. I wrestled with logic and my humanity as I weighed the pros and cons of giving this beggar some money - if I give him cash he'll probably spend it on drugs, so maybe I should default and give him some food instead.

By the time I came to this conclusion I was already out the store, groceries in hand.

I saw him looking at me expectantly, all the while counting up some singles and fives; his day's take I guess.

To put an end to this absurdly long thought process I just reached into my pocket and handed him two of the singles that happened to be in there. He accepted it graciously.

A few minutes later, my short term memory kicked back in and reminded me that I needed some matches. There was a small parlour across the street,so there I headed to make my last purchase.

As I'm standing by the counter counting my pennies, up comes the beggar behind me and with the fives and singles he was counting, purchased a small loaf of bread, a snack and a drink. He then looked at me, the delight in his eyes shining through his bushy eyebrows, and said "thank you brother!"

At that point I swore I could feel the Holy Spirit smiling at me and nodding in approval. Best feeling I had all day knowing that I fed my saviour.