Tuesday, December 15, 2009

Building OpenCV 2.0 with Visual Studio C++ 2008 Express Edition

Hopefully I will spiff this post up with some screenshots, but for now, let me just quickly note the steps that were required to get this to build.

  1. Download and install VS C++ Express Edition
  2. Download and install CMake. When the install asks, don't bother having it put on your System Path.
  3. Download and install OpenCV 2.0. There is a Windows installer. Note: This does not install a working open cv library . . . it is just the source files. Again, don't bother having the installer put OpenCV on your system path.
  4. Run the CMake GUI in your CMake installation. For the source directory, indicate the OpenCV directory (probably C:\OpenCV2.0). For the build directory, specify a build directory that you've created (recommended: C:\OpenCV2.0\release).
  5. Click the Configure button.
  6. In the configuration options, disable OpenMP. You probably won't have this if you are using VS C++ Express Edition.
  7. Click the Configure button again. Then click Generate.
  8. Go to your build directory (C:\OpenCV2.0\release). Open the Visual Studio Solution file. Once you're in Visual Studio, build the project (f7). This will take a while.
  9. You're done. When you create new projects, use the Lib and Include files in your build directory. (You'll need to add these to your Project properties). I'll try to explain more later and maybe include a sample test project.

Saturday, September 5, 2009

Working with GWT / Spring / Dispatch

The Hive Development blog has a nice tutorial on setting up a Google Web Toolkit app with the Presenter and Dispatcher patterns. This is all based on a nice Google presentation explaining some useful patterns for developing robust app with GWT.

I recommend watching the video first and then reading the hivedevelopment blog article. Read through it and then download the full source code using the link near the top of the page. In the end, it's helpful example starter application for exploring concepts.

Anyways, the framework that you end up with uses Google Guice for server-side dependency injection and the servlet config. I am going to describe how I converted that to use Spring instead, using the GWT-Dispatch-Spring library. Comments are welcome since I am probably not doing things optimally in some places.

Why would you want to do this? I think it is personal preference whether you use Guice or Spring (nice discussion/war going on here). I am fairly new to both so I don't have a personal opinion. In the end of this, you will end up with a project using Guice's ally Gin on the client and Spring on the server, so you can be like Switzerland and remain neutral. ;)

The major steps described here include:

  • Adding the Spring and gwt-dispatch-spring-ext jars to your project
  • Eliminating Guice from your server code
  • Adding the Spring configuration to your server code
  • Switch the client to use the Spring version of the DispatchAsync

Initial Setup

As I mention above, I recommend going through the blog and then downloading the tutorial code. Import the code into Eclipse (File->Import->Existing Projects Into Workspace). Make sure it all builds and that you can run it in the debugger.

Add Jars

Download the Spring library jars.
Download the gwtrpc-spring library.
Download the GWT-Dispatch-Spring extension library.
Import these jars into the project's war/WEB-INF/lib directory (right-click on the directory, Import->File System):
  • spring-aop-2.0.8.jar
  • spring-beans-2.5.6.jar *
  • spring-context-2.5.6.jar *
  • spring-core-2.5.6.jar
  • spring-security-core-2.0.4.jar
  • spring-web-2.5.6.jar
  • gwtrpc-spring-1.01.jar *
  • gwt-dispatch-spring-ext-1.0.0 *
The jars that I've marked with an asterisk also need to be added to your build path (Right click Referenced Libraries in the package explorer, Build Path->Configure Build Path).

Eliminate Guice from Server Code

Just delete the entire greet.server.guice package.

Configure the Server Code Using Spring

Modify SendGreetingHandler

There are several things we need to do to adapt the SendGreetingHandler to use Spring:
  • All your Handlers will now inherit from SpringActionHandler instead of implementing the ActionHandler interface.
  • To inherit from SpringActionHandler, we need a new constructor since that class requires the ActionHandlerRegistry to be passed in.
  • We need to swap out the Guice annotations and replace them with their Spring counterparts. We use @Autowired instead of @Inject. We also label the class as a @Component.
  • I haven't yet hooked back up the Logging functionality. An exercise for the reader.
  • To get the servlet and http request context, we are using the gwt-spring-rpc library RemoteServiceUtil.
Here is what my class looks like after making these changes:

@Component
public class SendGreetingHandler extends SpringActionHandler<SendGreeting, SendGreetingResult> {
 
 @Autowired
 public SendGreetingHandler(ActionHandlerRegistry actionHandlerRegistry) {
  super(actionHandlerRegistry);
 }

 @Override
 public SendGreetingResult execute(final SendGreeting action,
       final ExecutionContext context) throws ActionException {
  final String name = action.getName();
   
  try {

      String serverInfo = RemoteServiceUtil.getThreadLocalContext().getServerInfo();
      String userAgent = RemoteServiceUtil.getThreadLocalRequest().getHeader("User-Agent");

      final String message = "Hello, " + name + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>" + userAgent;

   
   //final String message = "Hello " + action.getName(); 
   
   return new SendGreetingResult(name, message);
  }
  catch (Exception cause) {
   
   throw new ActionException(cause);
  }
 }

 @Override
 public void rollback(final SendGreeting action,
        final SendGreetingResult result,
        final ExecutionContext context) throws ActionException {
  // Nothing to do here
 }
 
 @Override
 public Class<SendGreeting> getActionType() {
  return SendGreeting.class;
 }
}

Create applicationContext.xml

This file will configure Spring to do annotation-based dependency injection. It also indicates to Spring that it should search the Spring/Dispatch package and our own server code package when looking for components to match dependencies. Place this in war/WEB-INF.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">


 <context:annotation-config />
 <context:component-scan base-package="com.adeoservices.gwt.dispatch.spring.server" />
 <context:component-scan base-package="co.uk.hivedevelopment.greet.server" />

</beans>

Change web.xml

We need to change our servlet to use a RemoteServiceDispatcher servlet. Change web.xml to this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>org.gwtrpcspring.RemoteServiceDispatcher</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.rpc</url-pattern>
 </servlet-mapping>


 <servlet>
  <servlet-name>remoteLoggerServiceImpl</servlet-name>
  <servlet-class>com.allen_sauer.gwt.log.server.RemoteLoggerServiceImpl</servlet-class>
 </servlet>


 <!-- Default page to serve -->
 <welcome-file-list>
  <welcome-file>GreetMvp.html</welcome-file>
 </welcome-file-list>
 
</web-app>

Quick Review: What We Just Did

At this point, we have converted the Server side code to use Spring instead of Guice. Try running the app. You will probably notice a bunch of logging statements in the Console regarding the Spring dependency injection scanning:

1253 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'sendGreetingHandler'
1254 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'springActionHandlerRegistry'
1255 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Autowiring by type from bean name 'sendGreetingHandler' via constructor to bean named 'springActionHandlerRegistry'

Try clicking the button to send the GreetAction to the server. You get an error because we haven't yet adjusted the client to work with Spring and to look for the new Spring RemoteServiceDispatcher that we defined in our new web.xml.

Update Client to Use Spring DispatchAsync

First, we need to add the Dispatch-Spring library to our client code. Add the highlighted line to GreetMvp.gwt.xml:

<inherits name='net.customware.gwt.dispatch.Dispatch' />
<inherits name="com.adeoservices.gwt.dispatch.spring.Dispatch-Spring"/>

Now, we just need to use the Spring-based DispatchAsync. Here is how I did it. I don't like it this way, so maybe somebody can help me (I'll explain). Go to the GreetingPresenter. Modify the constructor so that it takes a SpringDispatchServiceAsync instead of DispatchAsync:

public GreetingPresenter(final Display display, final EventBus eventBus, final SpringDispatchServiceAsyncImpl dispatcher, final GreetingResponsePresenter greetingResponsePresenter) {
What I don't like is how the GreetingPresenter now requires a specific implementation for DispatchAsync. What would be more appropriate is to configure Gin to inject the correct implementation in GreetingClientModule. At this point, I can't figure out how to get this to work: gin complains that DispatchAsync has been "double-bound". But I am basically brand new to Gin/Guice so I'm probably missing something.

In any case, the app should be working and the Client should receive a valid response from the server. You now have a working example using Spring on the server!

Sunday, August 30, 2009

Using Apache HttpClient 4 with Google App Engine

The ESXX blog has some handy code for integrating Apache HttpClient 4 with Google App Engine. Since it includes working source code, everything you need to figure it out is there. However, it can be a little confusing at first if you try dropping the code directly into an App Engine project. Your project will fail to compile as it uses several functions that are not supported by the App Engine SDK.

Instead of putting the problematic source code directly in your project, put them in a separate jar file. Then you can include that jar file in your project and everything should work fine.

I did this by creating a simple java project in eclipse, with just the two adapter code files. To get this to build, I also included the apache httpclient jars and the app engine sdk jar. I've included an image of my simple project structure here. Eclipse should automatically build the files once those jars are in place.

Then, at the command line, I simply went to that project's build directory and manually built the jar file using "jar cf GAEHttpClient.jar *". You can of course use your own jar file name. Make sure you build the jar at the root of your build directory structure.

Once your jar file is built, you should be able to add it to your main App Engine project (right click on the project in your Package Explorer and go to Build Path-> Configure Build Path-> Add external JARs . . . then add it to your war/WEB-INF/lib directory using File->Import->General->File System . . .) Once you have that (and the Apache httpclient jars) in place, you should be able to compile your code without error:

HttpParams httpParams = new BasicHttpParams();
ClientConnectionManager connectionManager = new GAEConnectionManager();
HttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);

Sunday, June 28, 2009

The WebFridge Project

A few months ago, in the spirit of our recessionary times, we decided to institute severe household financial austerity measures. Around the same time, I was interested in learning more about the latest java technologies that are being used in enterprise software and web applications. This resulted in . . .
Project WebFridge!

Our housing expenses are the biggest impact on our budget. But since our housing costs are relatively fixed, it seemed like the biggest opportunity for improvement was the food budget. But this has not been easy! I like food.

Here's our food expenditures over the past few months (credit goes to mint.com for the pretty graph):

A few notes:

  • In January, we took a vacation to New Orleans. Lots of good restaurants and bars there. So I view that spike as a special non-recurring charge.

  • Our general run rate appears to be in the $500-$800 range, and this reflects a major cutback in our restaurant/bar expenses. This still seems embarassingly high.

  • The green bars supposedly represent U.S. food spending according to Mint.com. Apparently people went on some kind of colossal diet in May.

  • Apparently the food stamp budget for two people averages around $6/day, or $180 per month. Whoa. We are nowhere close to that.

Anyways, what I decided to do was build a web application using the latest java technologies to keep an inventory of our foodstuffs.

We do throw out quite a bit of food that goes bad in our fridge or freezer because we basically forget that it's there. The goal of this application is to cut down on that waste. And also make it easier to plan our cooking menus and our shopping.

Here's a quick overview of how my application works. You can take a live look at our current inventory here!

Logging into the Website

The system requires a login but you don't have to do it every time if you select the Remember Me checkbox. There is an Administrator account that allows for managing user accounts. This all uses Spring Security, which is a great security/authentication toolset.

Reviewing Inventory

The inventory is displayed in a sortable list. You can also filter by item location (Fridge, Freezer, Pantry) or by Item Type (Pork, Canned Veggie, etc).

We often wonder, "what do we need to use in the freezer?". This can be answered easily by clicking the Freezer button and then sorting by the Days Until Expiration field.

Note the beautiful Fridge, Freezer, and Pantry icons that I drew. Need to make some prettier ones.

Adding Items using Barcodes and Auto-Lookup

When you add packaged items, the system lets you scan in the UPC barcode and the item's information will be entered automatically with the system's internal UPC product database. As soon as you scan in the barcode, the item description fields are automatically filled in.

This process really doesn't take too long. I don't enter everything. For example, individual pieces of fruit that sit in a fruit bowl on our counter, that's not worth tracking since we see it every day and know what's in there. Lots of the stuff we buy we immediately cook up for dinner so I don't bother entering that either.

I am using a $10 scanner from ebay, the infamous cuecat.

For other items that do not have official barcodes, I printed out on some removable barcode stickers using my laser printer. I put these on produce bags, tupperware containers, etc.

Of course those items are not in the built-in UPC product database, so I have to fill in the item info manually.

Note the Days Until Expiration field. That field is automatically filled as soon as you pick Item Type (ie- fruit is given 5 days, canned goods 700 days, etc), but you can of course override it.

Warning Tweets

When any item is 3 days from expiration, WebFridge automatically starts sending daily warning messages. This is really helpful in using up those things in the back of the fridge or freezer before they go bad.

I suppose I could have used regular email instead of going through twitter, but hey, it was fun figuring out how to call the Twitter API from my software.

Future Enhancements

  • Right now I don't bother filling in the item size and price. But it would be cool if I could have stats on item prices that I could check with my iphone when I'm at the store. I have a rough idea of prices for common things like a gallon of milk, but I am less sure of lots of things from apples to greek yogurt. I'd like to think of some way to make this price entry more automated (perhaps running OCR on the itemized grocery receipt) since this could be a PITA otherwise.
  • I want to make a special iphone web app interface. I already check this webpage in my iphone browser, but Apple has special html tags that allow you to make the page look like a native iphone app.
  • I'd like to be able to mark certain items as staples that would be automatically added to our shopping lists (right now we use Evernote for that) whenever they are removed from our inventory.

Tech Details

This application is a customization of the excellent AppFuse tutorial project. Appfuse is a great starting point for projects using java open source tools. I am using Hibernate to access a mySql database and Struts 2 for my web framework. It is wired together with Spring. This all running on a ubuntu linux server within Apache Tomcat. The code is automatically tested using jUnit and jMock and is built using maven.

I am not an html/css/graphic artist, so some of my customizations to the Appfuse web pages are not the prettiest ever.

Wednesday, June 17, 2009

Posting Code

I figured out a recipe for posting nicely formatted code online, like this:
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = "scripts/clipboard.swf";
...
SyntaxHighlighter.all();
I like the nice formatting and colors, including the ability to highlight lines. This also has a nice floating menu to allow the user to easily copy the code to their editor. If you are curious how to do this, read on! The key is a nice javascript library called Syntax Highlighter from Alex Gorbatchev. If you are comfortable with CSS styles and javascript, it should pretty easy to figure out how to use it and incorporate this library into your website or blog. Alex's website has good reference documentation, but it assumes you know how to hook javascript and css into your website.

If you are like me, and CSS and javascript is still a little unfamiliar, here is the recipe that I figured out. Note that this also works on Blogger, which is what I'm using right now . . . you'll just need to edit your template html.

Step 1: Add the javascript libraries to your webpage

Paste the following into your <head> section:
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shCore.js">  </script> 
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushBash.js">  </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCpp.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCSharp.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCss.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushDelphi.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushDiff.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushGroovy.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushJava.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushJScript.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPhp.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPlain.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPython.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushRuby.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPerl.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushScala.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushSql.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushVb.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushXml.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushAS3.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushJavaFX.js"> </script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPowerShell.js"> </script>
Note that each script (except for shCore.js) is for a different programming language. These provide the logic for language-specific highlighting. As you'll see, when you do your actual posting, you'll indicate which language your code is in. So, technically, you don't need all these scripts, just the ones for the languages that you'll be quoting on your page. But it doesn't hurt to just paste the whole block in for simplicity's sake.

Step 2: Link to the SyntaxHighlighter CSS styles

Immediately after the stuff you just pasted (and still within the <head > tag), add the following links:
<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/2.0.320/styles/shCore.css"/>
<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/2.0.320/styles/shThemeDefault.css" id="shTheme" />

Step 3: Configure

This step may be optional for you. Basically, we make javascript calls into the library to configure the behavior of SyntaxHighlighter. These options are documented here. For a start, just paste the following in after the previous stuff:
<script type="text/javascript">
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf';
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.gutter = true;

SyntaxHighlighter.all();
</script>
Note the highlighted line about the clipboardSwf. This gives the user a nice floating menu that allows them to easily copy your code to the clipboard. Also note the next line referencing bloggerMode. That needs to be set to true to have the formatting work correctly from within the Blogger.com framework.

Step 4: Post your Code!

Now, whenever you want to post some code, you can enclose it in a <pre> tag with a special
class
indicating which language highlighting you would like (java, c#, etc). The class is of the format: "brush: " . . . deduce the language string from the javascript filenames in Step 1 above. Like this:
<pre class="brush: java">
System.out.println("Hello World!");
</pre>
Have fun!