Anacron squeezing the life outta my Mac?

8 05 2008

So I download Anacron because I’m sick of manually launching Mac Janitor to run daily, weekly, and monthly stuff right? Ever since then I start having all kinds of crazy issues. I loose settings and preferences left and right. It started with Quicksilver spontaneously quitting and forgetting what it was supposed to look like when it reopened. Then I noticed Parallels started looking elsewhere for my WinXP VM install. (I have it under ~/Library/Parallels which may or may not be the default.) All of the sudden RDC can’t remember the defaults for talking to my Dell. It’s crazy and it all started when I installed Anacron. The bad thing is I don’t know how to uninstall software on a Mac yet. In windows you have add/remove programs, in Mepis/Ubuntu I could always rely on Synaptic, on a Mac you’re supposed to be able to just delete the .app folder but what about software that installs via an installer? Has anyone else had similar issues with Anacron? Is it just me???




Lok! I rote a benshmark!

7 05 2008

Hey smart peepoles! Lookie here! I rote a code that can be utilised to see how much more wirst your favorite language is dan minez!!! Lookey!

Language Minez


short startTime = Clock.getcompooterClok().whatTimeIsIt()
Console.getTurminalz().riteLetters << "Hi Momma!"
short stopTime = Clock.getcompooterClok().whatTimeIsIt()
Console.getTurminalz().riteStuff << "It only tooks " &lt;&lt; (stopTime - startTime) << "!!!"

Language Yourz


<target name="go">
   <script>
      long startTime = System.currentTimeMillis()
      StringBuffer message = new StringBuffer()
      System.out.println "" + message.append("Hi Momma!").toString()
      long stopTime = System.currentTimeMillis()
      System.out.println "Look howe much more longer it tok here " + (stopTime - startTime)
   </script>
</target>

Here are the times, no lie:
My Favorite toy: 203ms
Your Dumb Syntax that you like: 4851ms

See! It’s obvious that MinezScript is way more JohnBlaze than your dumb language that you like!! More John Blaze in every way! I don’t even see why they still make your dumb language that you like!

That’s what I saw posted on a WordPress blog tonight. I’m not even going to link to the site because it’s just not worth it. If I see one more dumb performance analysis, or language comparison like that I’m going to dress the author in an A1 steak sauce jersey and throw him into a pool of gravy surrounded by hungry lions. People still think a benchmark surrounding a single line of code executed multiple times is enough to draw a sensible conclusion on whether or not to use a given technology.




Using Groovy with Maven

6 05 2008

Quick update. If you use Maven and got used to Groovy a while ago (in the 1.0 and 1.1 days) like I did you might be looking for Groovy-1.5 in the Maven repos. Don’t look here. Instead look here. The groovy stuff is in a new location under org/codehaus/groovy.




The Motivation Why We Do Things Part I

5 05 2008

We, as humans, are a strange species. We buy scented toilet paper. We tour places with tall buildings, climb these building only to put money into telescopes so that we can see the ground close up. We report power outages over television broadcasts hoping to reach that one person running a generator out of his garage so that he can scramble and notify the rest of the neighborhood. We impose death penalties for murderers to teach that killing is wrong. Then during the lethal injection we sterilize the needle and swab the area with alcohol to prevent germs from spreading. We sometimes invent things or come up with ideas only for the sake of creativity. For example, there are braille dots on the keypads of drive up ATM machines. Then there’s that torch setting on the toaster which will transmogrify a slice of bread, no matter how thick, into dust as the timer expires. (Who thought that was a novel feature?) Today I got to thinking about what motivates us to do some of the things we do. More specifically, what motivates us to approach problems a certain way?

Here at Can’t see nothing but the source code the focus is on software engineering. Writing software is all about converting people’s thoughts and ideas into a barrage of ones and zeros so some electronic device can execute them. Most engineers obsess over the details of:

  1. Their favorite… *cough* Groovy… *cough cough*… programming language
  2. Their favorite intellij I mean intelligent IDE
  3. Their favorite platform
  4. Their deep understanding of some algorithm

There are, no doubt, other things they obsess over but these are by far the most popular. In fact, you can’t be a qualified engineer unless you have a touch of Aspergers syndrome and/or are obsessed over something that normally people take for granite. So is it a wonder why software engineers have such a hard time with product management? Is it a surprise that any time you get any two half way decent software guys in a room they will argue over something as time-wasting as an Integer vs. a short? The more qualified the engineers the longer the argument ensues. You want that kind of argument. You may not want it to go on forever but you do need to entertain some of these dumb discussions. It’s healthy for the project and while it feels like it makes your deadlines slip it’s healthy for project management. If you don’t entertain two tech guys entertaining themselves over why SWT is way more betterish than Swing then you’ll end up with competition and divergent ideas. It’s important to encourage these debates but not let them run on mindlessly.

We’ve all run into our share of horror code. Y’know the complicated backward counting loop that always skips the second to last index, or the complex multi-line boolean expression that when simplified turns out to be a constant if true=false. No matter how often you see this stuff isn’t your first reaction, “why in [insert explitive expression referring to bowel movement, sexual encounter or home of brimstone] would some bonehead do it that way?” If you expound on the motivation you will most certainly find a developer under the gun to figure out a problem for which there was no proper decomposition when the code was originally written. The lack of decomposition comes from the author’s (not necessarily the guy that wrote the hack) obsession over a deep understanding of some particular domain problem. It goes like this. The product owner says, “we need a quarterly break out of our gross profit margin and these reports only give year end totals.” The original developer says or thinks, “Oh, I’ve tackled cross tab queries at my last job and I came up with the Oracle flavored secret sauce to make them perform like lightning. Alls yuh haff tuh do is…” then the code is written. Days later when the original author is in Florida on his second honey moon and junior developer Sam, who happened to be filling the coffee pot the same day Mr. Guru went off on his cross tab rant, is assigned to go fix the off by .001% bug you end up with the bone headed hack we described above.

You ever start a new job and hit a wall when someone says, “we have a strict policy and we absolutely don’t do X” and X is something absolutely critical to software development, like “do regression testing”, “use and IDE”, “compile our code”, or “use the internet”? Many times the issue lies in nomenclature. The company actually does “thing X” but does it in such a round about way that they have completely renamed and reinvented it’s intention. I worked at a company on a Java project where the nightly build was a series of make files that recursed through folders compiling folder by folder and took hours to complete. I also worked at another job where the build and release process could not be automated because the possibility of error so it made sense to have a person run each step so that it could be confirmed and validated without issue. (Translation, management needed someone to blame/harass/terminate instead of some process.) I’ve worked with people who swore every possible piece of functionality could be implemented or belonged in a DBMS table. I’ve also worked with people who thought reading books on programming was an optional practice and completely unnecessary barring you had enough experience dealing with real rather than text book issues. In all I’ve seen my share of craziness.

Nothing tops this
In all my years of software development I’ve never seen anything difficult to understand than this one guy. He deployed a special servlet to a production box that would accept hot deployments of a product that was being developed internally. He didn’t write the servlet but for some reason he was so obsessed with the thought of being the servlet’s to bypass certain security restrictions that had been plaguing him since the beginning, that it became sensible to try out this functionality on the release day of the product. Now considering all normalcy of common sense one would typically refrain from a such an idea as it:

  1. involves production hardware
  2. is the release day of a highly visible product
  3. had not been ok’ed by management
  4. involved practices that were frowned on in the company

But this guy’s motivation was outside the realms of common sense. Motivation for stoopidity comes, in the tech field, from obsession. Whether it’s obsession over how much heat your thermal component can emit, obsession to make money or obsession over a development philosophy it’s always rooted in obsession. Some people obsess over sandwiches, while others obsess over anything from bunnies, to marbles, to motorcycles. In many ways it can be a good thing mostly when controlled. Seeing these obsessions as the root of all stoopidity takes talent, and insight.

Have you been there? Have you been the victim or the catalyst of some form of motivation? Have you or a loved one been hurt by someone else’s motivation? Speak on it people….




Debugging while profiling… driving while drunk

5 05 2008

If you own a copy of JProfiler and you wanna do something sensible like, oh I dunno, debug a remote server while profiling it watch out! There’s an unwritten rule in Java land, “never attach more than one JVM instrumentation device at a time”. You shouldn’t chew gum while walking, you’re not allowed to drive while drinking, rubbing your head and patting your tummy is advised against, and don’t try to JProfile with a debugger connected. If ya’ don’t know, now ya’ know…




Pyx4ME Hack

1 05 2008

It’s late tonight but I gotta get this posted. I’m still trying to get a good dev cycle with the Maven Pyx4ME maven plug in and IntelliJ Idea. I’m running on Parallels on my Mac. Here’s an extra tag I added to the project generated from the pyx4ME archetype:


<plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <executions>
          <execution>
              <id>run</id>
            <phase>install</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <tasks>
                  <property environment="env"/>
                  <echo message="Running WTK out of ${env.WTK_HOME}"/>
                  <taskdef resource="antenna.properties"/>
                  <wtkrun jadfile="target/${project.artifactId}-${project.version}-me.jad"/>
              </tasks>
            </configuration>
          </execution>
          <execution>
              <id>site</id>
            <phase>site</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <tasks>
                <copy overwrite="true" file="${project.build.directory}/${project.build.finalName}-me.jar" tofile="${project.build.directory}/site/mymidlet.jar" />
                <copy overwrite="true" file="${project.build.directory}/${project.build.finalName}-me.jad" tofile="${project.build.directory}/site/mymidlet.jad" />
                <replace value="mymidlet.jar" token="${project.build.finalName}-me.jar" dir="${project.build.directory}/site">
                  <include name="mymidlet.jad"></include>
                </replace>
              </tasks>
            </configuration>
          </execution>
        </executions>
          <dependencies>
              <dependency>
                  <groupId>net.sf.antenna</groupId>
                  <artifactId>antenna</artifactId>
                  <version>0.9.14</version>
              </dependency>
          </dependencies>
      </plugin>

This lets me run my project using WTK assuming WTK_HOME is been set as a system env var. More stuff later.




Maven, Ant, Ant Builder, Gant, and the hand that rocks the Gradle

1 05 2008

Developing software is an iterative process that begins and ends with a build system. Over the years I’ve learned that such a system can make or break a project. As such I’ve become very anal about the build process because IT is what it takes to complete a development cycle and the development cycle is what drives the direction of software. If the cycle is too long developers take or create shortcuts. If the cycle is too complicated requiring too many steps or too much setup, developers make critical mistakes which lead to the creation of imaginary-required safegaurds. These shortcuts and safegaurds make their way into the core of your software creating baggage and removing features while adding no functionality. So the build system is very important to the overall health of your project.

In Java land there has long been the world renowned Ant project. Something that started as a simple hack but became an ecosystem of good ideas. Years later another project, Maven started as an attempt to standardize on these good ideas. The Maven project recognized one important thing… all of these Ant based projects were doing the same thing, building software. It was early in its time and had some rough spots so then the Maven2 project was born. I’m not going into the history of Ant and Maven, instead I want to focus on what I feel is the most important goal. While there may be more than one way why does there have to exist so many right ways? Look at the title above. See all of those build entries in the list? Every entry in the list represents a genius idea. Each one addresses a slightly different problem. Now what would happen if we could throw them all into a pot with some curry, stir well, then bake for about an hour and 15 minutes? More important, what would happen if we took the core dev team from each project, locked them in a room with a limited supply of beer and oxygen and allow them to exit with only one 4-5 letter acronym to save the day of struggling engineers trying to build and deploy software?

I personally like Maven, not because I believe it to be the best or even easiest build technology, but because it remembers and enforces the most important idea: “We’re all doing the same thing, building and deploying software!” I’ve seen so many discussions and efforts on build stuff mostly focused in the wrong area, syntax. People usually get themselves into a tangle with Ant where they need a mutable property or a loop or an if/then or some other procedural thing and feel trapped. Other people get themselves into a tangle with project structure and/or build lifecycle where they feel they need to impose order of operations to skirt what’s actually a circular dependency they’ve blinded themselves to or some improper manual contrived dependency management solution. Whatever the case they always point to one of the two biggest scapegoats: Syntax and XML. (Of course XML is a syntax! That was the point of that last joke!)

Syntax isn’t everything!
Syntax is important but it’s not the whole picture. You can create a marvelous project with even the most hideous syntax if you understand structure. True syntax lets you better identify and express good structure but it’s not a prerequisite. Let’s look at it this way. X may have better prettier syntax than Y which has better syntax than Z. But if Z requires a certain structure or orderly way of thinking where X and Y allow and possibly encourage random structure then what are the true advantages?

What’s this Gradle Project?
I just finished reading up on Gradle which would almost look like Gant except that they’ve taken an slightly different approach. There is some Maven’ish convention over configuration in it and I gotta say… I really like what I see. I think I’m on like the 2nd chapter or so of the PDF documentation, which is well written. You know a good project when you see well written docs and comprhensive examples. You can just tell a lot of thought went into the overall design. Gradle attempts a build language using Groovy DSL concepts. What that dumb sentence means is that it contorts the Groovy syntax to allow you to logically express build constructs like tasks, dependencies, sub-projects and the like. Like Gant it integrates Groovy’s Ant Builder which gives you direct and full access to all of Ant’s capabilities using Groovy’s builder notation which mirrors XML tag syntax without the restrictions of XML. You can do stuff like:

   mkdir(dir: scriptDir)
   copy(todir: scriptDir) {
       fileset(dir: 'bundle-includes/scripts', excludes: 'start*')
    }


Which mirrors Ant syntax like:


   <mkdir dir="$scriptDir}"/>
   <copy toDir="${scriptDir}">
      <fileset dir="bundle-includes/scripts" excludes="start*"/>
   </copy>

Gradle goes further allowing multi-project builds and dependencies to be expressed in this syme syntax:


subprojects {
   manifest.mainAttributes([
           'Implementation-Title': 'Gradle',
           'Implementation-Version': '0.1'
           ])
   dependencies {
      compile "commons-lang:commons-lang:3.1"
      test "junit:junit:4.4"
   }
   sourceCompatibility = 1.5
   targetCompatibility = 1.5
   test {
      include '**/*Test.class'
      exclude '**/Abstract*'
   }
}

What about Gant?
As much as I love Groovy and Maven I also dig Gant. I’ve written my first build with it. I n my build I wrap a Maven multi-project build and assemble a tarball of Tomcat with our application pre-installed. It sounds much fancier and prettier than it really is. Gant much like Gradle gives you the builder syntax and a rich set of APIs to interact with. Gant also mirrors Ant structure more closely than Gradle, following the same nomenclature that Ant uses. Gant targets equal Ant targets, Gant tasks equal Ant tasks and so forth. Gant introduces target sets which from my limited understanding are preconfigured targets that know how to do certain things. So far I’ve only used the “clean” target set which already knows how to clean your project. In my build I overrider the clean directory (a feature of target sets), just because I can. Gant promises Maven target sets and also integrates with Ivy. Here’s an example build that uses the MavenTargetSet to build Gant itself:

includeTargets ** gant.targets.Maven * [
    groupId : 'org.codehaus.gant' ,
    artifactId : 'gant' ,
    version : '1.2.1-SNAPSHOT' ,
    javaCompileProperties : [ source : '1.5' , target : '1.5' , debug : 'true' ] ,
    deployURL : ‘https://dav.codehaus.org/repository/gant’ ,
    deploySnapshotURL : ‘https://dav.codehaus.org/snapshots.repository/gant’
    ]

setDefaultTarget ( install )

Overall there’s a lot to be gained by using Gant and I’ve only scratched the surface.

Then there’s Maven
While new projects like Gant, Gradle, Raven, Rake or whatever promise better syntax along with convention over configuration simplicity there’s still Maven. It’s an established project with a lot of maturity that not only builds with far less XML than Ant but also brings in a lot of other features. Maven has plugins that operate almost like mini programs within your build system. I couldn’t understand the complexity involved in creating a plugin initially as I’ve been used to Ant’s simple “create a class with an execute method” idea. But when you look at what Maven plugins do and can do you see they are more than just software components. A build plugin can do anything from simply attaching additional artifacts to the build to completely altering or replicating the build life cycle. Cargo is a good example of the possibilities. With cargo you can completely automate every step in the life cycle of a JEE application from the aquisition of the container (it auto-downloads from the net), to the installing of your product starting and stopping of the container, to integration testing and more. Maven offers the release plugin that ties in your VCS system. Performing releases with Maven allows you to tag not only your product but record the tags or release version of everything your product and your product’s build depends on. That alone is a very powerful feature that you only appreciate when attempting to rollback and reproduce an earlier build. While tools like Ant and Ivy can manage project dependencies Maven manages build dependencies the same way so you can garauntee for eg. that the same version of JUnit and the Xalan Compilers that ran 3 weeks ago during a tag are invoked today when you wish to reproduce. This works because everything involved in a Maven build is either a plugin or a dependency marked with the same name, group ID, and version convention. When releases are performed Maven ensures that there are only released versions involved in the build and commits an expanded project descriptor that notes the precises versions involved to the VCS (Version Control System). In other tools like Ant and Gant, extensions are stored in the tool’s home folder typically in a lib directory and are subject to change. Maven pulls every extension and artifact from a shared repository.

There’s a lot of features in all of these build technologies and I’ve gotten waaay off topic forgetting my point. I’ll summarize: There are a lot of options for building software and each looks more enticing than the others. However, I encourage you to do your homework when selecting one.




How many lines of Java?

29 04 2008

You need to open a web connection to some site and post some binary data from a local file. You need to validate that the site returns data that matches byte for byte the contents of another file stored on your hard drive. You need to return pass or fail depending on whether or not the data matched. Sounds simple enough, right? I’m setting my stop watch… you have 10 minutes to scroll to the comment section below and code the logic in Java… Ready? Go!

What does it look like? (Did you hit the submit button when you were done?) Did you get it right on the first go? No, we don’t have a back-end compiler and test engine on this site so you wouldn’t get a green bar when you hit submit. The point here is to find the bug. You got a bug somewhere in that logic! First ask yourself, what’s it doing with the streams? Are you closing them all properly or leaving them to Roc, the garbage collector? Did you side step all of the try/catch ugliness with the big oogly try/catch generic Exception that squelches your NullPointer issues? That’s a big bug, believe it or not, because it hides the real problems for you and sends you on wild goose chases. (Who chases wild geese anywayz? What happens when you catch one? Is there a prize? Do you become a wild goose in turn with other hungry savages chasing your tail wielding fork and knife?)

The other point is why bother? Look at the code. I bet there’s a lot of bloat, unless you’re reaching out to some 3rd party API or framework. If you are then you get an F for cheating cuz you can’t submit binary jar includes in the comment section which means you stuff won’t run anyway. Here’s a breif snip of the very same requirement using Groovy:


def runTest(url, reqMethod, requestBinFile, responseBinFile) {
    def con = url.openConnection()
    con.requestMethod = reqMethod
    con.doOutput = true
    requestBinFile.withInputStream { input ->
        con.outputStream.withStream { output -> output << input }
    }
    assert HttpURLConnection.HTTP_OK == con.responseCode
    responseBinFile.withInputStream { input-> input.eachByte {theByte -> assert theByte == con.inputStream.read().byteValue()} }
    con.inputStream.close()
}
    try { runTest(new URL("http://myremotesite.com"), "POST", new File(resourceDir, "typicalRequest.bin"), new File(resourceDir, "expectedResponse.bin")) }
    catch(AssertionError e) { return "fail: $e"}
    finally { println "Done!" }
    return "pass"

While there is a dangling close on the input stream the entire thing could be written without explicitly calling to close anything. The magic comes from the callback pattern as you’ll see in this walk through.

But that’s not Java!
Look again. We are using standard Java API objects URL and File.
new URL("http://myremotesite.com")
new File(resourceDir, “typicalRequest.bin”)

We just didn’t have to import them. Our variables are untyped and we dropped semi colons because it’s unnecessary.
def con = url.openConnection()
All of our get/set methods become accessible using properties syntax. We also have auxiliary helper methods, more on that below.

Decorated Objects
Groovy comes as the Amaretto creamer in your cup of Java. It decorates standard Java objects with additional capabilities. For example, there’s an execute method added to java.lang.String that turns any string into an instant command line. You can do stuff like:
"cmd /c explorer C:\\myscreenshot.png".execute()
to open up an image on your hard drive. They’ve also added goodies like plus(int days) to the java.sql.Date object. All of the stuff you would normally break out into a util component has been tucked neatly inside the Groovy enhanced Java API.

New Style
If you’re still for looping and switch casing your way through development you need to get with the program. There’s a new style of programming and either ya’ with it or yer’ slackin’! My example shows off the power of closures and call backs. Let’s talk about what they are and the things they bring to the table. Typical programming requires iteration which results in the loop. In tasks like the example above you need to acquire some resource iterate and dispose of the resource. Since Java uses checked exceptions in a lot of it’s low level API calls you’re forced to deal with them at every turn. The actual thing you are trying to accomplish gets lost in a flurry of noise code dealing with the state of indexes or counters, loop constructs and exception handling. With the callback pattern (which is also possible in pure Java) the iteration, state management, and exception handling is dealt with by some object that you call. This object calls back the code that invoked it on each step of iteration. (You can use callbacks for more than just iteration.) You write logic that looks like so:
networkThingIterator.iterateNetworkThings(this);
instead of:

Connection con = null;
try{
   con = networkThing.connectToNetwork();
   int count = con.getCountOfThingsToDealWith();
}
catch(NetworkException e) { /*I dunno what to do here, I never do so...*/}
for(int i = 0; i < count; i++){
   try{ networkThing.doNetworkStuffWith(localVariable); }
   catch(NetWorkException e) {/*I dunno what to do here, I never do so...*/}
}
finally {
   if(null!=con) try{con.close();} catch(Exception e) {/*Ooooh... I'm squelching!!!*/}
}

We do this in plain old Java but we have to implement an interface which many would inline turning the above example to:
networkThingIterator.iterateNetworkThings(new NetworkThingHandler() {
public void handleNetworkThing(NetworkFooBar foo) {
//The innards of your for loop goes here!
}
});

Not too bad but there’s a little bit of noise here. The syntax of Anonymous inner classes mandates you write an entire class definition where all you really want to write is the method to handle the iteration.

Enter closures
With closures you write what looks, works, and smells like a method but can be grabbed hold of like an object. It removes the cruft of anonymous inner classes and adds the ability to pass a method or an action, or a thing to do (i.e. verb) to an object that does callbacks. Our above networkThing iteration would look like:
networkThingIterator.eachNetworkThing( {
//handle network thing here
}//End of closure defitnition
);//end of method call

Back to the example
In our initial Groovy snip we see closures being passed to what looks like magic methods added to the OutputStream and File objects. These withStream methods contain callback logic that opens the stream, passes it to the closure, and closes the stream. We also have another piece of magic in the left shift operator [<<] that pipes or reads the contents of an InputStream to an OutputStream. The net result is code that focuses on the real task of connecting to streams without the noise of try to open, catch exception, blibbidy-blobbidy, try to close. Look closer. There’s another call back decorated onto InputStream that performs iteration on eachByte and passes it to the given closure. It’s named eachByte. Self explanatory enough? I’d write more but I’ve become way to verbose on the topic so hit me up with any finer details or points of interest.




IIOException can’t create cache file

28 04 2008

Tomcat + ImageIO

What do you get? Trouble! Who would guess that doing PNG with JDK APIs conversion requires you to have a temp folder off of $CATALINA_BASE? After being labeled the build master unofficially, I took the initiative (if you can call totally screwing up a quasi-production deployment initiative) to prune what looked like cruft from a template tarball. Among this cruft was our precious temp folder. Let me explain better.

We use a deployment template for production builds. You know how this stuff goes when one developer gets something working and management says something like, “can you make yours work like his?” Thus begins the binary hand-off. A binary archive of the stuff he did bequeathed unto you to bring identical magic to your project. You then hand it down to the next developer that needs to do something similar. And so on and so forth. The entire idea is crazy but it’s the stuff major companies run on. by the time it gets handed to the 5th or 12th person down the line nobody remembers or understands anything from the original project only that this thing is what’s supposed to make everything else work just like it.

So I get this tarball, and I’ve got plenty others that look sorta like it that I tried creating from scratch. Some of mine half work while others just flop. I loose track because all correspondences with the deployment team and myself happens in a loosely coupled chain of random emails and secure copies to locked down servers that I have no business touching. I finally get something working that I can actually automate but I feel dirty because this binary template is checked into our version control system. So I begin cleaning the cruft, extracting the true thing that our project needs… structure not binary data. Everything begins to work. Everything except for a few execution paths that I have not had time to QA due to my tight schedule. I ask for QA from the QA team but I’ve been so tied up in performance tests that I can’t let the team anywhere near the deployment. I find other issues due to my not following certain design patterns. I fix issues. But the entire thing takes sooo much effort because I work in a highly secured environment. I work with one guy that’s been a blessing giving me higher than usual access rights as if I truly knew what I was doing on a Linux box. (Wasn’t I losing my Linux touch just days ago?)

The end of my plight is today. After hitting the “IIOException can’t create cache file” thing I Googled and found some info hinting to some more detailed discussion that only hints that you need a temp folder configured for Tomcat. I examined the startup script and plugged in the missing temp folder and voila! Everything worked as it should.

Moral to story
If you get: IIOException: can’t create cache file!
And you’re running in Tomcat
Then you need to make sure $CATALINA_BASE/temp actually exists and is writable.

By default Tomcat’s startup scripts set java.io.tmp.dir to $CATALINA_BASE/temp but this could be overriden by a number of different ways. It is the java.io.tmp.dir that is used by ImageIO and possibly numerous of other 3rd party APIs and open source components for cache files and other temporary stuff.




Get’cha Groove On

26 04 2008

I’ve been slowly getting back into my Groovy state of mind after immersing in Maven2, Servlets, and J2ME for over a year. If you’re one of those people who can’t stand yet another programming language then this topic is for you. If you’re one of those who think “My language grammar suites me just fine” then step off! I ain’t even tryin’ to holler at you. If you’re one of those people who don’t understand why a language is so important than allow me to elaborate.

Modern languages are about high level expressiveness, getting things done by mirroring the thought more closely which requires less specific steps. For instance: The loop has been done many times over. We don’t want to think loop until I get my desired result. in my variable which is a value equal to the number of files in a directory. We want to express that we are taking some action on each file in a folder. Older style languages pay little if any attention to the need to express the thought of a developer. Rather they organize the mechanics of the syntax to allow re-use of common constructs. if/select/while constructs are being replaced with closures. Code generation and reflection are giving way to Meta Object Protocols. The new thing in town is DSL, which focuses on how easy it is to express the intent of the logic by massaging and bending the syntax of the language.

That said, you can probably tell that I’m going to speak about Groovy for a minute. If you don’t want to learn another language then Groovy is perfect for you! You most likely already know it. Take the following snip for example:


import java.io.File;
import java.util.*;

public List getNamesOfMusicInFolder(File folder) {
   List names = new ArrayList();
   File files = folder.listFiles();
   for(int i = 0; i < files.length(); i++)
      if(files[i].getName().toLowerCase().endsWith(".mp3")) names.add(files[i].getName());
   return names;
}

If you can write or figure out code like that then you’re already a Groovy programmer. Expert points if you happen to know the Java API. Now why is that so interesting? Because we can groove it up by doing Ruby like stuff with the same familiar programming constructs, APIs and platform that we’ve been using for years. Start by removing semi colons, Variable declararations and import statements because Groovy makes them unnecessary.


def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   def files = folder.listFiles()
   for(int i = 0; i < files.length; i++)
      if(files[i].getName().toLowerCase().endsWith(".mp3")) names.add(files[i].getName())
   return names
}

Now let’s pretend getter and setter methods are properties, because Groovy doesn’t care about the difference. And while we’re at it we’ll use the left shift operator which also doubles as an append operator:


def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   def files = folder.listFiles()
   for(int i = 0; i < files.length(); i++)
      if(file[i].name.toLowerCase().endsWith(".mp3")) names << file[i].name
   return names
}

Now use a more modern loop construct:


def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   for(file in folder)
      if(file.name.toLowerCase().endsWith(".mp3")) names << file.name
   return names
}

Wait! Why are we looping at all? Let’s pass a closure to the each method. A closure is a chunk of code that the each method executes on each thing:


def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   folder.each( { file -> if(file.name.toLowerCase().endsWith(".mp3")) names << file.name } )
   return names
}

Kinda ugly but remember that parenthisis are optional in Groovy


def getNamesOfMusicInFolder(folder) {
   def names = new ArrayList()
   folder.each { file -> if(file.name.toLowerCase().endsWith(".mp3")) names << file.name }
   return names
}

And on and on and on, till the break of dawn or at least until we get it down to the beautiful one liner that would cause your average gear head to brag more than George Castanza grabbing the first parking spot.


new File(dir).listFiles( { dir, file -> file.toLowerCase().endsWith( ".mp3" )  } as FilenameFilter )*.name

What about bindings? Where are the bindings? What are bindings? Bindings are interfaces or APIs that a given platform or framework offers for programmers that use a given language. Groovy is just Java with flava. That means anywhere there’s Java bindings there’s groovy bindings. And since any interface or API can be grooved up that means you can actually modify or add flava to those bindings. More on that in another post.

That’s a small example of what you can do with Groovy. There is a much bigger picture here, the Java platform. Groovy compiles to, runs on, plays well with, the JVM. You don’t need a separate skill set to take advantage of what people from other camps brag about. Java already has several GUI builders, Mattisse being among the best. Java has what I believe is some of the best IDEs ever thought of. (IntelliJ Idea and Eclipse though many complain about Eclipse memory issues.) Java supports presentation engines that regurgitate Flash or AJAX. Java is the king of server deployment simplicity… just plug a spec compliant archive in and go. JVMs are on midranges mainframes, browsers, and mobile devices. (I’m not to crazy about mobile JVMs.) To coin a phrase, “Java is everywhere you wanna be.”

Taking that idea even further, the Groovy camp offers features such as “.Net” interoperability, Windows binaries, and COM scripting that means even on Windows platforms you aren’t that far from native behavior while leveraging the same familiar syntax and VM that uncle Otis grew up with. I could go on forever but I’m gonna take a break now and actually do some Groovy coding. I’ll come back with something we can all admire.