Development tips and tricks

Fun with PNG Gamma Channels

I was doing some web-site work for a customer last night, when I noticed a very bizarre thing in IE7.     I had a div with a background color (defined with CSS), and next to it was another div with the same background color (this time as a PNG background image.    The color of the PNG was the same color as the background CSS color.     In Firefox, Mozilla, and Safari the divs were seamless (the colors matched perfectly).    In Internet Explorer, the colors were off every so slightly, ruining the seemless effect.

 

It turns out, other people have seen issues just like this one.   It turns out to be an issue with how IE deals with the gamma channel in PNG.

 

A couple of work arounds:

  1.  Use either all CSS or all PNGs (at least things would be consistent!).
  2.  Remove the gamma channel info the PNG when you save it

 

Not all image editors give you this level of control when you save a PNG, but I found a great little tool called TweakPNG (Windows-only) that lets you tweak the gamma channel (as well as the other chunks in a PNG file).   

Comments[0]

CSS Reset

If you do a lot of CSS work, you are probably familiar with the fact that every web browser has its default styles (and ever browser has different defaults).   This can make it difficult to format content consistently across browsers... unless you reset all of these defaults in your own style sheets.

 

Eric Meyer has an excellent Reset CSS Style sheet.   This will save you a ton of time.   :-)

Comments[0]

Interesting News in the Grails World

SpringSource acquired G2One, which means a lot of great stuff for Groovy/Grails.  You can read some stuff on the lead developer's blog here which also has links to official announcements, etc.

Comments[0]

Wisdom on Software Engineering

Robert Glass posted a great article on the IEEE online journal - Frequently Forgotten Fundamental Facts about Software Engineering.

 

Robert is also the authors of one of my favorite books, Facts and Fallacies of Software Engineering.   If you have not read this book yet, do it now!


 

 

Comments[0]

Java OnError option Rocks!

Hi there,

OK, so if you're like me your worst enemy is silent failure.  Things better just work or fail fast.  So I wanted to blog about my latest battle hardened tool: the Sun JVM "OnError" option.  This option has been around for quite a while, since JDK 1.5, but I thought it blog worthy none-the-less.

If the a fatal error (crash) occurs in the JVM, the scripts and/or commands that are specified in the "-XX:OnError" argument are executed.  So, in a production situation you can configure it to send you an email when it crashes with the error log information.  Absolutely Awesome!   Here is an example of how I configured it for a production install:

-XX:OnError="(echo 'FATAL APP1 Crash ' && cat hs_err_pid%p.log)|mail address1@domain.com,address2@domain.com"

This comes to mind because I just received an email informing me that one of our systems crashed.  It looked like this: crash_err_log.txt

Now on the other hand, you probably have monitoring software installed, with staff to maintain your production installs.  But if you like a little redundancy at little to no cost, this feature is great.

More information on this feature at :

"Troubleshooting Guide for Java SE 6 with HotSpot VM"
http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/TSG-VM.pdf
Section: "B.1.3 -XX:OnError=Option"

"Troubleshooting Guide for Java SE 5"
http://java.sun.com/j2se/1.5/pdf/jdk50_ts_guide.pdf
Section: "1.13.2 OnError Option"

Have a great one,
- Andres Galeano

Comments[0]

simplicity.equals(accessibility)

Craig Walls made a great post on how easy it is to build the Spring Framework from source code.

 

I tried it, and it works like a charm.   In under five minutes, I checked out the project and built the jars.   In a world of increasingly ridiculous complexity, it's refreshing (and inspiring) to see a project that really makes the build simple.    Kudos to these guys for doing it.    In fact, I think if more projects did this, it would invite more people to learn, explore, and participate.

 


Comments[0]

Hacking Google Chrome

I recently installed Google Chrome and I like it. However one thing has been bugging me and that is the way it does not let me save a password for a site, once I have blacklisted it with the 'Never for this site' button.

Today, with a little effort, I was able to figure out how to do it. The steps are below. 

  1. Download SQLite Database Browser from here.
  2. Close Google Chrome. If you try to make this change with the browser still open, not only will the change fail to take effect, it will hang the browser and you will have to kill it.
  3. Launch the 'SQLite Database Browser.exe', ignore the Security Warning, and click Run. Open the database located here: C:\Documents and Settings\{account}\Local Settings\Application Data\Google\Chrome\User Data\Default\Web Data
  4. Open the Browse Data tab, and open the 'logins' table. Scroll horizontally to the 'blacklisted_by_user' column.
  5. Find the row having a value of '1' in this column that you want to reset. Double-click on the row and change the value to 0, and click 'Apply Changes'.
  6. Save the database, and close the SQLite browsing window.
  7. Open Google Chrome, navigate to the site, and login. The 'Do you want Chrome to save your password?' bar will appear.

I agree, it is a pretty technical workaround.

Comments[0]

Chicago Recap Part Three: Why I feel strongly about Grails

Well, I feel compelled to talk about the third topic so shortly after writing my second recap entry on Groovy scripting.  A majority of the reason for me attending Chicago was not for Groovy (though I got a lot out of that), but looking for the answer to the age old question of "Why Grails?"  To me, I don't really need a huge reason, since it's quite fascinating to me and I'm happy with the "it's just easy" response.  But, because I'm a team player and used my time with Jeff Brown as a chance to answer everyone's questions including my own, I thought I'd find a better answer.

So, in a nutshell, I believe (and Jeff agreed) that Grails tends to get signed off on as a CRUD generating framework, because it's so easy to get a CRUD application off the ground.  Grails is an awesome compilation of technologies, and it's aim is to make generating all kinds of apps easier, while still maintaining its ability to do enterprise application.  I think this is in part to it being reliant on the Spring Framework, because a majority of the applications I see tauted as "enterprise" typically are founded on Spring.  I think the Grails team did an awesome job in founding the entire framework on Spring, and hooking into Spring's vast capabilities to leverage other enterprise-worthy frameworks (such as Hibernate). 

However, I think Grails is SO easy that it provides the illusion that it can't be used for enterprise development.  Also, I believe the absence of configuration files leads you to believe your stuck in a mold that you can't split from.  So, again, I questioned Jeff on such things, and he again delivered.  My question was focused on how to get to the nitty gritty Spring stuff, and how to tweak it if I need to.  Now I'll testify that in 90% of the applications I've worked on using Spring, I'll never have to tweak the configurations if they were built on Grails -- cause the default Grails-generated configuration is what I use anyway.  But, as a curious guy looking to boost my knowledge, it'd be nice to know for arguments sake.

First, there is the resource.groovy file.  Two nice features of this are -- it uses the Spring BeanBuilder in Groovy instead of XML, leaving you with clean, readable code for your beans.  And second, if I wasn't mistaken in Chicago, your beans will get injected anywhere the names match up (such as "emailBean" where you have a declaration of "def emailBean"). 

Second, and especially for writing plugins for your applications under Grails, there is a closure called something to the effect of "doWithSpring".  Here, anything that needs to be handled by Spring at boot up can be scripted here.  We didn't get a ton of time to touch on this, but with the upcoming book written by Graeme and Jeff, it's going to get mentioned.  I wait for it like a kid at Xmas. 

Besides those two custom hooks, I'd need use cases.  Do you have examples of where you need to get something super special that you're sure Grails doesn't have already out of the box?  Let me know, if I can't answer it, I'm sure Jeff (or anyone with the Grails team) can. For more on Grails and Spring, feel free to read the link here in their user documentation.

Some worthwhile mentions though before I sign off on this blog entry:  command objects, service classes, ajax tags, and the plugin system for Grails are a great read.  If you have a second and are bored, it's definitely worth a look at, and you may find some information there that answers your own questions about Grails. I'll definitely take time to touch on them some more in my future recap entries of Chicago.

So, I hope this validates my excitement on Grails.  I don't tend to get excited about frameworks that are only worthy of creating quick demo's for clients or consultants.  I really, truly believe that Grails is enterprise worthy, and it's abstraction of the Spring configuration really exposes how powerful and flexible the Spring framework really is.  It's hard to see that when you're busy writing configuration files for lots of beans, and after multiple crashes of Tomcat because of missed items, you finally get it working after some frustration.  Stripped away, Grails exposes Spring for all it's capabilities, while at the same time maintaining your capability to tweak the configuration.  In my opinion, that is worth the hour of down time to start a Grails application, and really get to play with it -- because you'd be surprised what an hour accomplishes using Groovy on Grails.


Comments[0]

Chicago Recap Part Two: Groovy Scripting Makes Life Easy

Upon my return to the office after my week learning Groovy and Grails, I've often been asked how it is that I began learning the "syntactical sugars" it offers.  So, I felt it would be beneficial to blog quickly on my experiences with Groovy in particular, and how I use it in my daily work tasks to make life easier. 

Groovy can be seen in two lights, at least the way I perceive it.  First, it can be a cooler Java, where all your *.groovy files are declared classes, extending objects or implementing interfaces, just with a lot less code and assumed defaults that you'd otherwise have to do yourself.  With getters and setters automatically generated, constructors having infinite permutations, and the ability to override them at any given point, it makes life pretty nice -- and keeps your classes looking simple and to the point.  

Secondly, and the focus of this article, is Groovy's ability to be used on the scripting front.  I have by and large (and Linux guys, don't kill me for this) replaced a majority of my bash scripts with Groovy scripts.  Obviously the only problem with such a method is that I have to have Groovy installed on my machine and the $GROOVY_HOME/bin folder as part of my path.  But, the lack of syntactical switching from my daily routines as a Java developer to creating convenience scripts that help in my daily administration duties has really boosted my performance on both fronts.  A task I usually have is maintaining data for an application that is by and large number-based.  From time to time, someone or something goes wrong to skew the numbers, and in the past has required anywhere from a half-hour to a whole day to repair.  Groovy, however, is useful in allowing me to create a 5 to 10 line script in most cases that automates the work, leaving me with more free time to do actual work rather then tech support or data entry.

By using Groovy as a scripting language, I've become much more familiar with it's advantages in the Java application forum, and continue to be a huge advocate to implementing it with our current projects.  I have a small "quick reference" chart with some common syntactical shortcuts that Groovy has, and hardly reference this anymore.  Groovy has borrowed a lot of concepts from languages like Perl, so anywhere I'd otherwise use Perl I've used Groovy.

It definitely is a decision you have to make and stick with.  Like any other language, there is some learning curve, but I will leave you with this thought:  If all else fails, write Java code.  Most of you reading this blog are Java developers, so writing straight Java code will be rather easy for you to do.  Then, when you have time to refactor and learn, take your Java code and trim it down to be a Groovier solution -- and write down or save the coding snippet for future reference.  Over time, you'll hopefully begin to retain these neat changes and shortcuts, and you'll find yourself hopefully wanting to write this way in your applications as well.

As always, if you need help -- I'm available.  Hopefully in my upcoming blog (Part 3), I'll cover a bit more on Grails and why I think it gets a leery response sometimes as an enterprise-worthy framework.

Comments[0]

Awesome Features that will make you LOVE Groovy

During the week of Aug 24th, I had a great opportunity to go to Chicago, IL for the week and take part in G2One's Groovy/Grails training session, taught by Jeff Brown.  Groovy/Grails has already taken hold of me as a developer, but this was an opportunity to ask a lot of low-level questions about both the language and the framework, and get a great answer by an expert.  At the end of the week, I felt justified in saying I believe Groovy and Grails both are definitely enterprise-worthy choices for development.

But, today I will not be writing about all of it in one huge blogpost.  Over the next week or so, I'll be taking time to write a blog post about a central idea that I found cool or important, in hopes to give myself space to spread the knowledge I learned.  With any luck, I won't be the only guy in the shop that gets excited about Groovy and Grails.  So, without further adu, I give you my first post:  Awesome Features that will make you LOVE Groovy

There could be a lot here, but I'm going to attempt to narrow this down to the following format:  introduce the item of coolness, give a couple sentances on why it's cool to me, and if applicable, a link to where you can read a bit more on it.  There is always asking me as well, but I definetly don't know everything, so I'll try and provide information written by an expert.

 1.)  Syntatical Shortcuts:  Groovy gives a lot of shortcuts and added helper methods that make the life of a Java developers life a LOT easier.  For example, a common item I use in Java is as follows:

String myVariable = (anotherVar != null ? anotherVar : "empty");

However, Groovy makes such a line a little easier to do.  Since nulls are evaulated as false in an if statement, we can use the following in place of the above to shorten the redundent typing a bit

String myVariable = (anotherVar ?: "empty")

Obviously declaring String in this case could be a 'def' declaration instead, but I wanted to portray my point. 

2.)  Language Additions on Objects:  This could turn into a HUGE list, but I'll touch on some of the convenience methods I use a little bit more frequently in Groovy.  The creator's of Groovy really did think of some of the methods that would be a great addition to the Java language, and using Closures in a lot of them, added some seriously powerful items to shorten your code up.  The example I'm thinking of is with Lists of data.  Typically, somewhere along the line, you'll want to keep the list in tact, but return a subset of the list based on some criteria.  In the past, I've written a separate function per filter I want to do, pass my existing List into the function, and return a filtered subset List object to use on the UI, or in the business logic, whatever might be the purpose.  Because of the code this can take, I will not put up the example Java code presented by Jeff in Chicago.  But, I will show you a use of the "findAll" method, which takes a closure and returns a subset of the list executed on.

Suppose I have a list of names, such as:

def names = ["Ted","Fred","Jed","Ned"]  //notice the shortcut to declare a new List :)

Now, lets say I need to take that list and return any name that is no more then three letters.  In Java, you'd have to declare a new empty List, iterate over the names list, check the current node, if it's less then or equal to three push it on the empty list, and once completed, return the new List object.  In Groovy, I would do the same logic, but with less code:

def shortNames = names.findAll{
it.size() <= 3
}

Simply explained, I call "findAll" on my names list, start a closure, for each node that's in the names list, it will get passed into the closure as the variable "it".  If the size of the current node is <= 3, it's "true", which tells the findAll method to push the node onto shortNames.  If it was false, it won't get put on shortNames.  Nice, clean, inline code -- this is a lot easier then jumping around to a separate function. 

Groovy has a lot more of these, some to look at are each, eachWithIndex, eachLine, the list goes on. 

3.)  Groovy has no checked Exceptions:  Now I haven't researched this a lot, but I guess I've fallen into this.  Exceptions typically that would prevent a build from occurring will not stop the Groovy class.  Checked exceptions are now all Runtime exceptions, and up to the developer to take care of.  try/catch blocks still work (along with most Java syntax), so you can care for exceptions as needed.  The reason for the change was briefly touched on, saying that the reason is because developers tend to just throw a try/catch around a possible exception in Java, without appropriately handling it.  So, when errors occur, there is no indicator as to what the true problem is, because the developer has left an empty catch block around the source.

4.)  == is the equivalent of calling .equals():  Now I typically didn't get burned by this in Java, and really only did by Strings as a beginner, but this is a pretty nice feature.  In hopes to keep everything the same, Groovy uses it's ability to do operator overloading, and overrides the == operator to call .equals() on the object at hand.  This keeps everything consistent as far as what to do at the if condition, and honestly makes things a little bit cleaner.

Now the question did come up at the training:  What if I do need to check the reference of two objects to see if they reference the same one?  Instead of doing ==, you can call .is() on the Object, like:

objectA.is(objectB) //does objectA reference the same item as objectB

For more reading on operator overloading, you can go to the Groovy site here.

5.)  Groovy supports almost all Java 5 features:  There are quite a few pro's with this item.  First and foremost for me, if I'm in a pinch and need to get code out the door, but don't know the Groovy way to write it, I simply write it like I would in a Java class, compile it and get it out the door.  Short of a couple insignificant differences (inner-classes is one), Java code will work and compile in a Groovy class.  This will flatten the learning curve for the Java developers trying out Groovy, and allow them to ease into the coolness of the Groovy language feature-set. 

The second pro that is nice here is that with Java 5 features, Groovy classes can be used with other enterprise frameworks, without the frameworks freaking out.  You can annotate your classes for JBoss Seam, run them with other Java classes annotated in a similar fashion, and the framework simply doesn't know it's got compiled Groovy classes running with it.  This allows you to continue with legacy applications running with enterprise frameworks, but still introduce Groovy code to the application -- uninterrupted.  BRILLIANT! 

And finally, remember this:  "Groovy is the sole alternative dynamic language for the JVM supporting annotations and generics."  JRuby, Jython, and the others all fall short of this support -- just another reason why Groovy is soooo cool.  More on this here.

6.)  Complete Ant integration and the groovyc command:  So, you're sold on using Groovy, but how can you integrate this into your application build without writing another task for compiling the Groovy files?  And what happens if you have a circular reference between a Java class and a Groovy class?  Well friend, I give you the groovyc command and Ant task. 

To simply include Groovy compilation to the existing Ant project you may have, you can do the following -- add the groovy-all JAR file (found in GROOVY_HOME) to your classpath, declare the use of the groovyc task (For a clearer look at this, read the groovyc page on Groovy's site here), and then use the task as specified in their manual.  Because it's already typed out for you (and I'm lazy), I'll again refer you to the Groovy site here for more detail on this item.

In conclusion, you can see that I've only hinted at some of the features I'm aware of and use often.  I can say that I've replaced Perl with Groovy on my Linux system, writing a lot of my command scripts with it.  It really has eliminated the back and forth lag that occurs when changing languages, and has helped me with getting tasks done quickly.

I honestly feel that, as a Java developer, despite what you've heard about Grails (since these two usually go hand in hand), you should spend some time checking out Groovy.  It's got a lot of features you wish you had in Java (even if you don't know it yet), and has kept things so easy that it's sometimes astonishing to think you wrote a major component in your application in half the time it previously would have taken. 

And, like Grails, Groovy has a very active modules library, which allows you to do anything under the sun for the most part.  The two plugs I'll put in here are for GroovyWS and Gant, but there are others.

Hope I didn't bore you too much, and email me your opinions on Groovy if you give it a shot.  I'm always willing to help spread the good word on Groovy!

Comments[0]

Avoiding Memory Leaks in JavaScript

I've been writing more JavaScript-heavy user interfaces lately, using frameworks like Ext, YUI, Prototype, etc.  As a result, I've been wondering about what potential JavaScript has for memory leaks.

The following provides a decent article on the topic:

    http://www-128.ibm.com/developerworks/web/library/wa-memleak/

The article makes the following points:

  • memory leaks occur when there is a circular reference between two objects because browsers like Firefox and IE do reference counting garbage collection.
    eg.
    var foo = {};  
    var bar = {};
    foo.bar = bar;
    bar.foo = foo; // memory leak
  •  One way to avoid the circular reference memory leak is to break the circular reference: eg.
    delete foo.bar;
  • closures are great, but are also great at hiding memory leaks:
         window.onload=function outerFunction(){
    var obj = document.getElementById("element");
    obj.onclick=function innerFunction(){
    alert("Hi! I will leak");
    };
    };
  • it's best to delete all references to dom objects in your javascript objects

Note that the circular reference problem is an issue for JavaScript-enabled browsers that do reference counting garbage collection.  Circular references are not a problem for Java.

In addition to circular references,  you need ot make sure you remove global references to your object. For example, if you are building a JavaScript widget toolkit, you might have a global array of all the widgets on the page. When you remove a widget from the page, make sure you remove the widget from the global array of widgets.  This is true of any language.

 

Comments[0]

Grails: Hooking to a Legacy Database

So it's been a while since I put in a "plug" for the Grails framework.  And, since I'll be receiving a boat load of information next week on Groovy and Grails, I thought I'd unload this food-for-thought to the programming community. 

I'm aware that Grails is always shown typically from a brand new, start-from-scratch project perspective.  You create your domain model, generate all your controllers and views, etc.  But, since I'm a true believer that Grails is the next generation of web application development, I thought I'd try to do what I thought would be really tough -- hook Grails to an application so old, it doesn't even use Hibernate 3.0!

Let me put up some background.  I support an application that, to say the least, has been migrated and drug through a lot of frameworks and technologies.  Some old persistence, Hibernate, a nasty mix of Javascript, JSP Scriplets and JSTL, and absolutely no hint of Spring.  It can be quite a pain to add new features to because it's almost a learning curve to remember the old way of doing things.  So, I thought it'd be the perfect project to challenge my biggest skeptisicm in Grails:  Hooking to a legacy database easily, without losing the power of GORM.

So, after reading snippets of blogs that had bits and pieces of what I needed, I set my stop watch and started.  The things I had at my disposal for this old project are:  old hbm.xml files for each entity, the POJO's with hibernate annotations that hook to the hbm.xml files, a soda and a dream.  I began by setting up a new Grails project with no tweaks of any kind. 

Next, with my referencing blog entry on one screen, code on another, I started on my journey.  So the Grails documentation speaks of using existing Hibernate mappings and using HibernateTools to reverse engineer a database to generate a hibernate.cfg.xml file that you drop in the Grails conf directory.  However, beyond that, there really is no explanation.  So, since I depend heavily on learning by trial and error, I decided to take my hbm.xml files and drop them in the grails-app/conf/hibernate directory.  Next, I needed to generate a hibernate.cfg.xml file -- which I created a small Groovy script that simply read all the filenames of the hbm.xml files in my hibernate directory, and created a list of <mapping resource="Foo.hbm.xml"> style entries in it. 

Great, so I had my "config" section set.  But, it would want POJO's, and I definetly wasn't going to follow my referenced blog post where the author handwrites a bunch of annotated domain classes to use with his hibernate configuration.  Remember, I'm trying to show how "fast" this is, not painful.  So, I did the next best thing, and JAR'd up the existing @hibernate annotated POJO's I had.  With that JAR, I dropped it in the Grails lib folder.  Awesome, now lets try and start this bad boy up.

I had some minor mapping conflicts (two to be specific, and they were with custom types declared in Hibernate), but after a minute of waiting for Grails to verify the database with all my configuration changes, it started.  Simply believing it couldn't be that simple, I created a dummy controller with a call to list out all the records I had in a rather large table of my database.  It worked, so I tried narrowing the list by using GORM's dynamic findAllBy* method.  That worked too.  I was simply stunned.  Total time to hook to my rather large, clunky, legacy application database -- fifteen minutes.  And all my dynamic methods for GORM still existed. 

So let me recap the process: drop hbm.xml config files in a folder, use a five line Groovy script to generate a simple hibernate.cfg.xml file to drop in the same folder, JAR up my existing POJO entity objects as a library dependency, and start up my application.  I guess it just goes to prove that Grails is not only useful for new rapid application development, but can also be useful for rapid application development on legacy applications.  Simply groovy!

Comments[0]

Nice Article on CSS Table Designs

For the CSS-impaired (like myself), here's a nice little article on how to do really nice table designs using CSS.

Comments[0]

Using Multiple Windows in Eclipse

Eclipse is a nice IDE that many of us use to develop Java apps.  Eclipse has many plug-ins to do various things such as source code control and database interactions.

Hopping between these different 'Eclipse Perspectives' can get cumbersome, so I thought I'd mention that Eclipse has a nice feature to open a perspective in it's own window.

You should try it.  While in a perspective, go to the Eclipse menu at the top and choose "Window" -> "New Window".  The perspective you're in will open in a new Eclipse work bench.

This is really great if you happen to have multiple monitors.  On one screen you can be authoring your code, and on the other screen you might be interfacing with the database, browsing CVS or monitoring your Find Bugs results.  Whatever perspectives you use most frequently.

The only thing to watch out for is to close them in the right order.  I believe the last one closed is the way eclipse will appear when you start it up next.

Comments[0]

Push Button documentation

There's a nice article on IBM Developer works that demonstrates how some tools can be used to generate documentation from your codebase systemically (rather than manually up-keeping it yourself).

 

Enjoy!


Comments[0]