Running Java apps as Windows Services

A tricky little problem, as it turns out. There is little out in google world to help you, and only a few tools. License issues with almost all I found, especially running on Windows boxes in 64 bit mode.

 I finally found Yet Another Java Service Wrapper at yajsw. License is LGPL and it supports 64 bit windows. I was able to get my application running very quickly. Worked perfectly the first time. Getting going was interesting:

 1) You download yajsw and extract the zip file.
 2) You run your app and lookup its PID.
3) You run the yajsw script generator, and it analyzes your running application to create a script file.
4) You then run the yajsw bat files to install-service, uninstall-service, start-service, stop-service, etc.

The only trick is to run the bat files with administrator permissions. (Right-click on the bat file and select “Run as administrator”.)

Right now the yajsw folder needs to exist on the server as well. Doubtless there are more convenient ways to package the install, but this was a good first step.

Sebago Resort – 2011 – morning by the basketball

Morning panorama with two levels of exposure for HDR. Wind was low so only minimal ghosting in the leaves. It was a beautiful day, and this is one of my better panoramas.
<iframe width="100%" height="600" allowfullscreen style="border-style:none;" src="http://clevercaboose.com/pannellum/src/standalone/pannellum.htm?config=http://clevercaboose.com/pano2/20110530-9/config.json"></iframe>

Moving panorama hosting to 360cities

It has always been annoying that the Microsoft HDView tool relies on silverlight and forces users to install a plugin. Not to mention that I started embedding the panoramas in my page and that led to problems … crashes and lack of 360 deg awareness. So I took another look around at free hosting tools, and gigapan and 360cities emerged as two good options. Gigapan is picky in that they reject panoramas that are too small. They REALLY mean giga. 360cities has some restrictions, but not as severe.

For now, I am moving to 360cities. While my panoramas are not good enough for them to include publicly, they will host them so I can show them here.

My 360cites profile can be found at http://www.360cities.net/profile/richmacd

Sebago – Cabin 6 – Kitchen – 2011

This is the start of a series of pictures I took of the insides of the cabins at Sebago. I am doing high-resolution (zoomed lens) and HDR in a cramped space, so the limitations of the camera do show, and it is really hard to get it perfectly. So it isn’t perfect.

Kitchen Interior of Cabin 6, Sebago Resort in USABy the way, the HDView panorama is the best way to see the cabin, but if we look at one picture, we have to choose which distortion we least dislike. The above image is hemispherical, and is used for the HDView panorama. Below is the panini projection, which tries to keep straight lines as straight lines. Better in some ways; worse in others.

Java generics and the “Smalltak setter” pattern

Anyone coming from a Smalltalk background recognizes the idea of setters returning “this”. (Smalltalk does it automatically). It can be useful when chaining multiple setters together. (See this) And it is more readable than having a method with several parameters. Which would you prefer?

1) Methods don’t return anything:

myObject.setValue1(value1);
myObject.setValue2(value2);
myObject.setValue3(value3);


2) One method with lots of parameters:

myObject.setValues(value1, value2, value3);

3) Setters return this:

myObject.setValue1(value1).setValue2(value2).setValue3(value3);

(1) requires the most typing and the most screen space, so it slows down good programmers.
(2) is the worst option because you (a) wind up with several combinations of all the setters (setValues12, setValues13, etc), and if value1, value2, and value3 are of the same class, then you risk putting the parameters in an incorrect order.
(3) Nothing wrong with (3). It is clear and readable.

Now there could be a style debate: Should we use the Java pojo style, i.e.,

myObject.setValue1(value1).setValue2(value2).setValue3(value3);

or should we go with Smalltalk style, i.e.,

myObject.value1(value1).value2(value2).value3(value3);

I could argue both povs, so I won’t argue at all.

—-
Now when you have a class hierarchy, you immediately run into a problem with this style. Look at the following code (I have placed all classes inside one outside class, so i can keep it organized. Ignore that issue as it doesn’t matter.)

public class TestThis {
static abstract class MySuperclass{
public MySuperclass setter1(String str1){
//set setter1
return this;
}
}
static abstract class MySubclass1 extends MySuperclass{
public MySubclass1 setter2(String str2){
//set setter2
return this;
}
}
static class MySubclass2 extends MySubclass1{
}
public static void main(String[] args) {
MySubclass2 mySubclass2 = new MySubclass2().setter1(“str1”).setter1(“str2”);//COMPILE ERROR
}
}

The problem here is that the setter1 method returns the MySuperclass type even though the instance is actually of type MySubclass2. Blame this problem on Java’s crappy strong typing model. use Scala if it bothers you too much.

Or use generics. Yes, the Java generics model is lame (See Scala if offended), but we can do it as follows (see this FAQ for the background)

public class TestThisGenerics {
static abstract class MySuperclass>{
public THIS setter1(String str1){
return (THIS) this;
}
}
static abstract class MySubclass1> extends MySuperclass{
public THIS setter2(String str2){
return (THIS) this;
}
}
static class MySubclass2 extends MySubclass1{
}
public static void main(String[] args) {
MySubclass2 mySubclass2 = new MySubclass2().setter1(“str1”).setter1(“str2”);//WORKS
}
}

Its tricky. You have to get that > just right. I don’t know about you, but I can’t quite understand it perfectly; I just do it.

There is one annoying thing in the above class. Do you see how we have to cast “this” with “(THIS)” every time. And the compiler warns us that this is an “Unchecked cast”, which it is. We know it is safe, but the compiler doesn’t.

I have learned the hard way that compiler generics warnings can really bite you. You are not always smart enough to ignore it. It does usually pay to remove them. This brings up the silly but necessary “getThis()” pattern ( also see here ), so here is the final code without any compiler warnings:

public class TestThisGenerics {
static abstract class MySuperclass>{
protected abstract THIS getThis();
public THIS setter1(String str1){
//set setter1
return getThis();
}
}
static abstract class MySubclass1> extends MySuperclass{
public THIS setter2(String str2){
//set setter2
return getThis();
}
}
static class MySubclass2 extends MySubclass1{
@Override
protected MySubclass2 getThis(){
return this;
}
}
public static void main(String[] args) {
MySubclass2 mySubclass2 = new MySubclass2().setter1(“str1”).setter1(“str2”);//WORKS
}
}


Parboiled java patterns (Errors inside Optional)

I’ve been using Parboiled Java on a current project and think it is fantastic. Best thing since sliced bread and regexp. But as I was finishing up the edge conditions of the testing, I ran into some fundamental pattern issues which are not obvious and not in the examples. So here are some notes:

My problem domain syntax is essentially OData with some modifications. We’ve kept the basic ideas and added some necessary extensions. A user will create a URL representing a database search, send it to my system, I parse that URL and convert it to a search object, perform the search, then reply with the data from the search.

It was easy to create code for  the matching syntax. It was the error conditions and catching the errors that turned easy into hard and ugly. I don’t mind hard but I do mind ugly, so perhaps this post will lead to a better approach. Otoh, error handling and parsing tend to produce really ugly children, so a clean approach may not be possible either.

Here is an example of a URL snippet:

Person($expand=location($current))

Without getting into the meaning much, this is a database query that means Find all Persons and “expand” their “location” property which are “current”. In other words, find all people and return the people and their current locations.

Below is a parboiled parser class that does the trick:


import static org.parboiled.errors.ErrorUtils.printParseErrors;

import org.parboiled.BaseParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
import org.parboiled.annotations.BuildParseTree;
import org.parboiled.parserunners.ParseRunner;
import org.parboiled.parserunners.TracingParseRunner;
import org.parboiled.support.ParseTreeUtils;
import org.parboiled.support.ParsingResult;

@BuildParseTree
public class BlogTest extends BaseParser {
    public static void main(String[] args) {
        parse(“Person($expand=location($current))”);
    }
    private static BlogTest parser = Parboiled.createParser(BlogTest.class);
    public static boolean RESULT_TREE_ON = true;
    public static boolean STDOUT = true;
   
    public static void parse(String str) {
        ParseRunner runner = new TracingParseRunner(parser.Query());
        ParsingResult result = runner.run(str);
        if (result.hasErrors()) {
            String errorMessage = printParseErrors(result);
            if (STDOUT) {
                System.out.println(“\nParse Errors:\n” + errorMessage);
            }
        }
        if (RESULT_TREE_ON) {
            System.out.println(str + ” ===>  ” + ParseTreeUtils.printNodeTree(result));
        }
        if (STDOUT) {
            System.out.println(“Parse String = “+str);
            QueryAst query = (QueryAst) result.resultValue;
            query.print();
        }
       
    }
    Rule Query() {
        // This matches the Person($expand=location($current=true))
        return Sequence(
            Word(),
            matchedQueryName(),
            Optional(
                Sequence(
                    “(“,
                    Expand(),
                    “)”
                )
            )
        );
    }
    protected boolean matchedQueryName() {
        QueryAst query = new QueryAst();
        query.name = match();
        return push(query);
    }
    Rule Word() {
        return OneOrMore(
            LetterOrDigit()
        );
    }
    Rule LetterOrDigit() {
        return FirstOf(CharRange(‘a’, ‘z’), CharRange(‘A’, ‘Z’));
    }
    Rule Expand() {
        // This matches the $expand=location($current=true)
        return Sequence(
            “$expand=”,
            Word(),
            matchedExpand(),
            Optional(
                “(“,
                Optional(
                    Current()
                ),
                “)”
            ),
            popExpandAst()
        );
    }
    protected boolean matchedExpand(){
        ExpandAst expand = new ExpandAst();
        expand.name = match();
        return push(expand);
    }
    protected boolean popExpandAst(){
        ExpandAst expand = (ExpandAst) pop();
        QueryAst query = (QueryAst) peek();
        query.expand = expand;
        return true;
    }
    Rule Current() {
        // This matches the $current
        return Sequence(
            “$current”,
            currentSucceeded()
            );
    }
    protected boolean currentSucceeded() {
        ExpandAst prop = (ExpandAst) peek();
        prop.current = true;
        return true;
    }
   
    static class QueryAst {
        public String name;
        public ExpandAst expand;
        public void print() {
            System.out.println(“Query: name=”+name);
            if (expand == null){
                System.out.println(“expand == null”);
            } else {
                expand.print();
            }
        }
    }
    static class ExpandAst {
        public String name;
        public boolean current;
       
        public void print() {
            System.out.println(“Expand: name=”+name + ” current=”+current);
        }
    }
}
The problem is all the optionals. The parentheses are optional, and the text inside the parentheses are optional. In other words, the following URLs  are all legal:


Person($expand=location($current))
Person($expand=location())
Person($expand=location)
Person()
Person

But if there is text inside the parentheses, then it must be correct. In other words, the following URL is illegal:


Person($expand=location($currents))

When the java class shown above parses the above string, it will succeed because it matched on “$current” and didn’t care that the following letter was a “c”. We need to correct this.

One way to do this is to use the TestNot() rule. (If there are better ways, I’d love to know.) Change the Current() rule to the following:

    Rule Current() {
        // This matches the $current and does not match $currents

             return Sequence(
                 “$current”,
                 TestNot(LetterOrDigit()),
                 currentSucceeded()
        );
    }


So now we will no longer match on $currents. Problem is, the parser still succeeds because the Current() rule is enclosed by an Optional(). The error inside the Current() rule matching will be ignored.

We want the parsing to fail with a useful error message where the error occurred. How do we do this?

I’ve come up with two approaches, neither of which I am that crazy about:

Option 1 is to throw an Exception when the illegal text is discovered. Something like:


    Rule Current() {
        // This matches the $current and does not match $currents
             return Sequence(
                 “$current”,
                 Optional(
                    LetterOrDigit(),
                    throwError(“Illegal character found after $current”+match())
                 ),
                 currentSucceeded()
        );
    }

    protected boolean throwError(String msg){
        throw new ActionException(msg);
    }






Option 2 is drastic: We define our parsing rules to accept “almost anything”, use the match() method to build up intermediate objects (i.e., abstract syntax trees or ASTs), then analyze these objects for correct data.

An argument for option 2 is that the parsing phase should be separate from the validation phase. And one can build up a generic and reusable AST system. I spent a day working this out, but ultimately abandoned it as the parsing rules had become so “unrelated” from the “correct syntax” of my problem domain. I didn’t like the code-smell.

I’m still working through this, but right now Option 1 is forging ahead.

Robyn’s room 2012

Daughter spent the day cleaning and re-arranging her room. The miracle of mess-removal, and once again being able to see the hard wood floors that her Mother and I discovered under crappy carpet and restored. We thought of taking a picture, then I remembered that photosynth is available for her new itouch, so we played with that. Good, but not good enough for Dad, so I spent 2 hrs taking the pictures, and maybe 10 hrs building the panorama with hugin, then the computer did a few hours of cranking as well. This one came out quite nicely. Problems mostly due to the average camera lens.

Rob Gillaspie – Corporate Slave

Back in 1993, I was working an hellacious job at the refinery in El Dorado. (Hell Dorado, as I called it.) Monday through Friday in the plant, home for weekends. Lousy project. One bar in town and these were the days when you needed a “membership” to enter. I wound up eating most of my meals in my motel room.

Anyway, I was back in Lawrence for Art in the Park, and I ran into a very talented kid (high school senior) who was displaying his work. His name was Rob Gillaspie. One image in particular caught my eye: Corporate Slave. Surprise :-)

I told him I wanted to buy it and how much would he sell it for. Nice kid, he was stunned, and eventually came up with “five dollars”. I talked him up to ten dollars with a lecture about how it was going to cost me twice that to have it framed. Anyway, we parted company and I never saw nor heard from him again. Periodically I google and FB his name, but nothing yet. So now at least his name and his art work are in google and perhaps he can find me.

 
Rob Gillaspie
Corporate Slave
1993
Update: My google trick was successful and he finally showed up. You can find him at  Mal Content google user

Robin MacDonald newspaper clippings

I’d scanned some of my Dad’s old newspaper clippings, so it was time to commit them for posterity.. Cricket from the sixties…

This is an article from the 1960s. Currie Cup cricket is the South African equivalent of each US state competing against each other. SA had 5 provinces (or “states”).

Golf next. My Dad never got a hole in one but he got an albatross at Royal Durban Golf Club.

RDGC is a unique golf course. Totally flat and wind-swept. Two-shot penalty if you got into the rough. Surrounded by a horse race track. They have actually reversed the front and back nine since our time. Dad was club President a couple of years in the 70s.Fond memories of New Years dinners with party hats and Dad making the speech.

My Dad made the Natal amateur semifinals a couple of times. Natal was one of the South African provinces.

Paradise Cafe enchilada recipe

Paradise Cafe in Lawrence, KS was my favorite restaurant back in the college days. Sadly no longer with us, but I made some great friends there.

(You can find their facebook page at facebook paradise cafe group )

For some reason or another, I got hold of the enchilada recipe, so here it is:

Filling

1 pound spinach, chopped

2 tablespoons olive oil
2/3 cup finely diced onions
2/3 cups sliced mushrooms
1 teaspoon garlic
1/2 teaspoon dried oregano
salt and pepper
dash Tabasco

Cheese sauce
3 tablespoons margarine
3 tablespoons flour
2 cups milk
16 ounces sour cream
1 4-ounce can chopped green chilies
1 2-ounce jar diced pimientos, rinsed
 /2 teaspoon salt
 1/2 teaspoon Tabasco or to taste
 1 cup or 4 ounces grated Swiss cheese
 12 6-inch blue corn tortillas
 1 1/4 cups or 5 ounces grated Swiss cheese
 chopped tomatoes and black olives
 salsa

Preheat oven to 375 degrees.

Make filling: Sauté onions in oil until translucent. Add mushrooms, garlic and oregano. Continue to cook until mushrooms are soft. Add spinach and sauté until wilted. Add salt, pepper and Tabasco to taste.

Make cheese sauce: Melt margarine in saucepan. Whisk in flour and cook over medium-low heat for 2 to 3 minutes. Whisk in milk a little at a time and cook over medium heat, stirring frequently until smooth and thickened. Do not add other ingredients until sauce is thickened. Add sour cream, chilies, pimientos, salt and Tabasco. Heat through but do not boil or the sauce will break apart. Add Swiss cheese a little at a time, stirring constantly. Remove from heat as soon as the cheese has completely melted.

Heat heavy skillet or griddle until hot. Quickly heat corn tortillas on skillet. Spoon some of the spinach filling down the center of each tortilla. Add some Swiss cheese and 1 to 2 tablespoons cheese sauce.
Roll tortilla around filling and place, flap side down, in a shallow casserole. Cover and warm in 375-degree oven until enchiladas are heated through and cheese is melted. Just before serving, pour cheese sauce over tortillas. Garnish with chopped tomatoes and black olives.

Serve with salsa. Makes 12 enchiladas.

Bucket List Books

It occurs to me that everyone should maintain a list of “bucket-list” books. Books that are so important that we believe everyone should read. Or maybe this is the wrong term. Maybe this is just a list of books which we found essential to whoever we are today. I’ll get started here.

Zen and the art of motorcycle maintenance / Lila, by Robert Pirsig

Two books actually. Good college age reading, perhaps for advanced high school. This is an engineer’s bible. Foundations of logic and “truth”


Gödel, Escher, Bach: An Eternal Golden Braid, by Douglas Hofstadter 

College age. Very tough mathematics. Mind-blowing. The art of bootstrapped complexity.


A new kind of Science, by Stephen Wolfram

If it turns out to be true, the most important mathematical work since Godel’s incompleteness theorem.

Narcissus and Goldmund, by Herman Hesse 
One of the great writers of all time. The intellectual life vs. the experiential one. If one every plans to spend time debating capitalism vs. socialism, Democrat vs. Republican, etc, etc. one should also read Magister Ludi, in order to remove forever the fantasy that there could exist a perfect system.

Shogun, by James Clavell
Because aliens really do exist on this planet, and by the end of the book you will partially understand how they think. You’ll also never complain about the dropping of the atom bomb to end WWII.

And many more …