Can anything I write here help open source?

November 23rd, 2009

I spend a lot of my time working with open source software and I like to think that I’ve picked up a number of the tricks, gotchas, and other secrets of these systems.  So, whenever I think of posting to this blog, it usually along the lines of “man, I just spent a day figuring out X. I should document that for the next poor sap that comes along.” Invariably, I don’t. Occasionally this is due to time constraints, but more often it’s because there’s already a wiki or something for whatever I’m dealing with and I believe that keeping related information in one place is a good idea. So, I don’t write it here, or there.

Unfortunately, writing open source documentation isn’t as fun as coding or as gratifying as blog traffic* so there’s a pretty good chance the open source knowledge diaspora will continue. Important, headache preventing, technical information will remain in change logs, mailing lists, and random blog posts while user guides and other documentation will be ignored or buried**.

Stack Overflow is helping a bit, but it would be nice if some of the best answers there were pulled back into (or at least linked to from) the how-tos and getting started guides of the projects they concern.

I, for my part, am going to start writing this stuff down. Where it belongs.

* yes, I recognize the irony here.
** many open source projects could do a hell of a lot better job at making documentation easier to find.

open source

Using rails.vim with JRuby

July 23rd, 2009

I spent this evening fiddling around with rails.vim and JRuby.  I have some Java code that I’d like to use with Rails, so I’m using JRuby (also, JRuby seems to hate Windows slightly less than MRI).  Anyway, this is really about using vim to edit Rails code. I installed rails.vim and found that it was hard-coded to use plain old Ruby. Assuming that jruby.bat (or jruby, I guess) is on your system path, all you need to do is modify the app_ruby_shell_command in autoload/rails.vim like this:

function! s:app_ruby_shell_command(cmd) dict abort
  if self.path() =~ '://'
    return "jruby.bat ".a:cmd
  else
    return "jruby.bat -C ".s:rquote(self.path())." -S ".a:cmd
  endif
endfunction

Basically, just change “ruby” to “jruby.bat” and add the -S parameter.

The -S flag is important. Otherwise, it seems JRuby’s implementation of the -C flag is a little buggy. For example, almost any script/ command will fail:

>jruby -C c:\path\to\rails\app script/generate
C:/Program Files/jruby-1.3.1/bin/../lib/ruby/1.8/pathname.rb:711:in `relative_path_from':
        different prefix: "C:/" and "C:\\path/to/rails/app" (ArgumentError)
        from C:/Program Files/jruby-1.3.1/lib/ruby/gems/1.8/gems/rails-2.3.3/lib/rails_generator/lookup.rb:110:in
        `use_component_sources!'

Everything seems to be working well now. Yay.

app_ruby_shell_command

jruby

99 Prolog Problems in Ruby

April 12th, 2009

I spent the weekend on the shores of Lake Huron. During the kids’ naps, I worked through the first 28 problems of P-99: Ninety-Nine Prolog Problems in Ruby. Many have done it before me (in many languages and variations). Many will do it after.

So far P27 gave me the most trouble because I refused to use my brain. Figured it out on a nice long walk with the family. P28 was a pain because I was figuring out how Ruby blocks/procs work. Here’s the code.

p.s. an immutable list, like in Scala (or Lisp, etc, etc), with pattern matching of course, would be handy in Ruby. I wonder if one exists…

ruby ,

Ten Little Soul Crushing Features of Java

April 8th, 2009

There are a lot of big things (lack of closures, type inference, etc, etc) to dislike about Java. This is a list, in no particular order of little things that make day to day Java development just that much more irritating. Most of these are just convenience methods whose omission is unforgivable. Libraries exist to address all of them, but that’s beside the point.

1) No string join method

How many times have I written this?

2) No way to set additional JVM parameters in manifest of executable jar

It’s really convenient to just double-click a jar … until you need to set your heap size or something and you have to go crawling back to a shell script.

3) java.net.URL constructor throws checked MalformedURLException rather than unchecked IllegalArgumentException

Seriously, what is so special about this exception?

4) java.io.File has no getExtension() method

Same as join() above.

5) No immutable collections.  Collections.unmodifiableList() and friends don’t count

6) java.io.File.delete() silently does nothing if you try to delete a non-empty directory

It’s even more irritating to write deleteFolder() than join() and getExtension().

7) java.util.Random has a setSeed() method, but no getSeed() method

8) java.util.logging is built-in and incredibly lame

They sucked every ounce of the joy out of log4j.

9) JTree selection behavior gives me a headache every time I have to deal with it

10) No method to just read an entire InputStream or Reader into a byte array or string

Same as join() above.

Bonus) No method to copy a file!


java

Importing Multiple WSDLs with Maven

March 11th, 2009

The jax-ws-maven plugin for Maven includes  the handy wsimport goal. This goal will take a WSDL from a URL or file and generate Java bindings for the service described.  The generated code may not be beautiful, but it works. Anyway, today I spent more than an hour fiddling with wsimport. In my case I was trying to import multiple WSDLs into my project with different target packages. I ran into several hurdles and figured that I’d document them here for future victims.

First, for better or worse, I’m working in NetBeans.  The Maven support is passable, but out of the box, the error reporting leaves a lot to be desired. In particular, detailed error reporting must be enabled. Otherwise, when there’s an error in your pom.xml file, you’ll get a nice <Badly formed Maven project> error with no other explanation. To enable error reporting go to Tools->Options->Miscellaneous->Maven, and check “Produce Exception Error Messages”. That will make your life easier. Now, about wsimport…

The obvious way to import multiple WSDLs is to include multiple executions in the jaxws-maven-plugin section of pom.xml. In fact, this is even the right way to do it… but if you just take your single-WSDL example, stolen from some tutorial somewhere, and copy it, you’ll end up with a couple of problems. First, when multiple execution are present, they must each be given a unique id, using of all things, the <id> tag.  This wasn’t that tough to figure out once I turned on error reporting as described above.

The second issue was more problematic and, in my opinion, probably a bug in the plugin. Each execution includes a “staleFile” which is used to manage dependencies, i.e. correctly recompiling WSDL when it changes. However, it happens that when multiple executions are present they use the same staleFile.  This means that the import of the second WSDL always thinks it’s up to date and thus never runs.  After a bunch of googling, I managed to find a solution in this bug report. So, the solution is to manually set a staleFile for each WSDL. Here’s the resulting <plugin> block from pom.xml:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>jaxws-maven-plugin</artifactId>
   <executions>
      <execution>
         <id>FirstWsdl</id>
         <goals>
            <goal>wsimport</goal>
         </goals>
         <configuration>
            <wsdlLocation>http://localhost:8080/FirstWsdl?wsdl</wsdlLocation>
            <wsdlFiles>
            <wsdlFile>path/to/FirstWsdl.wsdl</wsdlFile>
            </wsdlFiles>
            <packageName>com.example.first</packageName>
            <!-- Without this, multiple WSDLs won't be processed :( -->
            <staleFile>${project.build.directory}/jaxws/stale/wsdl.FirstWsdl.done</staleFile>
         </configuration>
      </execution>
      <execution>
         <id>SecondWsdl</id>
         <goals>
            <goal>wsimport</goal>
         </goals>
         <configuration>
            <wsdlLocation>http://localhost:8080/SecondWsdl?wsdl</wsdlLocation>
            <wsdlFiles>
            <wsdlFile>path/to/SecondWsdl.wsdl</wsdlFile>
            </wsdlFiles>
            <packageName>com.example.second</packageName>
            <!-- Without this, multiple WSDLs won't be processed :( -->
            <staleFile>${project.build.directory}/jaxws/stale/wsdl.SecondWsdl.done</staleFile>
         </configuration>
      </execution>
   </executions>
</plugin>

That’s it. Cheers.

java , , ,

The Ruby Way: Chapter 1 … bipolar

January 27th, 2009

I just finished chapter 1 of “The Ruby Way” by Hal Fulton.  I feel a little torn because it is simultaneously one of the worst chapters I have read, and also one of my favorites.  I’ll start with the bad.

The editing is pretty bad. I came across a number of typos which make me wonder if anyone actually read it before going to print. On top of that, this is some seriously sloppy technical writing (kind of like this blog). New or alternative terms are introduced without note, examples are only explained by cryptic, embedded comments, and seemingly complex concepts are given no examples at all.

The one statement that stuck out for me was on page 5 where the author describes the is-a relationship:

The relationship between a class and its superclass is interesting and important; it is usually described as the is-a relationship, because a Square “is a” Rectangle, and a Rectangle “is a” Polygon, and so on.

Ummm, please tell me that your first example of a class hierarchy isn’t one that if not just wrong is at least highly controversial.  You couldn’t have started with Person and Employee?

Hal Fulton calls this chapter “our review of object-oriented programming and our whirlwind tour of the Ruby language” so besides the typos and sloppiness, I’ll give him a break. That’s really a lot to jam into one chapter of a book whose intended audience is assumed to basically know all that stuff.

It’s like a man page. It all makes perfect sense if you already know it.

So as my hesitation grew, I reached section 1.5, “Training Your Intuition: Things to Remember”. This is where, in my opinion, the author turns everything around. This is one of my favorite sections of a technical book I’ve read in a long time. It’s basically a somewhat random laundry list of Ruby idioms, gotchas, and nuggets of general wisdom. It reminds me of the best stuff you find in a FAQ when learning a new language. It reminds me of the lists I write for colleagues when I have to bring them up to speed on a new technology. It reminds me of how I felt the first time I read Effective C++ when I was too young and foolish to recognize that for the oxymoron it was.  It’s all the stuff that you wish that a language manual would come out and tell you right away, but is completely missing or at least hidden between simplistic examples.

Great stuff. Anyway, at least he ended on a high note. Flipping through the rest of the recipe-style chapters of the book, I’m pretty confident I’ll find it invaluable specifically because it continues that laundry list style that for some reason appeals to me so much.

p.s. my “learning scala” project was a simple rules engine. For Ruby, I’m planning on a tcl interpreter. Hopefully, I can do it in less than 550 lines. Combining the speed of Ruby with the speed and expressiveness of Tcl … good times.

ruby

Remedial Scala: Interpreting Scala from Scala

January 25th, 2009

For my “learning Scala” project, rooscaloo, I needed to dynamically generate and compile Scala code as rules are loaded into the engine. I had initially intended to do this as an internal DSL, but I honestly couldn’t think of a way to handle the fact that variables are bound at match time in the rete network. This is a learning project anyway, so I decided to just generate code and compile it.  Now, I could have sworn I had seen a Scala scripting example using JSR-223 in a blog somewhere, but couldn’t find it again.  I only found one very basic example of how to do this, in the Scala bug tracker. So I figured I’d write down what I came up with.

Note that this code makes use of the scala.tools.nsc package which is not part of the standard Scala library. Thus, it may change in future versions of Scala. Also note that after the fact, I was able to track down two partial JSR-223 implementations here and here. It’s comforting that I ended up in basically the same place.

The example given in the bug tracker works, but it’s very simple and there are two things it doesn’t do. First, it prints all its output to stdout, including error information. Second, it doesn’t show how to retrieve results from executing scripts. That is, code goes in, but nothing comes out. These are both solved pretty easily.  In the first case, we simply supply our own PrintWriter when instantiating the internal Scala interpreter:

  private val writer = new java.io.StringWriter()
  private val interpreter = new ScalaInterpreter(new Settings(),
                                                 new PrintWriter(writer));

  ...

  def exec(code : String) {
    // Clear the previous output buffer
    writer.getBuffer.setLength(0)

    // Execute the code and catch the result
    val ir = interpreter.interpret(code);

    // Return value or throw an exception based on result
    ir match {
      case Success => ()
      case Error => throw new ScriptException("error in: '" +
                                              code + "'\n" + writer toString)
      case Incomplete => throw new ScriptException("incomplete in :'" +
                                                   code + "'\n" + writer toString)
    }
  }

For the second issue, returning results, I had to think a little longer, probably longer than necessary. scala.tools.nsc.Interpreter doesn’t return anything besides Success, Error, or Incomplete as seen above. But, you can pass objects in, so I ended up creating a container object to hold the result:

class ResultHolder(var value : Any)

  ...

  def eval(code : String) : Any = {
    // Clear the previous output buffer
    writer.getBuffer.setLength(0)

    // Create an object to hold the result and bind in the interpreter
    val holder = new ResultHolder(null)
    bind("$result__", holder);

    // Execute the code and catch the result
    val ir = interpreter.interpret("$result__.value = " + code);

    // Return value or throw an exception based on result
    ir match {
      case Success => holder.value
      case Error => throw new ScriptException("error in: '" +
                                              code + "'\n" + writer toString)
      case Incomplete => throw new ScriptException("incomplete in :'" +
                                                   code + "'\n" + writer toString)
    }
  }

As you can see, I ended up with two separate routines. exec executes a Scala statement, ignoring its return value. This is useful for imports, class declarations, anything that does not evaluate to a value.  eval executes a Scala statement, catches the result and returns it.

Anyway, that’s about it. It seems that full JSR-223 support is in the plan for Scala. Until then, what I have here works for me and it was a good learning experience. Here’s the full source for my solution.

scala ,

Remedial Scala: XML

January 21st, 2009

Tonight I finally got to the XML chapter of Programming in Scala. I was excited because I had seen a few examples on the web and wanted to try something out that wasn’t jdom or jax-b or whatever. So, I read the chapter and it was … short. The authors even admit in the conclusion that it barely scratches the surface and I have to agree :)

Anyway, my exercise for Scala’s XML support was adding an XML encoding of rules to rooscaloo. My plan is to eventually write a parser with parser combinators, but that’s not until chapter 31.

Overall, Scala’s XML support is a dream compared to anything I’ve done in Java before. I began by creating some case classes for my AST:

  case class RuleAST(name : String,
                     fireCode : String, unfireCode : String,
                     conditions : ConditionAST*)

  case class ConditionAST

  case class ObjectConditionAST(typeName : String,
                                binding : String,
                                testCode : String) extends ConditionAST

  case class NotAST(children : ConditionAST*) extends ConditionAST

really simple stuff.  Here’s what a rule looks like in XML:

    <rule name="bob-is-not-a-cat-lover">
      <if>
        <object type="Person" binding="p"> p.name == "bob" </object>
        <not>
            <object type="Cat" binding="c"> c.owner == p </object>
        </not>
      </if>
      <then>println("bob does not fancy cats")</then>
      <unfire>Tprintln("bob now owns a cat!")</unfire>
    </rule>

(I couldn’t think of a better name for rule retraction than unfire…)

and here’s the satisfyingly compact code to convert an XML node to a RuleAST object:

  def parseRule(node: scala.xml.Node) : RuleAST =
    RuleAST(node \ "@name" text,
            node \ "then" text,
            node \ "unfire" text,
            parseConditionList(node \ "if" \ "_") : _*)

  def parseConditionList(xml : scala.xml.NodeSeq) : Seq[ConditionAST] =
    for(e <- xml)
      yield e match {
        case <object>{ _* }</object> => parseObjectCondition(e)
        case <not>{ _* }</not> => parseNot(e)
      }

  def parseObjectCondition(xml : scala.xml.Node) : ObjectConditionAST =
    ObjectConditionAST(xml \ "@type" text, xml \ "@binding" text, xml.text)

  def parseNot(xml : scala.xml.Node) : NotAST =
    NotAST(parseConditionList(xml \ "_") : _*)

This could actually be much more compact but I chose to break it up into methods so I could test each construct individually. Still, I’m fairly certain there’s an even better way to do this, but this represents 45 minutes of work including unit tests, so I’m still pretty happy. One thing I discovered that wasn’t covered in the book was the use of the “_” wildcard to get all sub-elements of a node. For example we can see above that I use:

   node \ "if" \ "_"

to get the list of all child elements of the <if> node.

The match statement in parseConditionList is a little irritating to me and I feel like there’s probably a better way to do that.

Just like the book, I’ve obviously only started to scratch the surface of  Scala’s XML support. Since I also just read the chapter on extractors, it seems like it might be interesting to define extractors to automatically convert XML to an AST. Of course, there’s also XPath, transforms, etc.

Maybe tomorrow night. It’s time to sleep.

p.s. here are some more Scala XML resources I’ve found useful:

scala ,

Remedial Scala: Emulating C# Extension Methods

January 17th, 2009

I admit that, as a Java programmer, I’ve been jealous of C#’s extension methods for a while. Java’s getting pretty long in the tooth. While C# is adding lots of cool new features, Sun doesn’t have the balls to even add closures despite three working implementations to choose from.  I get bimonthly reports from a former co-worker and C# aficionado of this or that cool feature that Java will never have.  He loves to rub it in.

I know that extension methods are just syntactic sugar and any Lisp adherent will tell you they’re really just a poor man’s version of generic functions.  But I want them nonetheless.

So, forget about Java. I’m pleased to say that in Scala it is easy to emulate extension methods. Here’s Microsoft’s example code in C#:

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

this just adds a WordCount method to the built in string class. Here’s the equivalent code in Scala, with a main method for good measure:

object Main {

  implicit def stringToWordCounter(s : String) = {
    new {
      def wordCounts : Int = {
        s.split(Array(' ', '.', '?')).map(_ trim).filter(! _.isEmpty).size
      }
    }
  }

  def main(args: Array[String]) {
    println("Hello Extension Methods".wordCounts)
  }

}

This makes use of Scala’s support for implicit conversions. If a method is called on an object that doesn’t exist on that object’s base type, the compiler searches for an implicit method (stringToWordCounter in this case) that converts to a type that does have that method. stringToWordCounter converts implicitly to a anonymous class that just happens to have a wordCount method. Cool. Note that the returned type can have any number of methods and may also implement traits (interfaces).

One thing I don’t know about is performance. Implicit conversions mean constructing a new intermediary object to call the method on. Maybe the compiler is smart? Anyway, this is remedial Scala, so I’ll worry about that later.

Also of note in this example is how much nicer the code to split, trim, and filter the input string is. I’m assuming there’s some other, more functional way to do this in C# without resorting to the long-winded StringSplitOptions.RemoveEmptyEntries flag.

That’s it for today’s installment of Remedial Scala. See you next time.

scala , ,

Buffalo buffalo buffalo buffalo …

January 16th, 2009

Today I had a programming experience akin to the grammatically correct sentence “Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.”

I’m working on a DSL that has values, which probably should have been called elements instead. I say this because I had to add a value keyword to the language which, of course, entailed a class named ValueValue. See where this is going? I knew things had gotten out of hand when I wrote this line of code:

    ValueValue valueValue = (ValueValue) value;

Yipes. Maybe this is why some think naming constructs is the hardest thing about programming.

software engineering ,