[codecrate]2024-02-26T22:33:02+00:00https://codecrate.comMy No-Shame-November story2023-11-23T00:00:00+00:00https://codecrate.com/2023/11/my-no-shame-november-story<p>A long time ago, in a company far far away…I was an early developer at a <strong>non</strong>-tech company supporting internal business systems.</p>
<p>I loved being heads down…cranking out code and features. It was a flow that I tried to stay in as much as possible, and everything else was viewed as a “distraction” or waste.</p>
<p>I was developing a custom intranet web app, and supporting a very diverse set of users, and a non-zero percentage of them were non-technical.</p>
<p>I had one particular user who was vocal when things came up. In one particular instance, there was an issue that she raised up that I was absolutely confident was “User Error” (PEBCAK was my term of choice to talk down on others who didn’t understand the elegance of systems I was building).</p>
<p>After multiple rapid-fire back-and-forth emails to try and resolve this issue as quickly as possible and get back to “cranking out <strong>L33T</strong> code”, I took a screenshot of the screen that she was referring to, imported it into Microsoft Paint, and using a bright red pencil, circled the part of the page that had the feature she needed, and sent my last email to her with no text. Just the image. It looked like a six-year-old had scribbled on the page to highlight the area. A bit like this…</p>
<p><img src="/images/2023-11-23.png" alt="Oh the humanity..." /></p>
<p>A few minutes later, I had my “oh shit” realization. This wasn’t user error. It was a legit bug that I wasn’t reproducing locally. I can remember sinking down into my cubicle in shame realizing that this was 100% my fault. Fixing the bug took minutes, and I honestly can’t remember if I ever responded back to that member owning up to my mistake.</p>
<p>Talk about passive-aggressive. I could have picked up the phone. I could have walked over to her office to observe the behavior on her computer and not just assume it “Works for me”!</p>
<p>Although I’m not proud of my behavior in that instance, I am grateful for the experience; it taught me a great lesson in humility. Passing unit tests doesn’t mean that there aren’t bugs. It just means that I may not have caught a behavior. I believe it made me a better developer to be much more responsive to my customers’ feedback, and much more skeptical that I “got it right”.</p>
My innerwork journey with performance reviews2022-07-09T00:00:00+00:00https://codecrate.com/2022/07/performance-review-mindset-shift<p>A year ago, during our performance review cycle, I struggled to complete a written evaluation in less than four hours. Every single word I wrote was agonizingly written and rewritten as it felt like I was carving into a stone tablet of each person’s “Permanent Record”. This year, I had <strong>significantly</strong> more direct reports, and an upcoming work trip in Amsterdam overlapping when performance reviews were due. I was feeling stressed to put it mildly.</p>
<p>To get the ball rolling, I started building a lightweight primer with an inventory of highlight accomplishments for each team member during the review period. This helped remove some recency bias and refresh context of each team member’s holistic performance. It also had an unexpected <strong>negative</strong> side effect that put a whole lot of reviews into the “In progress” pile, and didn’t move any all the way to the “Done” pile.
<code class="language-plaintext highlighter-rouge">stress_level = stress_level + 1</code></p>
<p>Arriving in Amsterdam, I had a back-to-back schedule of meetings, and a list of recommended sights from co-workers. I <strong>REALLY</strong> wanted to tour some of the old city. As an American, anything older than 100 years is considered almost <strong>ancient</strong>, and being able to trace back architecture to the 1300’s, is ridiculously cool. The timeline for performance reviews was closing in, and as a motivational opportunity, I made a personal commitment: “No sight seeing until all the written performance reviews are Done”.</p>
<p>A few days pass with meetings plus jet lag equaling a fair amount of exhaustion. A bit more inventorying work done in the spare moments, but as the weekend rolled around, there were still no performance reviews “Done”. The clock continued to tick. I decided to go into the office on Saturday morning. Alone in the silence, with no meetings or interruptions, I set a new goal: “Stay in this office until the performance reviews are done”.</p>
<p>Was my goal even realistic? I was lacking a benchmark for how long each review was going to take. Would it be like last year clocking in at four hours for each one? Would I be locked in the office until my coworkers found me here Monday morning? To get past this hurdle, I kicked off using Pomodoro timeboxing to give me clear checkpoints for reflection on my progress.</p>
<p>Two pomodoro cycles later, my first review was complete. Woah! The rush of dopamine for moving my first review into “Done” was incredible! Now I had a benchmark of what I could accomplish, and reevaluated my plan. Approximately 1 hour per review was definately viable. Twelve more reviews over two days was within reach. Now, I could restructure my goal from “Do all the reviews right now” to: “Complete half of them today, and half of them tomorrow”. And even better: “finish 3 more this morning and then go across the street for some <strong>INCREDIBLE</strong> ramen! :)</p>
<p>The rest of the morning <strong>flew</strong> by. Three more reviews complete, lunch devoured, but my energy level was <strong>really</strong> low and the only antidote was a power-nap in the <strong>incredible</strong> built-in nap stations in the office. After waking up, I paused before diving back into the work and asked myself: What was my <strong>real</strong> goal? The productivity hacks from the morning were definitely <strong>effective</strong>, but what was the intended purpose of all this activity? I wrote out a <strong>BIG BOLD</strong> heading at the top of my document…</p>
<h2 id="my-objective-is-to-help-my-team-grow">My objective is to help my team <strong>grow</strong>.</h2>
<p>And then I added the following subheading:</p>
<blockquote>
<p>It’s not about me. It’s not about my fear and insecurities of saying something wrong. It’s about helping <strong>them</strong> achieve their full potential.</p>
</blockquote>
<p>After writing out those last few letters of the subheading, there was a literal light-switch moment where my mindset shifted and something “clicked” within me. Why had each review taken four hours last year? It was because I was afraid. Afraid I might say something wrong. My apprehension, hesitation, and procrastination, was rooted in fear. Seeing this statement written out triggered a very real cognitive dissonance between who I <strong>thought</strong> I was and how I was actually acting. The words of objective was compelling me to act differently. It wasn’t about being <strong>perfect</strong>. It was about doing everything in my power to help my colleagues grow.</p>
<p>From that moment on, whenever I flipped back to my document, those big words jumped off the page. Writing each performance review was no longer an <strong>obligation</strong>. It was actually what I <strong>wanted</strong> to do. It changed the job to be done from “I <strong>NEED</strong> to complete this performance review because HR is telling me to” to “I <strong>GET</strong> to help each of my team members grow as a person and professional”. Intrinsic motivation kicked in, and the the afternoon disappeared in a true flow experience.</p>
<p>After completing each written review, I was <strong>genuinely</strong> excited for upcoming conversations to share my observations with each team member. Even critical feedback had a different feeling. I wasn’t afraid to share critical feedback, instead, I was eager to share my observations, clarify my expectations of the role, and then co-create a growth plan to help that individual succeed moving forward. I felt honored to be a part of these moments for each person.</p>
<p>At the end my trip, I didn’t end up doing any sight seeing, but all of the performance reviews were complete. Was I upset or disappointed? Not at all. It was an opportunity for me to wrestle with my personal innerwork, and I came away feeling like a different person.</p>
<h2 id="reflection">Reflection</h2>
<p>It wasn’t long after my trip to Amsterdam that I picked up the <strong>highly</strong> recommended book: <a href="https://www.amazon.com/Atomic-Habits-Proven-Build-Break-ebook/dp/B07D23CFGR/ref=sr_1_1?keywords=atomic+habits&qid=1657545907&sr=8-1">Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones</a> by James Clear. The insights I had after reading this book inspired me to write this post as the struggles I experienced on my journey mapped so well to many of the practices mentioned in the book.</p>
<p>At the start of this process, I was attempting to make each performance review <strong>Attractive</strong> (The 2nd Law from Atomic Habits). I attempted using “Temptation bundling” to motivate myself to complete my tasks and allow me to get to do the “fun” activities like sightseeing. This was effective at helping me be incrementally more <strong>productive</strong>, but these productivity hacks fell short. The <strong>real</strong> unlock was when I realized that my behavior was not aligned with my desired intentions and identity. I don’t think I can say it any better than this quote from the book:</p>
<blockquote>
<p>Imagine changing just one word: You don’t “have” to. You “get” to. You get to wake up early for work. You get to make another sales call for your business. By simply changing one word, you shift the way you view each event.</p>
</blockquote>
Git eXcited2015-09-01T00:00:00+00:00https://codecrate.com/2015/09/git-excited<p>As a developer, <strong>optimizing your version control workflow is one of most valuable
productivity improvements you can make</strong>. It is one of the most
frequently used pieces of software used during your work day (second only to
your IDE), and incremental gains have huge long term pay off.</p>
<p>I have developed custom git extensions and workflows for a <strong>long</strong> time, and
it is amazing to see how much <a href="https://github.com/wireframe/gitx">the gitx project</a>
has evolved with literally <strong>years</strong> of refinements. At it’s heart, the gitx
project offers a set of utility git scripts (packaged within the git namespace)
to simplify and optimize common workflows such as:</p>
<ul>
<li>starting a new feature branch with latest version of master updating a</li>
<li>feature branch with the latest code that has been released to master</li>
<li>integrating a feature branch into a staging environment releasing a feature</li>
<li>branch to master</li>
</ul>
<p>Having these workflows packaged into single commands is a huge help for your
entire team to just “do the right thing” with no guesswork or opportunities for
error (ex: “I forgot to pull latest master before I started my feature branch
and now the merge conflicts are killing me!”😎)</p>
<p>The gitx project is optimized for continuous delivery workflows used within
many development teams, <em>but</em> it is flexible enough to support alternative
workflows as well (ex: iOS/Android projects, rubygems, etc). It also offers
tight integration with Github including auto creating pull request and
autolinking issues from commits.</p>
<p>And here’s a simple scenario to help get an idea of what the workflow may look
like:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git start fix-all-the-things
<span class="nv">$ </span><span class="c"># fix all the things and commit them to git as normal</span>
<span class="nv">$ </span>git integrate staging <span class="o">&&</span> <span class="nb">echo</span> <span class="s2">"Integrate into staging environment for QA"</span>
<span class="nv">$ </span>git release <span class="o">&&</span> <span class="nb">echo</span> <span class="s2">"Merge changes into master!"</span>
</code></pre></div></div>
<p><em>Git moving and build something awesome!</em></p>
Using pry-remote to debug within Vagrant VM2015-01-29T00:00:00+00:00https://codecrate.com/2015/01/pry-remote-with-vagrant<p><a href="https://www.vagrantup.com/">Vagrant</a> is awesome and an absolutely essential
part of every development environment. Running your application within a
vagrant virtual machine <strong>does</strong> introduce a few challenges though…</p>
<p>One particularly nasty issue I hit recently was trying to debug some code using
my favorite Ruby debugging tool, <a href="https://github.com/pry/pry">Pry</a>.</p>
<p>The issue was that my application was launched within the VM using a linux process
manager (Ubuntu upstart) which means that the process is forked into the
background and it is not possible to halt the process to start a debugging
session using the standard <code class="language-plaintext highlighter-rouge">binding.pry</code> call.</p>
<h2 id="pry-remote-to-the-rescue">Pry-remote to the rescue!</h2>
<p>Debugging background processes requires using the
<a href="https://github.com/Mon-Ouie/pry-remote">pry-remote</a> gem which
was designed for this exact usecase. All you need to do is
swap out the method calls from <code class="language-plaintext highlighter-rouge">binding.pry</code> to <code class="language-plaintext highlighter-rouge">binding.remote_pry</code> and when
your application server hits the debugger, connect to the background process using the
<code class="language-plaintext highlighter-rouge">pry-remote</code> command. <em>Voila!</em></p>
<h2 id="connecting-from-the-host-os">Connecting from the host OS</h2>
<p>Now, debugging the background application process is awesome, but there is one
gotcha with this setup…<strong>it only works from within the guest virtual
machine</strong>. That’s pretty annoying for me since I like to use my host OS for terminal
commands and tools.</p>
<p>Vagrant supports port-forwarding from the host OS to the guest, but that
doesn’t work in this case since the pry-remote gem is opening up a random port
each time the debugger is triggered.</p>
<p>To workaround this issue, I use this simple shell script that automates
connecting to the virtual machine and firing up pry-remote.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/bin/bash</span>
<span class="c"># connect to application within virtual machine to debug running process</span>
<span class="c"># binding.remote_pry should be used to trigger breakpoints</span>
vagrant ssh <span class="nt">-c</span> <span class="s1">'cd /vagrant && bundle exec pry-remote'</span>
</code></pre></div></div>
<p>This solution combines the awesomeness of debugging applications with pry with
the convenience of not needing to manually ssh into the virtual machine all the
time!</p>
Automatically prefix email subject with Rails env2015-01-08T00:00:00+00:00https://codecrate.com/2015/01/email-prefixer-release<p>One trick I’ve used across multiple projects to help manage
email overload is to add a standard subject prefix to all outgoing
emails that contains the specific application/service along with the
Rails env for non-production environments (ex: staging, demo, etc).</p>
<p>For example:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># subject for MyApp from staging
[MyApp STAGING] Forgot Password
# subject for MyApp from production
# Rails.env omitted to keep emails pretty for users
[MyApp] Forgot Password
</code></pre></div></div>
<p>This simple change makes it much easier easier to visually scan incoming
emails and even simpler to setup effective email filters. All good
things to reduce email overload.</p>
<h3 id="actionmailerinterceptor-to-the-rescue">ActionMailer::Interceptor to the rescue</h3>
<p>Rails 3.1 and above have a great feature that allow for intercepting
all outgoing email and optionally modifying the mail object before it is
delivered. I’ve used a <a href="https://coderwall.com/p/qtsxug/prefix-all-emails-with-application-name-and-rails-env">pretty simple interceptor</a>
across several projects to add a standard subject prefix and have been very happy with the results.</p>
<p>Now, after several iterations I have finally gotten around to
wrapping this behavior up into a standalone gem.</p>
<p>The <a href="https://github.com/wireframe/email_prefixer">email_prefixer gem</a>
encapsulates this functionality and is absolutely simple to get up and running.
Literally <code class="language-plaintext highlighter-rouge">bundle install</code> and your done.</p>
<h3 id="customizing-the-application-name">Customizing the application name</h3>
<p>The <code class="language-plaintext highlighter-rouge">email_prefixer</code> gem automatically infers the application name from the
Rails application class name, but this can be changed using a standard Rails config initializer.</p>
<p>For example:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># config/initializers/email_prefixer.rb</span>
<span class="no">EmailPrefixer</span><span class="p">.</span><span class="nf">configure</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>
<span class="n">config</span><span class="p">.</span><span class="nf">application_name</span> <span class="o">=</span> <span class="s1">'MyCompany'</span>
<span class="k">end</span>
</code></pre></div></div>
<h3 id="feedback-wanted">Feedback wanted</h3>
<p>Are there other customizations that would be useful? I’d love to hear
any feedback or suggestions for improvements!</p>
Best Practices: Testing Rails controllers with RSpec2014-11-17T00:00:00+00:00https://codecrate.com/2014/11/rspec-controllers-best-practices<p>Rails is primarily a web development framework and so it is natural that controllers are an integral aspect of your application. Controllers in Rails typically accept HTTP requests as their input and deliver back and HTTP response as output. This is a pretty important part of building web applications, and so unit testing your controllers should be one of the most fundamental parts of your testsuite. I’m a huge fan for RSpec for testing Rails applications, and I’ve found that although the rspec-rails gem is a great starting point, there is a general lack of best practices for how to properly unit test controllers.</p>
<h2 id="essential-assertions">Essential assertions</h2>
<p>Let’s start with the basics. <strong>What should you test?</strong> The output of Rails controllers is the HTTP response, and so it is <strong>essential</strong> that each controller action has tests that assert the core HTTP response properties. For example:</p>
<ul>
<li>What was the response status code?</li>
<li>What was the response content type?</li>
<li>Did the controller render the expected template?</li>
<li>Did the controller render the expected Rails layout?</li>
<li>Did the controller set any flash messages?</li>
<li>Was any information inserted or deleted from the session?</li>
<li>Did the controller redirect the user to a new URL?</li>
</ul>
<p>Luckily, most of these assertions are a one-liner thanks to the excellent <a href="https://github.com/thoughtbot/shoulda-matchers">shoulda-matchers gem</a>.</p>
<h2 id="structured-contexts">Structured contexts</h2>
<p>Using RSpec contexts effectively are a critical aspect of writing great controller specs. <a href="http://betterspecs.org/#describe">Betterspecs.org</a> does a good job providing the basics, and here are some additional tips that apply specifically to controller specs which will help make your tests <em>much</em> more expressive.</p>
<p><em>NOTE: The setup and assertion blocks (before/it) have been left blank as an exercise for the reader. The implementations should be very straightforward and were omitted to emphasize the structure/language used to scaffold the context blocks.</em></p>
<h4 id="input-permutations">Input permutations</h4>
<p>Create a new context for each set of <em>meaningful</em> inputs. Typically this is used for varying query parameters, but it also works well when you need to exercise code paths for HTTP session or header usage.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="s1">'GET #index'</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'when params[:filter_by] == first_name'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'filters results by first_name'</span>
<span class="k">end</span>
<span class="n">context</span> <span class="s1">'when params[:filter_by] == last_name'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'filters results by last_name'</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h4 id="valid-vs-invalid-params">Valid vs invalid params</h4>
<p>Same premise as the previous tip, but worth calling out since it is such a common usecase.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="s1">'POST #create'</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'with valid params'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'redirects to show page'</span>
<span class="k">end</span>
<span class="n">context</span> <span class="s1">'with invalid params'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'re-renders #new form'</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h4 id="authenticated-access">Authenticated access</h4>
<p>Use separate contexts for authenticated vs un-authenticated access.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="s1">'GET #index '</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'when user is logged in'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'renders the listing page'</span>
<span class="k">end</span>
<span class="n">context</span> <span class="s1">'when user is logged out'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'redirects to login page'</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h4 id="authorized-access">Authorized access</h4>
<p>Create a new context for each user role accessing the endpoint (ex: admin vs standard user).</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="s1">'GET #show'</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'as content owner'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'renders the permalink template'</span>
<span class="k">end</span>
<span class="n">context</span> <span class="s1">'as an admin'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'renders the permalink template'</span>
<span class="k">end</span>
<span class="n">context</span> <span class="s1">'as a guest user'</span> <span class="k">do</span>
<span class="n">it</span> <span class="s1">'displays access forbidden message'</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h4 id="avoid-nested-contexts">Avoid nested contexts</h4>
<p>Do not nest contexts in order to share common setup. Just don’t. <strong>Ever</strong>.</p>
<p><em>This deserves an entire blog post of its own and will be a topic of future discussion…</em></p>
<h2 id="controllers-should-render-templates">Controllers should render templates</h2>
<p>Now, here’s a gotcha with the RSpec-Rails integration. For some reason, the default RSpec-Rails configuration disables rendering of templates for controller specs. In my opinion, This is a very poor recommendation that leads to a false sense of security. I’ve seen this happen more than once where your controller tests will pass, your code coverage will be 100%, but like a HAML indentation issue will blow up in production. <strong>BOOM</strong>.</p>
<p>Rails controllers operate on HTTP requests and <strong>the response body is a critical part of it’s job</strong>. To fix this, make sure to enable the <code class="language-plaintext highlighter-rouge">render_views</code> setting in your rails_helper.rb file.
https://github.com/rspec/rspec-rails#controller-specs</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">RSpec</span><span class="p">.</span><span class="nf">configure</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>
<span class="n">config</span><span class="p">.</span><span class="nf">render_views</span>
<span class="k">end</span>
</code></pre></div></div>
<p>I <em>do</em> encourage the use of view specs when a view has conditional codepaths, and I also recommend using integration/request specs when it is necessary to test Rack middleware, but it is unnecessary to write these extra specs for every single controller action and view. Why force developers to write separate integration tests that duplicate over 90% of your standard controller spec when I can simply render the views within controller specs and be done with it? I’m all for separation of concerns, but this is a simple matter of pragmatism vs dogma.</p>
<p>And, if there was a way to <a href="https://github.com/colszowka/simplecov/issues/38">detect the code coverage of views</a>, I actually would enjoy having controllers not perform this rendering call and could rely entirely on view specs. That way, any unrendered code paths in views could be caught by continuous integration processes. Until that is possible, I find it much safer to enable rendering by default and allow for specific controllers to opt-out of rendering if necessary.</p>
<h2 id="complete-example">Complete example</h2>
<p>And here is a simple example for a controller action with structured contexts and the bare minimum expected assertions. Enjoy!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="no">PostsController</span> <span class="k">do</span>
<span class="n">describe</span> <span class="s1">'GET #index'</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'when user is logged in'</span> <span class="k">do</span>
<span class="n">with</span> <span class="ss">:user</span>
<span class="n">before</span> <span class="k">do</span>
<span class="n">sign_in</span> <span class="n">user</span>
<span class="n">get</span> <span class="ss">:index</span>
<span class="k">end</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">respond_with</span> <span class="ss">:ok</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">respond_with_content_type</span> <span class="ss">:html</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">render_with_layout</span> <span class="ss">:application</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">render_template</span> <span class="ss">:index</span> <span class="p">}</span>
<span class="k">end</span>
<span class="n">context</span> <span class="s1">'when user is logged out'</span> <span class="k">do</span>
<span class="n">before</span> <span class="k">do</span>
<span class="n">get</span> <span class="ss">:index</span>
<span class="k">end</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">redirect_to</span> <span class="n">new_session_path</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">set_the_flash</span><span class="p">(</span><span class="ss">:warning</span><span class="p">).</span><span class="nf">to</span><span class="p">(</span><span class="s1">'Please log in.'</span><span class="p">)</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">is_expected</span><span class="p">.</span><span class="nf">to</span> <span class="n">set_session</span><span class="p">(</span><span class="ss">:return_to</span><span class="p">).</span><span class="nf">to</span><span class="p">(</span><span class="n">posts_path</span><span class="p">)</span> <span class="p">}</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p><em>NOTE: the RSpec <code class="language-plaintext highlighter-rouge">with</code> helper method comes from the handy <a href="https://github.com/wireframe/factory_girl_rspec">factory_girl_rspec gem</a> and the <code class="language-plaintext highlighter-rouge">respond_with_content_type</code> matcher from the <a href="https://github.com/tinfoil/shoulda-kept-respond-with-content-type">shoulda-kept-respond-with-content-type gem</a>.</em></p>
Detect and Respect CSS Selector Limits2014-10-24T00:00:00+00:00https://codecrate.com/2014/10/detect-and-respect-css-selector-limits<blockquote>
<p>Old IE continues to cause the world pain…</p>
</blockquote>
<p>Incase you didn’t know, IE8 and IE9 are pretty horrible web browsers. They
have a <em>significant</em> flaw where they <a href="http://blogs.msdn.com/b/ieinternals/archive/2011/05/14/10164546.aspx">can not render webpages if a single stylesheet has more than 4095 selectors</a>.
This issue affects <em>all</em> Microsoft browsers until IE10. Wow.</p>
<p>Unfortunately, these terrible browsers <a href="http://gs.statcounter.com/#browser_version_partially_combined-ww-monthly-201309-201409"><em>still</em> represent over 8% of the worlds internet traffic</a>,
and may need to be supported for certain projects. So, what is the easiest
way to keep your site compatible with these old versions of IE without driving
you mad?</p>
<p>I’ve explored several tools to automate splitting a single large stylesheet
into smaller ones to avoid hitting this limit including <a href="http://blesscss.com/">blesscss</a>,
<a href="https://github.com/zweilove/css_splitter">css_splitter</a>, and <a href="https://gist.github.com/ChristianPeters/2398394">home rolled scripts</a>
but I haven’t found any of them to be a real home run. Each solution is
fairly complex in nature which makes sense given the problem at hand.
Unfortunately, that complexity also makes for painful debugging when things go
wrong. At the end of the day, I would prefer to simply be <em>notified</em> when
my CSS files breach the selector limit, and then fix the issue manually by
splitting the files into logically related files (ex: application styles vs
admin styles).</p>
<p>This is a great usecase for a unit tests and I recently released the <a href="https://github.com/wireframe/rspec-respect_selector_limit">rspec-respect_selector_limit gem</a>
which contains a reusable matcher for asserting that your stylesheets won’t
break old IE. It’s a simple tool to integrate into your existing Rspec
testsuite like so:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">it</span> <span class="s1">'ensures application.css does not break old IE'</span> <span class="k">do</span>
<span class="n">expect</span><span class="p">(</span><span class="s1">'application.css'</span><span class="p">).</span><span class="nf">to</span> <span class="n">respect_selector_limit</span>
<span class="k">end</span>
</code></pre></div></div>
<p>For applications that already have multiple stylesheets, the <code class="language-plaintext highlighter-rouge">rspec-respect_selector_limit</code>
gem has an additional helper to assert that <strong>all</strong> of your precompiled CSS files
meet the limitations of old IE.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">it</span> <span class="s1">'ensures all configured CSS files do not break old IE'</span> <span class="k">do</span>
<span class="n">expect</span><span class="p">(</span><span class="n">precompiled_css_files</span><span class="p">).</span><span class="nf">to</span> <span class="n">respect_selector_limit</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This is a simple solution that keeps me in control of when to split out new stylesheets,
and as always contributions are welcome!</p>
Bundler Updater Gem2014-10-01T00:00:00+00:00https://codecrate.com/2014/10/bundler-updater-gem<p class="text-center">
<img alt="If you bundle update your entire Gemfile, you're going to have a bad time." src="/images/bundle_update_bad_time.jpg" />
</p>
<p>On any reasonably sized production project, you should <strong>absolutely never</strong> update all outdated gems at once.
There are new versions of gems being released daily and each time you update your bundle, you’ll be pulling in changes (<em>and bugs</em>)
from your dependent gems along with all of their transitive dependencies. For example, on my current application, running
<code class="language-plaintext highlighter-rouge">bundle update</code> pulled in <strong>52 updated gems</strong>. Talk about a risky release!</p>
<p>To help mitigate the risks associated with blindly updating <strong>all</strong> of your gems, I wrote
<a href="https://gist.github.com/wireframe/3f7e431f0d63ddb381c0">a small Ruby script to only update a subset of gems at once</a>.
With this script, I can cherrypick a few related gems and release them in a smaller batch and feel <strong>much</strong> more confident about
what changed and what needs to be tested.</p>
<p>After using this script over the past year, I finally decided to wrap this utility into a reusable gem. Now, introducing the
<em>cleverly named</em> <a href="https://github.com/wireframe/bundler-updater">bundler-updater gem</a>! The bundler-updater gem will examine your
Gemfile for all outdated dependencies and then interactively prompt you for which gems you would like to update.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>bundler-updater
<span class="o">></span> Update my_gem from 0.0.1 to 0.0.2? <span class="o">(</span>y/n<span class="o">)</span> y
<span class="o">></span> Update another_gem from 1.0.0 to 2.0.0? <span class="o">(</span>y/n<span class="o">)</span> n
<span class="o">></span>
<span class="o">></span> Updating my_gem...
</code></pre></div></div>
<p>It’s simple and a <em>huge</em> timesaver compared to manually running <code class="language-plaintext highlighter-rouge">bundle update each_individual_gem</code> over and over again.
Drop me a line if you find it useful or if you have any suggestions!</p>
<p>NOTE: It’s usually quite safe to bulk update non-production/test dependencies and it would be a nice enhancement for the bundler-updater
gem to support updating all gems a specified bundler group.</p>
<p><span class="text-muted">#patcheswelcome</span></p>
Using Rails Migrations to Manipulate Data2014-09-29T00:00:00+00:00https://codecrate.com/2014/09/using-rails-migrations-to-manipulate-data<p><a href="http://guides.rubyonrails.org/migrations.html">Rails migrations</a> were originally designed for manipulating <strong>database schemas</strong>. Adding tables, columns and indexes are all usecases that are incredibly well supported and even supports more advanced features like rolling back to previous schema state. Manipulating <strong>production data</strong> is also a common occurrence for developers, but how do you do that in Rails?</p>
<p>Importing data from flat files, updating records, and cleaning up records in a bad state are regular events. Many developers would tackle these tasks by popping up the Rails console on a production server and manually running a few commands to take care of business. You can accomplish all of these tasks using Rails migrations which is <strong>significantly</strong> less risky than giving every developer direct access to your database to <a href="http://codingsanctum.com/wp-content/uploads/2011/11/doitlive.jpg">run one-off scripts live on your production data</a>. Using migrations also provides easy access to feature branch code reviews and even <a href="http://blog.carbonfive.com/2011/01/27/start-testing-your-migrations-right-now/">unit testing</a>.</p>
<p>Here are a few protips I recommend when building your Rails data migrations:</p>
<h2 id="log-all-the-things">Log all the things</h2>
<p>Many schema migrations have a clear path for reverting if anything goes wrong, but data migrations are <strong>much</strong> more challenging to revert. It is absolutely <strong>essential</strong> for your migrations to provide as much debug information as possible for if/when anything goes wrong.</p>
<p>Here’s a simple example that highlights using the <a href="http://rails-bestpractices.com/posts/46-use-say-and-say_with_time-in-migrations-to-make-a-useful-migration-log"><code class="language-plaintext highlighter-rouge">say_with_time</code> helper</a> for auditing how long a migration step took and how many records were affected. <strong>Make sure to return the number of affected rows within the block</strong>!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">UpdateInvalidUsers</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span>
<span class="k">def</span> <span class="nf">up</span>
<span class="n">say_with_time</span> <span class="s2">"Updating invalid users..."</span> <span class="k">do</span>
<span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>
<span class="no">User</span><span class="p">.</span><span class="nf">find_each</span> <span class="k">do</span> <span class="o">|</span><span class="n">user</span><span class="o">|</span>
<span class="n">say</span> <span class="s2">"Updating user: </span><span class="si">#{</span><span class="n">user</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">"</span>
<span class="n">user</span><span class="p">.</span><span class="nf">update!</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'valid'</span><span class="p">)</span>
<span class="n">count</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="n">count</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h2 id="audit-state-pre-and-post-execution">Audit state pre and post execution</h2>
<p>Logging <em>during</em> execution of a migration is simple enough, and it’s also very helpful to log information before execution about the current state of the system. For example, logging the number of invalid records <strong>before</strong> the migration begins is a great data point.</p>
<p>A good data migration should also assert that the operation completed successfully and raise an error if something did not complete as expected.</p>
<p>Taking our previous example, here is an expanded version that adds in simple pre and post execution logging plus assertions.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">UpdateInvalidUsers</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span>
<span class="k">def</span> <span class="nf">up</span>
<span class="n">say</span> <span class="s2">"Found </span><span class="si">#{</span><span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'invalid'</span><span class="p">).</span><span class="nf">count</span><span class="si">}</span><span class="s2"> invalid records"</span>
<span class="n">say_with_time</span> <span class="s2">"Updating invalid users..."</span> <span class="k">do</span>
<span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>
<span class="no">User</span><span class="p">.</span><span class="nf">find_each</span> <span class="k">do</span> <span class="o">|</span><span class="n">user</span><span class="o">|</span>
<span class="n">say</span> <span class="s2">"Updating user: </span><span class="si">#{</span><span class="n">user</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">"</span>
<span class="n">user</span><span class="p">.</span><span class="nf">update!</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'valid'</span><span class="p">)</span>
<span class="n">count</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="n">count</span>
<span class="k">end</span>
<span class="n">invalid_count</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'invalid'</span><span class="p">).</span><span class="nf">count</span>
<span class="nb">fail</span> <span class="s2">"Found </span><span class="si">#{</span><span class="n">invalid_count</span><span class="si">}</span><span class="s2"> invalid records"</span> <span class="k">unless</span> <span class="n">invalid_count</span> <span class="o">==</span> <span class="mi">0</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h2 id="re-runnable-by-default">Re-runnable by default</h2>
<p>If a data migration raises an error, what should you do? Data migrations <strong>should be designed to be re-runnable</strong> and if any errors occur, Rails will automatically rerun your migration the next time you run <code class="language-plaintext highlighter-rouge">rake db:migrate</code>.</p>
<p>It’s also a good idea to <a href="http://guides.rubyonrails.org/migrations.html#using-models-in-your-migrations">define inner classes within your migration that shadow your application models and use <code class="language-plaintext highlighter-rouge">reset_column_information</code> to ensure your migration has access to the latest version of the model’s schema</a>.</p>
<p>Let’s take one last look at this example and make sure that the migration is re-runnable and doesn’t update records that have already been fixed.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">UpdateInvalidUsers</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span>
<span class="k">def</span> <span class="nf">up</span>
<span class="n">say</span> <span class="s2">"Found </span><span class="si">#{</span><span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'invalid'</span><span class="p">).</span><span class="nf">count</span><span class="si">}</span><span class="s2"> invalid records"</span>
<span class="n">say_with_time</span> <span class="s2">"Updating invalid users..."</span> <span class="k">do</span>
<span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># NOTE: only lookup invalid records that have *not* been migrated</span>
<span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'invalid'</span><span class="p">).</span><span class="nf">find_each</span> <span class="k">do</span> <span class="o">|</span><span class="n">user</span><span class="o">|</span>
<span class="n">say</span> <span class="s2">"Updating user: </span><span class="si">#{</span><span class="n">user</span><span class="p">.</span><span class="nf">id</span><span class="si">}</span><span class="s2">"</span>
<span class="n">user</span><span class="p">.</span><span class="nf">update!</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'valid'</span><span class="p">)</span>
<span class="n">count</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="n">count</span>
<span class="k">end</span>
<span class="n">invalid_count</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">status: </span><span class="s1">'invalid'</span><span class="p">).</span><span class="nf">count</span>
<span class="nb">fail</span> <span class="s2">"Found </span><span class="si">#{</span><span class="n">invalid_count</span><span class="si">}</span><span class="s2"> invalid records"</span> <span class="k">unless</span> <span class="n">invalid_count</span> <span class="o">==</span> <span class="mi">0</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>With these fundamental techniques under your belt, you can take your data migrations to the next level and even explore additional tools like <a href="http://railsguides.net/change-data-in-migrations-like-a-boss/">the migration_data gem</a> that make Rails migrations <strong>even</strong> easier.</p>
Optimized Development Workflow2014-09-10T00:00:00+00:00https://codecrate.com/2014/09/optimized-development-workflow<p>Over the years, I have worked to define and refine a software
development process that worked for me and my teams. It needed to be simple,
flexible and agile yet uncompromising in a set of fundamental principles.</p>
<p>I started off using <a href="http://nvie.com/posts/a-successful-git-branching-model/">the Git Flow process</a>
but it didn’t take long to realize that the Git Flow process was not meant for
our team. It was <a href="http://www.frenck.nl/2012/11/git-flow-never-heard-of-it-good-you-don.html">simply too complex</a>
and not optimized for delivering SaaS software. Every part of Git Flow
reeks of waterfall development and desktop software release cycles.</p>
<p>I wanted something <em>similar</em> to Git Flow, but <em>simpler</em>. I wanted a process
that accurately modeled how we were using continuous integration and continuous
deployment methodologies.</p>
<h2 id="the-basic-building-blocks">The Basic Building Blocks</h2>
<h4 id="master-branch--production-environment">Master branch == Production environment</h4>
<p>Straightforward and simple. Continuous integration and continuous deployment
take care of building all code checked into master, validating all tests pass,
and automatically deploying to production. Continuous integration also will
create a unique tag in git for each release.</p>
<h4 id="all-development-is-done-on-feature-branches">All development is done on feature branches</h4>
<p>No shockers here. This has been a best practice in software development for
a long time and git makes this stunningly easy.</p>
<h4 id="staging-branch--staging-environment">Staging branch == Staging environment</h4>
<p>How do you test your feature branch in a non-production environment? This is
where things get interesting. The staging branch is what I call an
<strong>aggregate branch</strong>. It represents a clone of the master branch with one or
more feature branches merged into it.</p>
<p>The staging branch can potentially have multiple feature branches in QA state
at the same time, but each feature can be released independently by merging
the associated feature branch into master.</p>
<p>I know what you’re thinking…this won’t scale to large teams, but I’ve personally
used this flow with a team of 25 developers and not had any issues other than
the occasional merge conflict. Not coincidentally, this workflow encourages
developers to be aware of potential merge conflict “hot spots” and leads to
better designed code as a result (ex: using small config/initializers instead
of lumping all configuration into application.rb)</p>
<p>And if the staging branch gets into a bad state, no worries. We have a simple
way to <code class="language-plaintext highlighter-rouge">nuke</code> any aggregate branch back to a known good state using git tags
that are created via continuous integration.</p>
<h4 id="peer-review-with-pull-requests">Peer Review with Pull Requests</h4>
<p>Github pull requests are incredible to facilitate discussion for feature branches.
It is a transparent way for team members to review each others code and a convenient
way for stakeholders to see what’s going on in a project.</p>
<h4 id="continuous-integration-and-continuous-deployment">Continuous Integration and Continuous Deployment</h4>
<p><a href="/2014/05/day-one-rails-continuous-integration.html">Continuous integration and continuous deployment need to be included from day
one</a>. These systems are the orchestration layer that perform all the heavy
lifting of validating and deploying each set of changes.</p>
<h2 id="example-workflow">Example Workflow</h2>
<h3 id="create-feature-branch">Create feature branch</h3>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git start my-feature-branch
</code></pre></div></div>
<h3 id="test-feature-branch-in-qastaging-environment">Test feature branch in QA/staging environment</h3>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git integrate staging
</code></pre></div></div>
<h3 id="create-github-pull-request-to-review-changes">Create Github pull request to review changes</h3>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git review
</code></pre></div></div>
<h3 id="release-feature-branch">Release feature branch</h3>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git release
</code></pre></div></div>
<p>And here is <a href="https://docs.google.com/presentation/d/1euOiki_e4OQ4jymGhS-o3xcET8-KZhDONUolDlOVT30/edit?usp=sharing">a presentation to help visualize the whole process</a>.</p>
<iframe src="https://docs.google.com/presentation/d/1euOiki_e4OQ4jymGhS-o3xcET8-KZhDONUolDlOVT30/embed?start=false&loop=false&delayms=60000" frameborder="0" width="480" height="389" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
<h2 id="thegarage-gitx-gem">TheGarage-GitX Gem</h2>
<p>Optimizing the command line experience for developers (and designers) has been
critical to the success of this workflow. We built <a href="https://github.com/thegarage/thegarage-gitx">TheGarage-GitX Ruby gem</a>
to inject custom commands into the Git namespace and streamline the process
as much as possible.</p>
<p>The beauty of this approach is that there is absolutely <strong>no magic</strong>.
TheGarage-GitX gem is nothing more than a set of helpful git aliases that
run a series of standard git operations with a single command. You can see the
actual git commands it runs during each step and even avoid using the shortcuts
entirely if you are comfortable with the overall flow.</p>
<h2 id="contributingmd">CONTRIBUTING.md</h2>
<p>Want to help new developers get up to speed on your development workflow? Just
create a CONTRIBUTING.md file in your Github repository and developers will
automatically see the document <a href="https://github.com/blog/1184-contributing-guidelines">any time they create a pull request</a>.
Github makes the lives of developers oh-so-nice.</p>
<p>I’ve found the CONTRIBUTING.md file to be a great place to document the
entire development workflow and walk developers through the process step by step.</p>
<p>Here is the <a href="https://github.com/thegarage/thegarage-template/blob/master/files/CONTRIBUTING.md">CONTRIBUTING.md template</a>
I use by default for all new projects.</p>
<p>This workflow was designed and optimized for teams building
SaaS products but I have even applied this framework to opensource project
development with minimal variation.</p>
Startup Words of Wisdom2014-09-08T00:00:00+00:00https://codecrate.com/2014/09/startup-words-of-wisdom<p>When I began working at a startup, I remember feeling overwhelmed by
the sense of responsibility. I was <em>trusted</em> and <em>empowered</em> to make a
difference. Every contribution had potential to make a huge impact on such
a small company. Talk about pressure.</p>
<p>Over the years, I have found these words of wisdom to be a useful tool for
improving my perspective at work and helping onboard new startup engineers.</p>
<blockquote>
<p>“It is better to beg forgiveness, than ask permission.”
<a href="http://www.goodreads.com/quotes/9453-it-is-better-to-beg-forgiveness-than-ask-permission">Grace Murray Hopper</a></p>
</blockquote>
<p>This quote was shared with me by an amazing mentor and it dramatically changed
the way I work.</p>
<p>In a startup, you can’t rely on your peers or superiors to officially sanction
and bless <em>every</em> aspect of your work. As an employee in a startup, you are
implicitly trusted to <strong>do your job and do it well</strong>.</p>
<p>Be transparent with the work you do and do <em>not</em> wait for someone else to create
a TODO list for you.</p>
<blockquote>
<p>“Talk may be cheap, but sometimes delays can be more costly than shipping
something broken.”
Me</p>
</blockquote>
<p>The more time you’re talking, the less time you are coding.</p>
<p>If you <em>need</em> to have a meeting to make a decision, build a tangible
prototype first. With a minimal investment of time, you can avoid the design by
committee scenarios and focus the discussion on “what is needed to
ship this <strong>real</strong> thing to production as soon as possible”.</p>
<p>These throwaway code prototypes are extremely cheap to create and share with
coworkers thanks to tools like <a href="http://gitscm.org">git for version control</a> and
<a href="http://git-scm.com/">ngrok to share local development environments</a>.</p>
<blockquote>
<p>“Perfect is the enemy of good”
<a href="http://en.wikipedia.org/wiki/Perfect_is_the_enemy_of_good">Voltaire</a></p>
</blockquote>
<p>It is very common for new engineers to have some anxiety releasing changes to
production fearing they may have overlooked something or may unexpectedly break
something.</p>
<p>Engineering at a startup is fast paced, and when you are required
to wear all the hats, it’s easy to feel like you’ve overlooked something. But
given the limits of time and available QA resources, <strong>you must be
comfortable with the risk of the unknown</strong>.</p>
<p>Balancing ideal state and functional state is tricky and the best advice is to
<em>document</em> a list of laundry items for your team to ensure you have visibility
into tasks that can be revisited at a later point.</p>
<blockquote>
<p>“It is better to be wrong than undecided.”
Me</p>
</blockquote>
<p>Bugs <strong>will</strong> happen and you <strong>will</strong> overlook edge cases. It’s just a fact
of life in a startup.</p>
<p>Shipping <strong>known functional code with unknown bugs</strong> still provides immense
value to the company. At least you are learning something! Keep your focus
on <strong>how to mitigate and minimize risk of said bugs</strong>.</p>
<p>Leverage automated systems for monitoring, notifications and continuous
integration systems to help you keep your sanity and ensure that when problems
<em>do</em> arise, you can <strong>detect and fix issues quickly</strong>.</p>
<blockquote>
<p>“If you aren’t sure which way to do something, do it both ways and see which
works better.”
<a href="http://www.brainyquote.com/quotes/quotes/j/johncarmac181820.html">John Carmack</a></p>
</blockquote>
<p>Always be open to experimentation and use data to make objective decisions for
you instead of just listening to the loudest person in the room.</p>
<p>Develop a strong analytics foundation including A/B split testing and put it
into practice throughout your daily programming practice.
your codebase.</p>
<blockquote>
<p>“Time is a startups most scarce resource. You never have enough of it. Invest
it only in things that matter.”
Me</p>
</blockquote>
<p>At the end of the day, all of these quotes are restating a common theme:
<strong>Avoid bottlenecks and focus on delivering real value in your job</strong>.</p>
<p>Good luck to all you engineers out there! Drop me a line with the quotes that
have inspired you!</p>
The Toolbox Bundler Group2014-06-04T00:00:00+00:00https://codecrate.com/2014/06/toolbox-bundler-group<p>There are many Ruby gems that provide commandline interfaces that are useful for development tasks.
<a href="http://github.com/thegarage/thegarage-gitx">The Garage Git eXtensions gem</a> is a good example of a CLI
application that adds additional Git subcommands for common development workflows and there are numerous
other gems that provide functionality ranging from
<a href="https://github.com/travis-ci/travis.rb">interacting with third party services</a> to
<a href="https://github.com/copiousfreetime/launchy">simplifying tedious jobs</a>.</p>
<h3 id="the-easy-button">The Easy Button</h3>
<p><a href="http://bundler.io/">Bundler</a> makes distribution of these utility gems to your entire team super easy
by just adding a few lines to your Gemfile. All your developers will have access to the tools they need
right out of the box, and you have a simple way to rollout new gem versions over time as well.</p>
<p>Since these gems are primarily developer utilities, you <strong>may</strong> be tempted to save these gems in
your <code class="language-plaintext highlighter-rouge">:development</code> Bundler group…but <strong>STOP</strong>!</p>
<p><strong>These are tools…not libraries!</strong></p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">group</span> <span class="ss">:development</span> <span class="k">do</span>
<span class="c1"># FIXME!</span>
<span class="c1"># This actually loads thegarage/gitx.rb source</span>
<span class="c1"># into your application runtime</span>
<span class="n">gem</span> <span class="s2">"thegarage-gitx"</span>
<span class="k">end</span>
</code></pre></div></div>
<p>By default, every gem declared in the <code class="language-plaintext highlighter-rouge">:development</code> group is <strong>automatically loaded
during application initialization which means that all Ruby files within those gems
will be included into your application</strong>. Not only does this bloat your
application’s runtime environment, but it also has potential for nasty and unexpected
side-effects when the gem’s CLI source code, monkeypatches, and all dependency gems
are loaded into your running application. This is so bad that some CLI gems have
started to <a href="https://github.com/ddollar/foreman/commit/fe0d953a2858e2cddacc9a3aa54935d170caceda">recommend against including the gem in your Bundler Gemfile</a>.</p>
<p>Can we get the benefits of simplified cross team distribution of the toolset
gems provided by Bundler <em>and</em> avoid polluting our Ruby runtime environment
with the code from these gems?</p>
<p><em>Of course we can!</em></p>
<h3 id="bundler-require-flag">Bundler :require Flag</h3>
<p>Bundler actually supports the ability to opt-out of the auto-loading behavior by passing
<a href="http://bundler.io/v1.6/gemfile.html">an optional <code class="language-plaintext highlighter-rouge">require: false</code> flag for any gem in your Gemfile</a>.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">group</span> <span class="ss">:development</span> <span class="k">do</span>
<span class="n">gem</span> <span class="s2">"thegarage-gitx"</span><span class="p">,</span> <span class="ss">require: </span><span class="kp">false</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This solves the immediate issue, but it is quite a manual process to add this option to every gem.
As your project grows, it is also quite easy to overlook the optional flag and accidentally
add a new gem that will get included into your runtime. Any other options?</p>
<h3 id="the-toolbox-bundler-group">The :toolbox Bundler Group</h3>
<p><a href="/2012/05/bundler-nirvana-with-custom-groups.html">Custom Bundler groups are an extremely effective way to group related gems into unique buckets</a>.
Let’s create a new custom group and shove all of these gems into an aptly named <code class="language-plaintext highlighter-rouge">:toolbox</code> group.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">group</span> <span class="ss">:toolbox</span> <span class="k">do</span>
<span class="n">gem</span> <span class="s2">"thegarage-gitx"</span>
<span class="n">gem</span> <span class="s2">"bundler-reorganizer"</span>
<span class="n">gem</span> <span class="s2">"foreman"</span>
<span class="n">gem</span> <span class="s2">"travis"</span>
<span class="k">end</span>
</code></pre></div></div>
<p><em>Perfect!</em> <a href="http://bundler.io/v1.6/groups.html">Bundler only loads a set of known groups</a>
into the running application, so any gem listed in the <code class="language-plaintext highlighter-rouge">:toolbox</code> Bundler group will
<strong>not</strong> be automatically loaded during Rails startup. We <strong>also</strong> have an
expressively named set of gems that is easily identifiable for future additions!</p>
<p>NOTE: You can <em>actually</em> give your <code class="language-plaintext highlighter-rouge">:toolbox</code> group any name that you see fit as long as it is
<strong>not</strong> one of <a href="http://bundler.io/v1.6/groups.html">the default groups loaded by Bundler</a>.</p>
<h3 id="optional-exclude-gems-from-production-deployments">[optional] Exclude Gems From Production Deployments</h3>
<p>Since these toolbox gems are primarily used for development purposes, you may
want to exclude these gems from being installed on production machines.
<a href="http://bundler.io/v1.6/groups.html">Bundler makes this process very straightforward</a>
via the <code class="language-plaintext highlighter-rouge">bundle install --without</code> command or the <code class="language-plaintext highlighter-rouge">BUNDLE_WITHOUT</code> environment
variable. Production deployments typically exclude the <code class="language-plaintext highlighter-rouge">development</code> and <code class="language-plaintext highlighter-rouge">test</code>
groups by default, so you just need to add the <code class="language-plaintext highlighter-rouge">toolbox</code> group to the list as well.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">export </span><span class="nv">BUNDLE_WITHOUT</span><span class="o">=</span><span class="s2">"development:test:toolbox"</span>
</code></pre></div></div>
<p>If you’re deploying to Heroku, <a href="https://devcenter.heroku.com/articles/bundler">checkout their documentation for configuring environmental variables</a>.</p>
Continuous Integration for Rails Apps from Day One2014-05-22T00:00:00+00:00https://codecrate.com/2014/05/day-one-rails-continuous-integration<p>One of the most valuable tasks every project should complete on their first
day is to define their continuous integration process. <a href="http://martinfowler.com/articles/continuousIntegration.html">Continuous integration</a>
has become such an essential part of modern day software development that having
a continuous integration strategy on <strong>Day One</strong> establishes the automation
infrastructure necessary to scale as your project and team grow.</p>
<p>Many Rails applications consider running <code class="language-plaintext highlighter-rouge">rake spec</code> the definition of
a continuous integration process and although it’s a good start, continuous
integration is about more than unit/integration tests.</p>
<p>The ultimate goal of a continuous integration test suite is to <strong>ensure the
project is in a good state before being released to customers</strong>.</p>
<p>Now, The actual definition of <em>“good state”</em> is specific to each project/team,
but at a high level, your continuous integration process will be <strong>automating
as many checks and balances necessary to feel confident that you are releasing
good code</strong>.</p>
<p class="text-center">
<img src="/images/automate_all_the_things.jpg" alt="Automate all the Things" />
</p>
<h2 id="the-basics-test-suite">The Basics (Test suite)</h2>
<p>Here are the basic structure I’ve developed and use for new projects to
kickoff their continuous integration process on the right foot…</p>
<p>First off, your continuous integration process <strong>needs</strong> to make sure your
test suite passes. Pick your framework (<a href="http://rspec.info/">RSpec</a>,
<a href="http://jasmine.github.io/">Jasmine</a>, etc), and use tools they provide.
Nothing fancy is necessary. If the tests aren’t green, go back to square one.</p>
<p>If the tests pass, that’s great <strong>BUT</strong> a project with zero tests <em>technically</em>
qualifies as a successful build. So adding a test coverage check is
<strong>extremely</strong> useful to ensure your code has an <strong>adequate level of testing</strong>
in place. Test coverage is apparently <a href="http://www.confreaks.com/videos/3315-railsconf-keynote-writing-software">a controversial topic now</a>,
but I have found adding test coverage checks to be extremely valuable for catching
untested code paths and in raising confidence that you are shipping “good code”.</p>
<p><a href="https://github.com/colszowka/simplecov">Simplecov</a> is very straightforward
to integrate into a continuous integration suite, and I recommend <strong>95%+ test
coverage as a good starting point</strong>.</p>
<h2 id="best-practices-styleguide">Best Practices (Styleguide)</h2>
<p>Every developer has their own coding style, and <a href="http://www.smashingmagazine.com/2012/10/25/why-coding-style-matters/">every project should have a set
of accepted principles for collaborating in a single codebase in order to write maintainable software</a>.
Most <a href="https://github.com/bbatsov/ruby-style-guide">development</a>
<a href="https://github.com/airbnb/javascript">communities</a> have codified their
best practices which provide an excellent baseline for your team to get started.</p>
<p>Establishing a coding style guide for your team on Day One saves you a
<strong>significant</strong> amount of time versus trying to retro fit a set of best
practices later on in the project development lifecycle. As your team grows,
having a style guide in place makes it that much easier to onboard a new developer
and ensure that new code is written inline with existing conventions. Sure, you
<strong>could</strong> just encourage best practices via a static style guide document, but
who would read it? Who would maintain it? Who would <strong>enforce it</strong>?</p>
<p>Javascript, Ruby, CSS linting libraries are readily available (<a href="https://github.com/bbatsov/rubocop">Rubocop</a>,
<a href="http://jshint.com/">JSHint</a>, etc) to automate this menial task and enforce your
codebase is adhering to the best practices defined by your team. My recommendation
is to <strong>start Day One with the basic out-of-the-box best practices, and tweak your
ruleset overtime as exceptions arise</strong>. It get’s you up and running quickly and
sets the foundation for incremental changes as the need arises.</p>
<p>Another benefit of automating this task is that it removes the burden during the
code review process from being “human syntax checkers” to focusing on the
bigger picture issues (architecture, modeling, API design, etc).</p>
<h2 id="sanity-checks">Sanity Checks</h2>
<p><a href="http://brakemanscanner.org/">Brakeman</a> and <a href="https://github.com/rubysec/bundler-audit">BundlerAudit</a>
are two great tools to plug into your continuous integration process as an
extra level of defense to ensure known vulnerabilities do not get released to
production. They both run quickly and are worthwhile investments to include
in your continuous integration process.</p>
<p>The goal is not to perform a full penetration test
or security audit of the system. It is to give you <strong>an increased confidence</strong>
that you are shipping “good code”.</p>
<h2 id="optional-project-reportsmetrics">[optional] Project Reports/Metrics</h2>
<p>Some teams benefit from having a standard set of reports generated
with every continuous integration run. These reports <strong>should not</strong> fail
the build and their objective is simply to <strong>get relevant information
in front of developers to motivate future changes</strong>.</p>
<p>Some examples of reports that might be useful for your team include:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">rake stats</code> - high level overview of project codebase stats</li>
<li><code class="language-plaintext highlighter-rouge">rake notes</code> - <a href="http://guides.rubyonrails.org/command_line.html#notes">view all <code class="language-plaintext highlighter-rouge">TODO</code>, <code class="language-plaintext highlighter-rouge">FIXME</code>, etc tags in the codebase</a></li>
<li><code class="language-plaintext highlighter-rouge">bundle outdated</code> - <a href="http://bundler.io/v1.1/bundle_outdated.html">view list of outdated gems that may need to be upgraded</a></li>
</ul>
<p>It’s been very interesting to see how simply <em>surfacing</em> this information every
time the build is run has led to developers actually <em>caring</em> about those <code class="language-plaintext highlighter-rouge">FIXME</code>
tags littered around the codebase and doing something about them.</p>
<p>These reports need to be <strong>fast</strong> to be included in the continuous integration
process. If they take too long, it will only lead to developer frustration. If they are
useful try <strong>very</strong> hard to have them run with every build. Having them run
only occasionally makes it extremely unlikely that someone will see them and act
accordingly.</p>
<p>The bottom line is:</p>
<blockquote>
<p>If you find that a report has value then use it, otherwise, move along…</p>
</blockquote>
<h2 id="rake-integration">Rake Integration</h2>
<p>So, how do you wire this whole thing up? Here’s my boilerplate Rake task that
I use for each of my projects. Just drop this into <code class="language-plaintext highlighter-rouge">lib/tasks/ci.rake</code> and
update your <code class="language-plaintext highlighter-rouge">Gemfile</code> to include the necessary dependencies and you’re good to
go! This little template has provided a <strong>huge</strong> amount of value for new projects on
Day One, and is easily customizable for future needs.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># lib/tasks/ci.rake</span>
<span class="c1"># continuous integration build task</span>
<span class="n">task</span> <span class="ss">:ci</span> <span class="k">do</span>
<span class="c1"># define all of the dependent tasks for a "clean build”</span>
<span class="c1"># add/remove tasks from this list as you see fit for your project</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="ss">:spec</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="ss">:rubocop</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="s1">'spec:javascript'</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="ss">:jshint</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="s1">'brakeman:run'</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="s1">'bundler:audit'</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="s1">'stats'</span>
<span class="n">tasks</span> <span class="o"><<</span> <span class="s1">'notes'</span>
<span class="c1"># execute tasks</span>
<span class="n">tasks</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">task</span><span class="o">|</span>
<span class="no">Rake</span><span class="o">::</span><span class="no">Task</span><span class="p">[</span><span class="n">task</span><span class="p">].</span><span class="nf">invoke</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Run the continuous integration process:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Run the full continuous integration build</span>
<span class="nv">$ </span>rake ci
</code></pre></div></div>
<p>I also recommend aliasing the <code class="language-plaintext highlighter-rouge">ci</code> Rake task to the Rake default task so you can
run Rake from the command line without any arguments. It helps
new developers get up and running quickly without having to hunt around and is
also useful when working with tools like <a href="http://docs.travis-ci.com/user/languages/ruby/#Default-Test-Script">Travis CI that run the default Rake
command without extra configuration</a>.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Rakefile</span>
<span class="nb">require</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'../config/application'</span><span class="p">,</span> <span class="kp">__FILE__</span><span class="p">)</span>
<span class="no">MyApp</span><span class="o">::</span><span class="no">Application</span><span class="p">.</span><span class="nf">load_tasks</span>
<span class="n">task</span> <span class="ss">default: :ci</span>
</code></pre></div></div>
<p>You can <strong>absolutely</strong> use a shell script instead of Rake for your build script
(ex: bin/build) and the core principles of the process remain the same. I
personally find Rake a bit nicer since it simplifies exit code management and
is written in Ruby.</p>
<h2 id="go">Go!</h2>
<p>With this basic framework in place, you can <strong>start shipping good code with
confidence on Day One of your next Rails application</strong>!</p>
<p>If you have an interesting continuous integration process that works for you,
I’d love to hear about it!</p>
Maintainable RSpec Helper2014-05-08T00:00:00+00:00https://codecrate.com/2014/05/maintainable-rspec-helper<p><a href="http://rspec.info/">RSpec</a> is a great testing library and there are are literally
a <strong>ton</strong> of useful libraries that integrate with your RSpec test suite.
Within a few minutes of bootstraping a new RSpec test suite, I typically add
in a standard set of gems for enhanced productivity
(ex: <a href="https://github.com/thoughtbot/factory_girl">factory_girl</a>,
<a href="https://github.com/bblimke/webmock">webmock</a>, <a href="https://github.com/vcr/vcr">vcr</a>,
<a href="https://github.com/travisjeffery/timecop">timecop</a>, etc).</p>
<p>The vast majority of libraries are straightforward to integrate into your project,
and only require a few steps:</p>
<ol>
<li>add the gem to your <code class="language-plaintext highlighter-rouge">Gemfile</code></li>
<li>require the library in your <code class="language-plaintext highlighter-rouge">spec/spec_helper.rb</code></li>
<li><em>[optional]</em> configure the library as necessary</li>
</ol>
<p>It doesn’t take long for your nice concise <code class="language-plaintext highlighter-rouge">spec_helper.rb</code> file to evolve into a
bloated, monolithic list of require statements and snippets of configuration code
for each library. My eyes bleed everytime I run across a file <a href="https://github.com/badeball/formtastic-pure/blob/32c4c254b183bdf5d0b1b28d5861e6e104694949/spec/spec_helper.rb">like this</a>.</p>
<h2 id="how-do-we-unwind-this-mess">How do we unwind this mess?</h2>
<p><a href="http://guides.rubyonrails.org/configuring.html">Rails has long used <code class="language-plaintext highlighter-rouge">config/initializers</code></a>
as a simple and elegant way to extract snippits of configuration code into their
own files and avoid globbing everything into one massive <code class="language-plaintext highlighter-rouge">config/application.rb</code>
file. Can we apply a similar pattern to RSpec?</p>
<p>Guess what?! RSpec <strong>already</strong> has this pattern built in! The <code class="language-plaintext highlighter-rouge">spec/support</code>
directory is automatically loaded by RSpec and is essentially equivalent to
<code class="language-plaintext highlighter-rouge">config/initializers</code>!</p>
<p>Here’s a simple example for how to load and configure the <a href="https://github.com/vcr/vcr">VCR gem</a>
into your RSpec environment <strong>without</strong> modifying your <code class="language-plaintext highlighter-rouge">spec_helper.rb</code> file.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># spec/support/vcr.rb</span>
<span class="nb">require</span> <span class="s1">'vcr'</span>
<span class="no">VCR</span><span class="p">.</span><span class="nf">configure</span> <span class="k">do</span> <span class="o">|</span><span class="n">c</span><span class="o">|</span>
<span class="n">c</span><span class="p">.</span><span class="nf">cassette_library_dir</span> <span class="o">=</span> <span class="s1">'spec/fixtures/vcr_cassettes'</span>
<span class="n">c</span><span class="p">.</span><span class="nf">hook_into</span> <span class="ss">:webmock</span>
<span class="k">end</span>
</code></pre></div></div>
<h2 id="under-the-covers">Under the Covers</h2>
<p>How does RSpec actually do it? There’s no real magic to it at all. By default, every
<code class="language-plaintext highlighter-rouge">spec_helper.rb</code> file is generated with this one hook that automatically loads
all Ruby files within the <code class="language-plaintext highlighter-rouge">spec/support</code> directory.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># spec/spec_helper.rb</span>
<span class="c1"># this line loads all your ruby files from spec/support</span>
<span class="no">Dir</span><span class="p">[</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"spec/support/**/*.rb"</span><span class="p">)].</span><span class="nf">each</span> <span class="p">{</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="nb">require</span> <span class="n">f</span> <span class="p">}</span>
<span class="c1"># BOOM!</span>
</code></pre></div></div>
<p>So, the next time you add a new gem to your test suite, resist the temptation
to modify your <code class="language-plaintext highlighter-rouge">spec_helper.rb</code>. Instead, create a <em>new file</em> in <code class="language-plaintext highlighter-rouge">spec/support</code>
and perform your standard <code class="language-plaintext highlighter-rouge">require</code> statement and any relevant configuration there!</p>
<p>Enjoy the organizational <em>#protip</em> and drop me a line if you have any other tricks!</p>
<p class="text-center">
![Keep Calm and Extract Code](/images/KEEP_CALM_AND_EXTRACT_CODE.png)
</p>
Rspec Lintable Matcher2014-02-28T00:00:00+00:00https://codecrate.com/2014/02/rspec-lintable-matcher<p>Awhile back, I <a href="/2011/06/jslint-rails-javascript-responses.html">released an Rspec matcher that validated controller responses returned linkable Javascript</a>
using the <a href="http://jslint.com">JSLint library</a>.</p>
<p>Today, I have the opportunity to resurrect that work and update it significantly
to work with the great <a href="http://jshint.com">Jshint library</a>.
The <a href="https://github.com/wireframe/rspec-lintable">rspec-lintable gem</a> adds a
convenient <code class="language-plaintext highlighter-rouge">be_lintable</code> matcher for your controller specs to easily ensure
that your Javascript responses are syntactically valid.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="s2">"#show"</span> <span class="k">do</span>
<span class="n">before</span> <span class="p">{</span> <span class="n">get</span> <span class="ss">:show</span><span class="p">,</span> <span class="ss">format: :js</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">should</span> <span class="n">be_lintable</span> <span class="p">}</span>
<span class="k">end</span>
</code></pre></div></div>
<p>All options and configuration for the <code class="language-plaintext highlighter-rouge">be_lintable</code> matcher are done via
the standard <a href="http://www.jshint.com/docs/">Jshint .jshintrc configuration file</a>.</p>
<p>This matcher gives you a <em>whole lot</em> of bang for your buck. It doesn’t
actually <strong>exercise</strong> the Javascript like a full integration test,
but in my experience, linting the response is a great smoke test that
actually catches quite a few issues that can break an end users browsers
(especially if they’re running IE).</p>
<p>Enjoy and send me any feedback if you have suggestions or issues!</p>
Jasmine Dynamic Fixtures2014-02-23T00:00:00+00:00https://codecrate.com/2014/02/jasmine-dynamic-fixtures<p>How many times has this happened on your team…</p>
<ol>
<li>A Javascript test relies on a chunk of static HTML markup modeled after the actual
markup used within your application. The <a href="https://github.com/velesin/jasmine-jquery">jasmine-jquery</a> library
makes this simple and straightforward.</li>
<li>Another developer/designer changes the HTML markup within the <strong>application</strong>,
but forgets to update the static test HTML fixture used by the <strong>testcase</strong>.</li>
<li>The Javascript test suite does <em>not</em> detect the regression. Your tests
continue to pass since they are loading a static HTML fixture that is now out of sync
with the actual markup used in your app.</li>
<li>Bugs are released to production and your Javascript no longer works as expected.</li>
</ol>
<p>It’s a simple mistake that is 100% preventable if your Javascript test suite
could <strong>re-use the same markup for both the real application and the relevant tests</strong>.
The recent <a href="https://github.com/searls/jasmine-rails/pull/90">jasmine-rails release</a> now includes
an elegant way to get rid of those fragile static HTML fixtures and leverage the markup used
within your application!</p>
<p>The JasmineRails <code class="language-plaintext highlighter-rouge">save_fixture</code> helper method can be used within any Rspec controller or view
test to safe off HTML fixtures that can later be re-used by your Jasmine test suite. This assumes of course
that your runs Rspec <strong>before</strong> Jasmine.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="s1">'spec_helper'</span>
<span class="n">describe</span> <span class="s1">'users/show.html.haml'</span> <span class="k">do</span>
<span class="n">before</span> <span class="k">do</span>
<span class="n">render</span>
<span class="k">end</span>
<span class="n">it</span> <span class="s1">'saves html fixture for Javascript specs'</span> <span class="k">do</span>
<span class="n">save_fixture</span> <span class="s1">'users/show.html'</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>After your Rspec test suite completes, these fixtures are saved to the <code class="language-plaintext highlighter-rouge">spec/javascripts/fixtures/generated</code>
directory. The <code class="language-plaintext highlighter-rouge">spec/javascripts/fixtures</code> directory can still be used for any static fixtures used by your application and the dynamic <em>generated</em> fixtures will be overwritten every time you run the Rspec tests.
The generated fixtures are also automatically ignored by Git, so you don’t need to worry about
polluting your project repository.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spec/javascripts/fixtures/
├── generated
│ └── users
│ └── show.html
└── static_fixture.html
</code></pre></div></div>
<p>These dynamically generated fixtures can now be loaded by your Jasmine specs with
the <a href="https://github.com/velesin/jasmine-jquery">jasmine-jquery</a> library by tweaking the path used by
the <code class="language-plaintext highlighter-rouge">loadFixtures</code> call.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">describe</span><span class="p">(</span><span class="dl">'</span><span class="s1">users/show.js</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="dl">'</span><span class="s1">use strict</span><span class="dl">'</span><span class="p">;</span>
<span class="nx">beforeEach</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">loadFixtures</span><span class="p">(</span><span class="dl">'</span><span class="s1">generated/users/show.html</span><span class="dl">'</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">it</span><span class="p">(</span><span class="dl">'</span><span class="s1">loads generated HTML fixtures</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// assert something here</span>
<span class="p">});</span>
<span class="p">});</span>
</code></pre></div></div>
<p>This solution has been a huge success for our team, and has successfully caught <strong>several</strong>
regressions by our standard continuous integration process (and <strong>not</strong> by our customers).</p>
Replace Rake with Thor2014-01-20T00:00:00+00:00https://codecrate.com/2014/01/replace-rake-with-thor<p>Okay, let’s be honest, when was the last time you actually wrote a unit test
for a Rake task? My guess is <strong>NEVER</strong>.</p>
<p>Unit testing Rake tasks is a <a href="http://robots.thoughtbot.com/test-rake-tasks-like-a-boss">pain in the ass</a> to say the least.
Most developers “work around” unit testing Rake tasks by
extracting logic out of the Rake task and into an actual unit testable Ruby object,
still leaving the actual Rake task untested. This may be acceptable for
<em>some</em> developers, but <strong>any technology that is prohibitively difficult to test
should be a red flag that something is wrong</strong>. This also can leave
significant coverage gaps if your Rake task is parameterized and requires
any parsing of CLI options.</p>
<p>Now, if you extract logic out of your Rake task and
into a good old <em>testable</em> Ruby object, why is the extra boilerplate
(and untested) Rake task even necessary?
Let’s get rid of that extra layer of indirection and complexity and simply use <a href="http://whatisthor.com">Thor</a> instead.</p>
<p>The beauty of Thor tasks is that they are Plain Old Ruby Objects <strong>and</strong>
a Rake-like task runner all in one. Your tasks are now 100% unit testable
without jumping through hoops, and your code is consolidated into one easily
maintainable location.</p>
<p>Go from this…</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Rakefile</span>
<span class="n">task</span> <span class="ss">:do_something</span> <span class="k">do</span>
<span class="no">MyCommand</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">run</span>
<span class="k">end</span>
<span class="c1"># lib/my_command.rb</span>
<span class="k">class</span> <span class="nc">MyCommand</span>
<span class="k">def</span> <span class="nf">run</span>
<span class="c1"># do something here</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>To this…</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># lib/tasks/my_command.thor</span>
<span class="k">class</span> <span class="nc">MyCommand</span> <span class="o"><</span> <span class="no">Thor</span>
<span class="n">desc</span> <span class="s1">'do_something'</span><span class="p">,</span> <span class="s1">'do some work'</span>
<span class="k">def</span> <span class="nf">do_something</span>
<span class="c1"># do something here</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Seriously, it’s that easy. Life on the Thor bandwagon is great from here on out.
You’ll never look back at Rake…until…</p>
<h2 id="rails-environment-dependencies">Rails Environment Dependencies</h2>
<p>Undoubtedly, there will come a time where you will want to write a Thor task
that relies on your Rails environment. Seems simple right? Good old Rake
made it easy:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">task</span> <span class="ss">:do_something</span> <span class="o">=></span> <span class="ss">:environment</span> <span class="k">do</span>
<span class="c1"># Rails environment is loaded</span>
<span class="k">end</span>
</code></pre></div></div>
<p>So, how do you do this in Thor? The <a href="http://github.com/thegarage/thor-rails">thor-rails gem</a> is my recommended solution. Include the <code class="language-plaintext highlighter-rouge">Thor::Rails</code>
module into your Thor command, and the Rails environment will automatically
be loaded just like the Rake <code class="language-plaintext highlighter-rouge">:environment</code> dependency.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MyCommand</span> <span class="o"><</span> <span class="no">Thor</span>
<span class="kp">include</span> <span class="no">Thor</span><span class="o">::</span><span class="no">Rails</span>
<span class="n">desc</span> <span class="s1">'do_something'</span><span class="p">,</span> <span class="s1">'do some work'</span>
<span class="k">def</span> <span class="nf">do_something</span>
<span class="c1"># Rails environment is loaded and available!</span>
<span class="n">say</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">env</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h2 id="gem-extensions">Gem Extensions</h2>
<p>Rake has been around for a <strong>long</strong> time, and the Ruby community
has built a <strong>considerable</strong> <a href="http://rubygems.org/search?query=rake">collection of extensions and integrations</a>.
There were two critical features that needed to be addressed
in order to complete the migration from Rake to Thor…</p>
<h4 id="performance-monitoring-newrelic">Performance Monitoring (NewRelic)</h4>
<p><a href="http://newrelic.com/">NewRelic</a> is my goto solution for application
profiling and the
<a href="https://github.com/flyerhzm/newrelic-rake">newrelic-rake gem</a> has
been an excellent addition to introspect performance of Rake tasks.</p>
<p>The <a href="https://github.com/thegarage/newrelic-thor">newrelic-thor gem</a>
brings that same profiling support to your Thor tasks with no code
changes. Can’t get much easier then that!</p>
<h4 id="exception-tracking-honeybadger">Exception Tracking (Honeybadger)</h4>
<p><a href="http://honeybadger.io/">Honyebadger</a> is an excellent solution
for tracking application exceptions. They even package tracking
of Rake exceptions right into their core gem.</p>
<p>The <a href="https://github.com/thegarage/honeybadger-thor">honeybadger-thor gem</a>
adds similar exception tracking to your Thor tasks. Just drop the
gem into your app and you’re set! Hopefully, this feature will
be <a href="https://twitter.com/codecrate/status/424034659228340225">integrated into the core honeybadger gem sometime soon</a>.</p>
<p>There’s simply no excuse to <strong>not</strong> write tests for your code,
and Rake tasks <strong>are</strong> most definitely code. But instead of delving into
the depths and horrors of <strong>how</strong> to unit test Rake tasks,
my answer is to simply leave your Rake in the yard and use <a href="http://whatisthor.com">Thor</a>.</p>
Bundler Reorganizer2014-01-12T00:00:00+00:00https://codecrate.com/2014/01/bundler-reorganizer<p><a href="http://bundler.io/v1.5/groups.html">Bundler groups</a> are an incredibly useful feature for managing dependencies of your ruby project.
Keeping your Gemfile organized can be a challenge and it’s all too easy to accumulate
stray inline group declarations over time that would be better served with the block-style syntax.</p>
<p>The <a href="https://github.com/wireframe/bundler-reorganizer">bundler-reorganizer</a> gem is now available
to get your Gemfile back in shape! One simple command turns your <strong>unwieldy</strong> Gemfile from this:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">gem</span> <span class="s2">"utils"</span><span class="p">,</span> <span class="ss">:group</span> <span class="o">=></span> <span class="ss">:development</span>
<span class="n">gem</span> <span class="s2">"more-tools"</span><span class="p">,</span> <span class="ss">:group</span> <span class="o">=></span> <span class="ss">:development</span>
<span class="n">gem</span> <span class="s2">"testsuite-runner"</span><span class="p">,</span> <span class="ss">:group</span> <span class="o">=></span> <span class="p">[</span><span class="ss">:development</span><span class="p">,</span> <span class="ss">:test</span><span class="p">]</span>
</code></pre></div></div>
<p>Into this!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">group</span> <span class="ss">:development</span> <span class="k">do</span>
<span class="n">gem</span> <span class="s2">"utils"</span>
<span class="n">gem</span> <span class="s2">"more-tools"</span>
<span class="k">end</span>
<span class="n">group</span> <span class="ss">:development</span><span class="p">,</span> <span class="ss">:test</span> <span class="k">do</span>
<span class="n">gem</span> <span class="s2">"testsuite-runner"</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Getting up and running with bundler-organizer is as simple as:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>gem <span class="nb">install </span>bundler-reorganizer
<span class="nv">$ </span>bundler-reorganizer path/to/Gemfile
</code></pre></div></div>
<p>That’s all there is to it. The command is 100% re-runnable, so you can re-prettify your Gemfile
from time to time as necessary.</p>
<p><a href="https://github.com/wireframe/bundler-reorganizer">Suggestions, feedback and patches</a> are always welcome!</p>
iPhoto Backup Gem2013-11-29T00:00:00+00:00https://codecrate.com/2013/11/iphoto-backup-gem<p>I’ve had a very simple photo archival strategy in place for over 10 years now which basically boils down to grouping related images in a folder named for the event with an <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO8601 date prefix</a> for easy organization.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Pictures
|____2013
| |____2013-08-30 End of Summer BBQ
| | |____IMG_3842.jpg
| | |____IMG_3843.jpg
</code></pre></div></div>
<p>It’s a super low-tech solution that has worked like a dream across multiple operating systems, computers, and cameras. As long as operating systems have concepts of files and hierarchical folders, this strategy should work great for a <em>long</em> time to come.</p>
<p>Over the past 5 years, I’ve been a Mac user and have come to really like iPhoto. It gets the job done for organizing photos with a clean and fairly intuitive interface. My only real complaint with iPhoto is how difficult it is to get access to my original files for archiving and backups. <em>Don’t even get me started on Time Machine and vendor lock-in…</em></p>
<p>I adapted <a href="https://github.com/wireframe/dotfiles/blob/628b982d9fc4e7b4cc9e6ca806cae81b541f9bbd/home/bin/iphoto_export.py">a home-rolled python script</a> as a first solution for extracting photos out of iPhoto and into my standard directory structure and it worked relatively well, but I finally got around to porting it to Ruby which is a <strong>huge</strong> win for code clarity since I am <strong>not</strong> a fan of Python.</p>
<p>The <a href="https://github.com/wireframe/iphoto_backup">iphoto_backup gem</a> is now available on ruby gems for <em>anyone</em> interested in extracting and archiving photos out of iPhoto. It is a simple command line application that will copy the files out of the original iPhoto location into the backup directory of your choosing.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>iphoto_backup
Processing Roll: Wedding Pics...
copying /iphoto/file.png to /my/custom/backup.png
</code></pre></div></div>
<p>Additional instructions and information are available on <a href="https://github.com/wireframe/iphoto_backup">Github</a>, and as always, <strong>pull requests are welcome!</strong></p>
Cooking OSX Machines with Kitchenplan2013-11-12T00:00:00+00:00https://codecrate.com/2013/11/cooking-osx-machines-with-kitchenplan<blockquote>
<p>Provisioning a new OSX machine is a chore, and time is the one thing we never have enough of…</p>
</blockquote>
<p><a href="http://www.opscode.com/chef/">Chef</a> has made setting up production servers trivial. Why not use Chef to automate setting up your development environment in a standard and reproducible way?</p>
<h1 id="kitchenplan-to-the-rescue">Kitchenplan to the rescue</h1>
<p><a href="http://vanderveer.be/blog/2013/04/14/presenting-kitchenplan/">Kitchenplan</a> is a brilliant tool for packaging up Chef recipes to setup and configure OSX/Linux environments. It’s the perfect tool to automate building out a team’s standard development environment.</p>
<p>Creating your own stack is as simple as following a few steps:</p>
<ol>
<li>Fork the <a href="https://github.com/thegarage/kitchenplan/">kitchenplan github repo</a></li>
<li>Customize your list of Chef recipes in <code class="language-plaintext highlighter-rouge">config/default.yml</code></li>
<li>Provision your machine using the awesome installer script (inspired by <a href="https://raw.github.com/mxcl/homebrew/go">Homebrew</a> and <a href="https://github.com/kitchenplan/kitchenplan/pull/33">written by yours truly</a>)</li>
</ol>
<p>The installer script takes you from zero to hero in one line. There’s literally nothing else you need to do to get up and going. The installer script even takes care of <strong>automatically installing Xcode Command Line Tools</strong>!</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # configure location of custom kitchenplan repository
$ export KITCHENPLAN_REPO=https://github.com/mycompany/kitchenplan.git
# install/update kitchenplan recipes and run chef
$ ruby -e "$(curl -fsSL https://raw.github.com/kitchenplan/kitchenplan/master/go)"
</code></pre></div></div>
<h2 id="re-runnable">Re-runnable</h2>
<p>We all know that provisioning your development environment is <em>not</em> a one time ordeal. We <strong>constantly</strong> tweak and change our environments as new tools/technologies become available. Kitchenplan (and Chef) support this flow incredibly well, and you can re-run kitchen plan anytime to update your local environment with new configuration or recipes. The installer script will actually automatically update an existing installation with the latest available configuration in the remote repository for you.</p>
<h2 id="flexibile">Flexibile</h2>
<p>Kitchenplan has an elegant set of configuration files that supports global as well as per-user level recipes/attributes. It also supports extracting common sets of settings and recipes into “groups”. Here’s an <a href="https://github.com/thegarage/kitchenplan/blob/master/config/people/ryansonnek.yml">example config for my current machine</a> that adds additional recipes and customized attributes.</p>
<p>I spent some time exploring <a href="https://github.com/wireframe/chef-osxbootstrap">Pivotal sprout</a> as an alternative to kitchenplan, but it’s lack of groups and limited local user customizations really make kitchen plan shine here.</p>
<h1 id="building-your-kitchenplan">Building your [Kitchen]plan</h1>
<p>There are <strong>lots</strong> of recipes to choose from to build your kitchen plan config, and it can be overwhelming to know where to start. I’ve found the best place to start is to cherry-pick recipes one at a time instead of trying to import a whole slew of recipes and weed through which ones are relevant.</p>
<p>In general, you can group your recipes into one of these three categories:</p>
<h2 id="osx-system-configuration">OSX system configuration</h2>
<p>These settings range from <a href="https://github.com/thegarage/chef-osxdefaults/blob/master/recipes/finder_display_full_path.rb">trivial tweaks to OSX Finder</a> to <a href="https://github.com/thegarage/chef-osxdefaults/blob/master/recipes/set_screensaver_preferences.rb">security related settings to ensure machines prompt for passwords after idle for an extended period of time</a>.</p>
<p>The <a href="https://github.com/kitchenplan/chef-osxdefaults">chef-osxdefaults cookbook</a> is a highly recommended starting point for these recipes (contributions welcome).</p>
<h2 id="application-installation">Application installation</h2>
<p><a href="http://brew.sh">Homebrew</a> and <a href="https://github.com/phinze/homebrew-cask">homebrew cask</a> are absolutely awesome and have pretty much cornered the market for installing apps on OSX. Luckily, the <a href="https://github.com/kitchenplan/chef-applications">chef-applications cookbook</a> is smart enough to leverage homebrew and homebrew cask under the covers and delegate to those existing libraries instead of re-inventing the wheel.</p>
<p>Pretty much every recipe I needed to get up and running was already available right out of the box (and contributions are always welcome).</p>
<h2 id="user-environment">User environment</h2>
<p>Building the perfect shell environment takes a <strong>long</strong> time and I’ve invested a ton of time in <a href="https://github.com/wireframe/dotfiles">my personal dotfiles</a>. Building out a sweet shell config with kitchen plan is completely possible, especially if you feel comfortable hopping in and creating a few simple recipes for <a href="https://github.com/revans/bash-it">bash-it</a> extensions.</p>
<p><a href="https://github.com/thegarage/chef-dotfiles">the chef-dotfiles cookbook</a> has done a good job here as well getting a basic shell environment up to snuff and on par with my old custom dotfiles configuration (yep, contributions are encouraged).</p>
<h1 id="remodeling-starts-today">Remodeling starts today</h1>
<p>Creating a custom kitchenplan is an easy way to pay it forward and give your “future self” a few extra hours of productivity when you have to setup that next development environment.</p>
Sublime Text Spec Focuser Plugin2013-11-05T00:00:00+00:00https://codecrate.com/2013/11/sublime-text-spec-focuser<p>Guard has been my tool of choice for continuous testing for quite some time now, and I can not recommend it enough. One of my only complaints with the workflow is that <strong>Guard can be too aggressive</strong> and run all the specs in the relevant files which creates overwhelming amount of feedback, when I actually just want to focus on a few specific tests.</p>
<p>Rspec supports <a href="http://stackoverflow.com/questions/5069677/how-do-i-run-only-specific-tests-in-rspec">tagging specs</a> as an elegant way to temporarily restrict your spec runner to only run a specific set of tests. This works out of the box with the Guard RSpec runner, but it can be cumbersome to constantly add and remove <code class="language-plaintext highlighter-rouge">focus: true</code> statements for each of your specs…<strong>until now</strong>!</p>
<p>For the past six months, Sublime Text has been my primary IDE, and I’ve released my first Sublime Text plugin, the <a href="https://github.com/wireframe/sublime-spec-focuser">Sublime SpecFocuser plugin</a>, to help streamline your workflow of focusing on Rspec tests.</p>
<p>The SpecFocuser plugin adds a convenient command that will automatically tag your currently selected spec with the proper <code class="language-plaintext highlighter-rouge">focus: true</code> statement. The plugin is also smart enough to traverse up your current scope as well to find the nearest <code class="language-plaintext highlighter-rouge">it</code>, <code class="language-plaintext highlighter-rouge">context</code> or <code class="language-plaintext highlighter-rouge">describe</code> block. And the best part is that once you’ve wrapped up your testing, re-running the plugin command will strip out the <code class="language-plaintext highlighter-rouge">focus: true</code> statement and get you back to a clean, un-focused test suite!</p>
<p>This is my first foray into the world of Sublime Text plugin development, and although I’m not a huge fan of Python, I’m impressed with the flexibility of the Sublime Text plugin system. That’s quite a statement given that after two solid years of working with VIM, I still cringe at the idea of delving into Vimscript!</p>
<p>I see a lot more hacking on Sublime Text plugins in my future to further optimize my development workflow…</p>
FactoryGirl RSpec Traits2013-10-10T00:00:00+00:00https://codecrate.com/2013/10/factorygirl-rspec-traits<p><a href="http://robots.thoughtbot.com/post/23673635798/remove-duplication-with-factorygirls-traits">FactoryGirl traits</a> are a great way to encapsulate a set of properties into convenient and meaningful names. Using traits effectively is a simple way to drastically improve the expressiveness of your specs.</p>
<p>The 2.0 release of the <a href="/2011/10/cleaner-rspecfactorygirl-integration.html">FactoryGirl RSpec gem</a> includes <a href="https://github.com/wireframe/factory_girl_rspec/pull/4">a major change that now treats traits as first class citizens</a>. When you instantiate a FactoryGirl object instance with traits, the FactoryGirl RSpec gem will now <em>automatically</em> name your local variable to include the traits as part of the variable definition.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="no">User</span> <span class="k">do</span>
<span class="n">describe</span> <span class="s1">'#some_method'</span> <span class="k">do</span>
<span class="n">with</span> <span class="ss">:user</span><span class="p">,</span> <span class="ss">:without_first_name</span>
<span class="n">it</span> <span class="s1">'works as expected'</span> <span class="k">do</span>
<span class="c1"># notice the variable name includes the trait!</span>
<span class="n">user_without_first_name</span><span class="p">.</span><span class="nf">some_method</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Keeping your variable names in sync with the declared factory/traits makes your specs much more <em>expressive</em>. This also means it is now possible to write a spec that relies on multiple instances of the same factory, and each instance can have different traits.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="no">User</span> <span class="k">do</span>
<span class="n">describe</span> <span class="s1">'#some_method'</span> <span class="k">do</span>
<span class="n">with</span> <span class="ss">:user</span><span class="p">,</span> <span class="ss">:without_first_name</span>
<span class="n">with</span> <span class="ss">:user</span><span class="p">,</span> <span class="ss">:without_last_name</span>
<span class="n">it</span> <span class="s1">'works as expected'</span> <span class="k">do</span>
<span class="c1"># notice each instance maps to the proper set of traits!</span>
<span class="n">user_without_first_name</span><span class="p">.</span><span class="nf">some_method</span>
<span class="n">user_without_last_name</span><span class="p">.</span><span class="nf">some_method</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>After using this change, it’s hard to imagine ever going back to a test suite that uses <em>generic</em> variable names for the instantiated factory objects.</p>
Optimistic Feedback for Improved User Experiences2013-09-05T00:00:00+00:00https://codecrate.com/2013/09/optimistic-feedback<p>Click on nearly any link in a Web 2.0 application and you’re almost guaranteed to experience the following:</p>
<ul>
<li>an inline spinner to show progress while some work takes place</li>
<li>a delay of an indeterminate amount of time while you wait for <strong>something</strong> to finish</li>
<li>spinner goes away and you get some kind of feedback that the work is complete.</li>
</ul>
<p>Here is a pretty classic example of how most web applications accomplish this.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="nb">document</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">a.delayed_feedback</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="kd">var</span> <span class="nx">$link</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">/path/to/endpoint</span><span class="dl">'</span><span class="p">,</span>
<span class="na">beforeSend</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// show an indicator while work is being processed</span>
<span class="nx">$link</span><span class="p">.</span><span class="nx">addClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">processing</span><span class="dl">'</span><span class="p">);</span>
<span class="p">},</span>
<span class="na">success</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// wait until XHR completes to give user feedback of success</span>
<span class="nx">$link</span><span class="p">.</span><span class="nx">addClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">success</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
<span class="p">});</span>
</code></pre></div></div>
<p>This delayed feedback interaction is appropriate for some use cases, but is it <em>always</em> necessary? Showing a “spinner” immediately forces a user to wonder <strong>how long will this take and when will it complete</strong>?</p>
<p>In start contrast, take a look at how Facebook implements their interaction for the Like button. Clicking “Like” gives you <strong>immediate</strong> feedback and flips the state to success even before a request has been fired. That’s right…they’re cheating a bit and assuming that the request <strong>will</strong> succeed eventually. And guess what? Over 99% of the time, the operation completes without any issues. This is an amazing UX for users and completely removes the disconnect between a user requesting work to be done and wondering if/when it will complete.</p>
<p>Building this style of interaction is actually extremely trivial to implement:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="nb">document</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">a.immediate_feedback</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="kd">var</span> <span class="nx">$link</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">/path/to/endpoint</span><span class="dl">'</span><span class="p">,</span>
<span class="na">beforeSend</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// assume success and give immediate</span>
<span class="c1">// feedback to the user</span>
<span class="nx">$link</span><span class="p">.</span><span class="nx">addClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">success</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
<span class="p">});</span>
</code></pre></div></div>
<p>Wow, talk about an improvement. Feedback is instant, and the <strong>perceived</strong> performance of the application jumps ten fold. Faster feedback equals happy users.</p>
<p><img src="http://farm6.staticflickr.com/5017/5428693024_f2c76f1d00.jpg" alt="" /></p>
<h3 id="one-more-thing">One More Thing…</h3>
<p>I can hear you screaming through the fibers of the internet…<strong>WHAT IF SOMETHING FAILS</strong>!</p>
<p>First of all, it’s absolutely critical for you to be able to <em>quantify</em> how likely the failure scenario is. <strong>Measure it</strong>. You can start with your existing “delayed feedback” solution and review how likely a failure scenerio is to occur. Next, you’ll need to determine how critical is it from a user’s perspective if something <em>seemed</em> like it worked and then it didn’t. In the example of the Facebook Like button, a missed “Like” far from a mission critical failure.</p>
<p>If you <strong>need</strong> to worry about failure conditions, a few options include:</p>
<ul>
<li>revert the state back to the original pre-XHR state</li>
<li>tell the user that something went wrong and ask them to re-load the page</li>
</ul>
<p>Here’s a simple example that gives a nice blend of immediate feedback plus error handling for the edge case when something goes wrong.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="nb">document</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">a.immediate_feedback</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="kd">var</span> <span class="nx">$link</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">/path/to/endpoint</span><span class="dl">'</span><span class="p">,</span>
<span class="na">beforeSend</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// assume success and give immediate</span>
<span class="c1">// feedback to the user</span>
<span class="nx">$link</span><span class="p">.</span><span class="nx">addClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">success</span><span class="dl">'</span><span class="p">);</span>
<span class="p">},</span>
<span class="na">error</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// oops! something went wrong</span>
<span class="c1">// revert back to previous state</span>
<span class="nx">$link</span><span class="p">.</span><span class="nx">removeClass</span><span class="p">(</span><span class="dl">'</span><span class="s1">success</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
<span class="p">});</span>
</code></pre></div></div>
<p>It’s all about finding the right tool (or interaction) for the right job. Keep this trick in your tool belt and use it whenever appropriate to make your next user experience awesome!</p>
Homesick for Managing Dotfiles2013-08-29T00:00:00+00:00https://codecrate.com/2013/08/homesick-dotfile-managment<blockquote>
<p>I’m homesick to-night, just homesick,
O! how I long once more.
Just to sit as of old in the twilight.
On the step of the old kitchen door.</p>
<ul>
<li><a href="http://skyways.lib.ks.us/poetry/homesick.html">Homesick by Ella Goodwin</a></li>
</ul>
</blockquote>
<p>Configuring a new development laptop can be a downright pain. From your bash configuration to git aliases, it’s easy to loose a day or five getting everything setup <em>just right</em>, and more often than not there will always be a few settings that get lost along the way…</p>
<p>Fear not good friends, <a href="https://github.com/technicalpickles/homesick">Homesick</a> is a tool that makes bootstrapping your next environment as simple as:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gem install homesick
$ homesick clone wireframe/dotfiles
$ homesick symlink wireframe/dotfiles
</code></pre></div></div>
<h3 id="boom">BOOM!</h3>
<p><a href="https://github.com/wireframe/dotfiles">My dotfiles</a> have now carried me through three OS installations in the past two monthes and each installation has been absolutely seemless. Having dotfiles in version control has made keeping changes in sync across machines a dream as well as sharing configuration with other developers.</p>
<p>The sky is the limit for what you include in your dotfiles, and the key features of <strong>my</strong> dotfiles include:</p>
<ul>
<li>environment initialization (ex: path, aliases)</li>
<li>bash configuration (ex: prompt, autocompletion, etc)</li>
<li>helpful scripts and commands (ex: git-cleanup.sh)</li>
<li>OSX system default preferences</li>
<li>VIM configuration</li>
<li>Sublime Text configuration</li>
<li>Git configuration (aliases, merge settings, etc)</li>
<li>Ruby configuration (IRB, Rubygems, Rspec, etc)</li>
</ul>
<h3 id="onward-to-automation">Onward to automation</h3>
<p>Homesick is a simple and powerful tool that takes 90% of my pain away when setting up a new environment, but there’s there’s still work to be done to make setting up a new environment literally a turn-key solution. <a href="http://boxen.github.com/">Boxen</a>, <a href="http://vanderveer.be/blog/2013/04/14/presenting-kitchenplan/">KitchenPlan</a> and other tools are now emerging in this space that look <strong>very</strong> interesting, but each of them adds a new layer of complexity that makes them more of an investment than the simplicity of Homesick.</p>
Adios Blogger. Hello Jekyll!2013-08-16T00:00:00+00:00https://codecrate.com/2013/08/migrating-from-blogger-to-jekyll<blockquote>
<p>It’s been a long time coming…</p>
</blockquote>
<p>For a variety of reasons, both personal and professional, my blogging pasttime
has pretty much come to a screeching halt.</p>
<p>With my <a href="/2013/07/a-new-day.html">recent job change</a>,
I’ve renewed my commitment to blog and now is a perfect opportunity to
revisit my workflow and toolset.</p>
<h3 id="blogger-is-teh-suck">Blogger is teh suck</h3>
<p><a href="http://blogger.com">Blogger</a> has been my blog engine of choice for the past
few years, but the thought of jumping back into blogging with the venerable
Blogger system doesn’t excite me for a number of reasons…</p>
<p>First, I <strong>hate</strong> WSIWYG editors. I absolutely loathe and abhor them.
As a writer, I need to focus on the <em>content</em>, and not be constantly fiddling
with the <em>markup</em> generated. As a Ruby developer writing blog
posts, code snippits are absolutely <em>hell</em> when you have to
fight with a WSIWYG editor.</p>
<p>In the end, I have found it infinitely easier to just write my posts in
<a href="http://daringfireball.net/projects/markdown/">Markdown</a> and then export the
generated HTML and dump them into Blogger’s HTML editor untouched. So, why not
skip all of the run around and work with a blog engine that is Markdown compatible?</p>
<h3 id="enter-jekyll">Enter Jekyll</h3>
<p><a href="http://jekyllrb.com/">Jekyll</a> is a static website framework perfect for blog authors
built by the awesome folks at <a href="http://github.com">Github</a> and has caught on like
wildfire with the development blogging community.</p>
<p>Jekyll is <em>very</em> developer friendly and includes all the tools you need to build a
static site that <em>feels</em> like a mini-app (paritials, variables, etc).
Liquid templates are going to take some time to get used to, but the basics are easy
to grasp and there’s really no need to dig in much deeper.</p>
<p>Things I like:</p>
<ul>
<li>Simple yet flexible</li>
<li>Full control - I own the HTML, CSS, and JS libraries and am not limited by a theme chooser.</li>
<li>Git integration - offline editing, commit, push, and your content is live!</li>
<li>No ads, banners, etc polluting my site!</li>
</ul>
<h3 id="the-mass-exodus">The Mass Exodus</h3>
<p>This isn’t the first blog migration I’ve done. I’ve had a blog now for over
ten years going all the way back to when good old <a href="http://jroller.com">JRoller</a>
was the new hotness. I carried those posts along to Blogger, and they’ll
stay with me as I transition to the next blog engine…</p>
<p>There are <em>plenty</em> of <a href="http://jekyllrb.com/docs/migrations/">resources</a> available
for <a href="http://blog.coolaj86.com/articles/migrate-from-blogger-to-jekyll.html">exporting Blogger</a>
posts <a href="https://gist.github.com/kennym/1115810">to Jekyll</a>,
and it didn’t take much work to whip up a <a href="https://github.com/wireframe/wireframe.github.com/blob/master/_blogger_archive/import.rb">custom ruby script</a> that did a great job
migrating the HTML posts from Blogger into Jekyll format. I even took the extra
step to convert the HTML posts into Markdown and I’m happy to say that it did a
pretty great job and only required some minor manual tweaks to clean up afterwards.</p>
<p>Making the transition seamless was a breeze and only required me to
<a href="https://github.com/wireframe/wireframe.github.com/blob/master/_config.yml#L3">tweak the Jekyll permalink URL to match the old Blogger URL structure</a>, and then update the DNS entry to redirect my
old blog.codecrate.com domain over to the Github hosted codecrate.com site.</p>
<h3 id="to-infinity-and-beyond">To Infinity and Beyond!</h3>
<p>Now that the pain is over, it’s time to get back in high gear pushing out some new posts!</p>
A New Day2013-07-16T00:00:00+00:00https://codecrate.com/2013/07/a-new-day<p>In just a few minutes, the clock will chime, and with it, I will have another year under my belt. Another year older, and <em>hopefully</em> another year wiser…</p>
<p>It’s been an amazing and eventful year as a father of a growing family, and as a developer now transitioning to a new company. My spare time has been reduced to near zero and my reduced capacity for <strong>hackathons</strong> has forced me to be incredibly selective in what opensource projects I invest in.</p>
<p>With all of this change comes uncertainty. Risk. The possibility that something may fall apart. So, why leave a good thing for a new venture? Why choose the <strong>unknown</strong>?</p>
<p>I’ve been incredibly blessed over the past five years to be a part of <a href="http://socialcast.com">something special</a>.
Working at a startup had always been a dream, and working at a <em>successful</em> startup was an absolute <strong>dream come true</strong>. But at some point, things can become comfortable and routine which is a red flag that change is necessary.</p>
<p>Keeping the status quo is not an option. A feeling of complacency can lull you to into a secure position and steal away the passion and fire that got you to where you are today. So where do we go from here? The answer of course is <strong>forward</strong>.</p>
<p>Every single decision has an unknown outcome on your future. Although there is a <em>risk</em> of failure, these is also a <em>guarantee</em> for new opportunities. If you are unwilling to change, you are <em>guaranteed</em> to atrophy.</p>
<p>Each day is a chance to <em>move</em>. A chance to <em>learn</em>. Every moment is a chance to <em>grow</em>.</p>
<blockquote>
<p>“Stay hungry. Stay foolish.”</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Whole_Earth_Catalog">Steve Jobs</a></li>
</ul>
</blockquote>
Backgrounded 2.0 Beta2012-05-22T00:00:00+00:00https://codecrate.com/2012/05/backgrounded-20-beta<p><a href="http://github.com/wireframe/backgrounded">Backgrounded</a> 2.0 beta is now available with some really exciting changes. I’ve taken this release as an opportunity to critically evaluate the perfect API for invoking background jobs. The new API is _not_backwards compatible with previous versions, but it is SEXY as HELL!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span>
<span class="c1"># instance method to do some stuff</span>
<span class="k">def</span> <span class="nf">do_stuff</span>
<span class="k">end</span>
<span class="c1"># class method to do something else</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">do_something_else</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="c1"># execute class method in background</span>
<span class="no">User</span><span class="p">.</span><span class="nf">backgrounded</span><span class="p">.</span><span class="nf">do_something_else</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="c1"># execute instance method in background</span>
<span class="n">user</span><span class="p">.</span><span class="nf">backgrounded</span><span class="p">.</span><span class="nf">do_stuff</span>
</code></pre></div></div>
<p>Oh snap…Did you see what happened there? I just ran class and instance methods in the background with <strong>no</strong> code changes whatsoever! This new API allows for _any_method on _any_ruby object to be executed in the background. But that’s not all! The new API also simplified passing custom options into the background handlers (which is awesome for resque users).</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># execute instance method on a custom resque queue</span>
<span class="n">user</span><span class="p">.</span><span class="nf">backgrounded</span><span class="p">(</span><span class="ss">:queue</span> <span class="o">=></span> <span class="s1">'custom'</span><span class="p">).</span><span class="nf">do_stuff</span>
</code></pre></div></div>
<p>It’s glorious…</p>
<h2 id="extension-gems">Extension Gems</h2>
<p>One of Backgrounded’s core missions is to be a simple and lightweight wrapper around <em>any</em> background processing framework. With this release, I’ve decided to extract logic for each library into separate gems. This helps simplify the core testsuite and makes it more extensible in the long run to release updates to specific libraries without bumping the core library version.</p>
<p>The <a href="http://github.com/wireframe/backgrounded-resque">backgrounded-resque gem is now available on github</a>.</p>
<h3 id="bundler-config">Bundler config</h3>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">gem</span> <span class="s1">'backgrounded-resque'</span>
</code></pre></div></div>
<p>If any other developers are interested in building a backgrounded wrapper, spin up a gem and drop me a line!</p>
<h2 id="after_commit_backgrounded-callback">after_commit_backgrounded Callback</h2>
<p>Using ActiveRecord callbacks to perform background work is an
<a href="/2009/10/backgrounded-activerecord-callbacks.html">extremely common pattern</a>.
Background jobs should only be invoked after the data has been committed to the database to
ensure that the background job will have access to the recent changes and
backgrounded now makes it even easier to do the “right thing”.</p>
<p>The after_commit_backgrounded callback is just like your standard <a href="http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit">Rails after_commit hook</a> with a few minor upgrades. It executes the referenced method in the background (duh), and it allows for an optional :backgrounded option to customize the options for the Backgrounded::Handler.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="c1"># execute :do_something in the background</span>
<span class="n">after_commit_backgrounded</span> <span class="ss">:do_something</span>
<span class="c1"># execute :do_something_else in the background</span>
<span class="c1"># passing custom options to the backgrounded handler</span>
<span class="n">after_commit_backgrounded</span> <span class="ss">:do_something_else</span><span class="p">,</span> <span class="p">\</span>
<span class="ss">:backgrounded</span> <span class="o">=></span> <span class="p">{</span><span class="ss">:priority</span> <span class="o">=></span> <span class="ss">:high</span><span class="p">}</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Grab the latest beta version via rubygems and send any feedback my way!</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install backgrounded --pre
</code></pre></div></div>
Bundler Nirvana With Custom Groups2012-05-03T00:00:00+00:00https://codecrate.com/2012/05/bundler-nirvana-with-custom-groups<p>Managing gem dependencies in Rails applications has been an ongoing struggle over the years. Anyone out there still remember vendoring and freezing gems/plugins into their application? Ah yes, the good old days. Thank goodness for <a href="http://gembundler.com/">bundler</a>. For all of it’s warts, it’s an exceptional piece of software and has made my life <em>infinitely</em> better.</p>
<p>The basics of bundler are all well and good, but my goal here is to take your bundler-fu to the next level.</p>
<h2 id="the-problem">The Problem</h2>
<p>As applications grow, managing your Gemfile dependencies is an ongoing issue. The number of dependencies grows…and grows…and grows, until you are no longer able to grok what your application needs to get up and running with a simple visual scan.</p>
<h2 id="enter-custom-bundler-groups">Enter Custom Bundler Groups!</h2>
<p>Inspired by the great article by <a href="http://iain.nl/getting-the-most-out-of-bundler-groups">Iain Hecker</a>,
I began exploring more advanced usage of bundler groups.
The <a href="/2012/03/rails-console-tweaks-gem.html">rails-console-tweaks gem</a> was a step in the right direction,
but there’s plenty more work to be done!</p>
<p>After launching a few Rails applications from the ground up, I found a number of reusable themes that could be expressed quite well using bundler groups.</p>
<p>At a minimum, a basic Rails application should have a bundle group for each of these areas:</p>
<ul>
<li>:app - gems for front end appservers (ex: rack middleware)</li>
<li>:worker - gems for resque backend processing jobs (ex: resque-ensure-connected)</li>
<li>:console - gems for firing up a rails console (ex: hirb, awesome_print)</li>
<li>:development - gems for day to day development tasks (ex: email_preview, mailcatcher, etc)</li>
<li>:test - gems for running testcases (ex: rspec, webmock, etc)</li>
<li>:debug - gems for firing up the debugger (ex: pry)</li>
<li>:darwin/:linux/etc - gems specific to your particular OS (ex: growl) (might be improved at some point see https://github.com/carlhuda/bundler/issues/663)</li>
<li>:ci - gems for running continuous integration by automated build processes (ex: jslint)</li>
<li>:ct - gems for continuous testing workflow (ex: guard, autotest, etc)</li>
</ul>
<p><a href="https://gist.github.com/raw/2589028/a03f649b838fc9e4ecf93a3a239cac37d111e9da/Gemfile">An example annotated skeleton Gemfile is available in this Gist.</a></p>
<p>Adding these specialized bundler groups gives your app an instant boost in:</p>
<ul>
<li>Clarity - Each of these self describing groups will help avoid paralysis when you get 100+ gems in your app</li>
<li>Speed - I’ve personally seen a 500ms difference in application startup time for even a simple usecase. Every little bit helps!</li>
<li>Safety - Isolating non-prodution gems from your production environment.</li>
</ul>
<h2 id="putting-the-pieces-together">Putting the pieces together…</h2>
<p>Once you have grouped your gem dependencies, the next step is to ensure that the proper groups are loaded in the proper places.</p>
<h3 id="rails-application-config">Rails Application Config</h3>
<p>The Rails application.rb config file is used to declare which custom groups are loaded based on the current Rails environment (production, development or test). In our configuration, we want to ensure that the debug gems are loaded into our development and test environments.</p>
<h3 id="rack-appserver-config">Rack Appserver Config</h3>
<p>The appserver specific gems are autoloaded using the Rack config.ru configuration file by configuring the standard RAILS_GROUPS environment variable. It’s a simple and elegant solution.</p>
<h3 id="resque-background-job-config">Resque Background Job Config</h3>
<p>Autoloading gems into your background workers can also easily be done by passing the RAILS_GROUPS config to your resque workers.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ RAILS_GROUPS=worker QUEUES=* RAILS_ENV=production rake resque:work
</code></pre></div></div>
<h3 id="capistrano-deployment-config">Capistrano Deployment Config</h3>
<p>It’s important to make sure that these development and test gems are excluded from your production environment. It’s quite easy to tweak the Rails default capistrano deployment task to exclude additional custom groups</p>
<h2 id="versioning-best-practices">Versioning Best Practices</h2>
<p>When building your Gemfile, It’s important to lock down <strong>all</strong> production gems with a <strong>STRICT</strong> version requirement (ex: “1.0.0”). This prevents a careless developer from running “bundle update” and pulling in gems that are not fully tested. On the other hand, it is highly recommended to use a <strong>LOOSE</strong> version requirement for development and test gems to easily upgrade to the bleeding edge version (ex: “~> 1.0.0”).</p>
<p>A full list of all files referenced in this post can be found <a href="https://gist.github.com/2589028">in this Gist</a>. Comments and suggestions are always welcome!</p>
Rails console tweaks gem2012-03-24T00:00:00+00:00https://codecrate.com/2012/03/rails-console-tweaks-gem<p>Every developer toolbox has a certain set of tweaks for use in the Rails console.
There is <a href="http://stackoverflow.com/questions/4774847/rails-console-tips-tricks-and-customizations">no</a>
<a href="http://rors.org/2009/12/20/10-rails-console-tricks.html">shortage</a>
<a href="http://rors.org/2011/07/17/inline-logging-in-rails-console.html">of</a>
<a href="http://rbjl.net/49-railsrc-rails-console-snippets">blog</a>
<a href="http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb/">posts</a> for customizing your Rails console.
However, there is still a considerable gap in tooling to simplify the experience.
The Rails console tweaks gem is a solution to help you bootstrap a new app and get the best
default console experience right out of the box.</p>
<p>Just drop this gem into your Rails application Gemfile and watch the magic happen the next time you open your Rails console!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Gemfile</span>
<span class="n">gem</span> <span class="s1">'rails-console-tweaks'</span>
</code></pre></div></div>
<h1 id="sql-logging">SQL Logging</h1>
<p>By default, all SQL statements executed in the console will be logged to standard out. This is invaluable when debugging applications in order to inspect what SQL is being executed during an action.</p>
<h1 id="bundler-console-group">Bundler Console Group</h1>
<p>The Rails console tweaks gem autoloads any gems defined in the consolebundler group which makes it easy to plug in new fancy console tools as they are released. Creating a separate bundler group has the added benefit that these debugging tools will not be exposed to your standard production environment. Using custom bundler groups is slowly becoming a best practice for grouping related gems for several reasons such as: <a href="http://iain.nl/getting-the-most-out-of-bundler-groups">speed, safety, clarity</a>.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Gemfile</span>
<span class="n">gem</span> <span class="s1">'rails-console-tweaks'</span>
<span class="c1"># any gems in this group are only available</span>
<span class="c1"># within the rails console</span>
<span class="n">group</span> <span class="ss">:console</span> <span class="k">do</span>
<span class="n">gem</span> <span class="s1">'wirb'</span>
<span class="n">gem</span> <span class="s1">'hirb'</span>
<span class="n">gem</span> <span class="s1">'awesome_print'</span>
<span class="k">end</span>
</code></pre></div></div>
<h1 id="hirbwirb-integration-optional">HIRB/WIRB Integration (optional)</h1>
<p>If you use the HIRB or WIRB ruby gems in your application, the Rails console tweaks gem will auto-enable the gems to customize your console output.</p>
<p>The <a href="https://github.com/wireframe/rails-console-tweaks">Rails console tweaks</a> gem is 100% opensource and any comments or suggestions are welcome!</p>
callback_skipper for faster factories2011-11-28T00:00:00+00:00https://codecrate.com/2011/11/callbackskipper-for-faster-factories<p><a href="http://www.flickr.com/photos/brentbat/2137221211"></a></p>
<p>The Rails community has taken a strong stance that <a href="http://railscasts.com/episodes/158-factories-not-fixtures">test fixtures are evil and factories are the new hotness</a>. The most compelling reason for this shift being that factories greatly reduce maintance costs as your application grows over time.</p>
<p>The largest drawback when replacing fixtures with factories is the additional performance overhead when initializing your test state. This is due to the fact that factories utilize the full ActiveRecord lifecycle (initialize object, validate, save to database) compared to fixtures which are a glorified database bulk import which bypass object creation/validation.</p>
<p>Take this example ActiveRecord model and testcase (using <a href="https://github.com/thoughtbot/factory_girl">FactoryGirl</a> factories):</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Foo</span>
<span class="n">after_create</span> <span class="ss">:do_something_expensive</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">test_new_instance_has_bar</span>
<span class="n">foo</span> <span class="o">=</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">create</span> <span class="ss">:foo</span>
<span class="n">assert</span> <span class="n">foo</span><span class="p">.</span><span class="nf">bar?</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This is a classic example where using factories will be much slower than fixtures. It may not seem like a big deal, but it becomes a real issue when you have a sizable application testsuite, and I’m a firm believer that if a testsuite isn’t fast, it doesn’t get run.</p>
<p>Sending email with after_save callback is another great usecase. How can we get the benefits of factories without the additional overhead? Can we have our cake and eat it too?</p>
<p>Since 99% of our testcases rely on the basic factory instance and are not dependent upon the expensive callback being fired, it would be ideal to skip the expensive callback for most of your testcases and only fire it for testscases that are explicitly asserting it’s behavior.</p>
<p>The newly released <a href="https://github.com/wireframe/callback_skipper">callback_skipper gem</a> fulfills this exact usecase. The goal is to make it trivial to skip a particular model callback for a specific instance. This is a homerun for test factories to setup a default factory which skip non-critical callbacks and still have the flexibility to create a factory that _does_fire the slow-ass callbacks for specific tests.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># spec/factories/foo_factory.rb</span>
<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:foo</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span>
<span class="n">f</span><span class="p">.</span><span class="nf">after_build</span> <span class="k">do</span> <span class="o">|</span><span class="n">o</span><span class="o">|</span>
<span class="n">o</span><span class="p">.</span><span class="nf">skip_callback</span> <span class="ss">:save</span><span class="p">,</span> <span class="ss">:after</span><span class="p">,</span> <span class="ss">:do_something_expensive</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="no">Factory</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:foo_with_expensive_callback</span><span class="p">,</span> <span class="ss">:class</span> <span class="o">=></span> <span class="s1">'Foo'</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Oh yes, we <em>can</em> have our cake and eat it too…</p>
<p>The callback_skipper gem is equivalent to the core <a href="https://github.com/wireframe/callback_skipperhttp://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-skip_callback">ActiveRecord.skip_callback</a> method with the added benefit of only skipping the callback for a specific instance instead of globally for all invocations.</p>
<p>As always, the gem is 100% opensource and suggestions are welcome!</p>
Cron Backgrounded Resque Jobs2011-11-09T00:00:00+00:00https://codecrate.com/2011/11/cron-backgrounded-resque-jobs<p><a href="http://www.flickr.com/photos/jeremy-g/1512405671/"></a></p>
<p><a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html">Cron</a>is still the de facto standard when it comes to scheduling execution of jobs. It does one thing, and it does it well.</p>
<p>Using cron to fire off heavyweight Ruby/Rails jobs is fairly trivial to get up and running. When each cron job fires up a full Rails process, it won’t be long until you accrue enough jobs that your cron server will be brought to it’s knees. Since you already have a pool of <a href="http://github.com/defunkt/resque">Resque</a> background workers running to process async jobs, why not leverage dormant workers to process jobs that are kicked off via cron?</p>
<p>Here is a simple solution that can be used to have cron enqueue jobs into <a href="/2010/09/backgrounded-resque-support.html">Backgrounded Resque jobs</a> without loading the entire Rails environment.</p>
<p>This is an excellent optimization to increase the availability of your cron server and avoid running out of memory when multiple jobs fire up at the same time.</p>
<p>crontab invocation:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>script/backgrounded enqueue Foo.bar --queue baz
</code></pre></div></div>
<p><a href="https://gist.github.com/1351867">script/backgrounded</a>:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#!/usr/bin/env ruby</span>
<span class="nb">require</span> <span class="s1">'rubygems'</span>
<span class="nb">require</span> <span class="s1">'thor'</span>
<span class="k">module</span> <span class="nn">Backgrounded</span>
<span class="k">class</span> <span class="nc">CLI</span>
<span class="n">desc</span> <span class="s1">'enqueue'</span><span class="p">,</span> <span class="s1">'enqueue a clazz.method invocation for resque backgrounded workers'</span>
<span class="n">method_option</span> <span class="ss">:queue</span><span class="p">,</span> <span class="ss">:aliases</span> <span class="o">=></span> <span class="s2">"-q"</span><span class="p">,</span> <span class="ss">:desc</span> <span class="o">=></span> <span class="s2">"resque queue to enqueue the operation to"</span><span class="p">,</span> <span class="ss">:default</span> <span class="o">=></span> <span class="s1">'backgrounded'</span>
<span class="n">method_option</span> <span class="ss">:rails_env</span><span class="p">,</span> <span class="ss">:aliases</span> <span class="o">=></span> <span class="s1">'-e'</span><span class="p">,</span> <span class="ss">:desc</span> <span class="o">=></span> <span class="s1">'control which rails env used to load the redis config'</span><span class="p">,</span> <span class="ss">:default</span> <span class="o">=></span> <span class="s1">'production'</span>
<span class="c1"># operation Clazz.method to enqueue into resque backgrounded queue (ex: Foo.bar)</span>
<span class="k">def</span> <span class="nf">enqueue</span><span class="p">(</span><span class="n">operation</span><span class="p">)</span>
<span class="nb">require</span> <span class="s1">'bundler'</span>
<span class="no">Bundler</span><span class="p">.</span><span class="nf">setup</span>
<span class="nb">require</span> <span class="s2">"thread"</span>
<span class="nb">require</span> <span class="s2">"active_support/inflector"</span>
<span class="nb">require</span> <span class="s2">"resque"</span>
<span class="nb">require</span> <span class="s2">"yaml"</span>
<span class="n">clazz</span><span class="p">,</span> <span class="nb">method</span> <span class="o">=</span> <span class="n">operation</span><span class="p">.</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="s1">'.'</span><span class="p">)</span>
<span class="k">raise</span> <span class="s1">'invalid operation'</span> <span class="k">unless</span> <span class="n">clazz</span> <span class="o">&&</span> <span class="nb">method</span>
<span class="no">Resque</span><span class="p">.</span><span class="nf">redis</span> <span class="o">=</span> <span class="no">YAML</span><span class="p">.</span><span class="nf">load_file</span><span class="p">(</span><span class="no">File</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"config"</span><span class="p">,</span> <span class="s2">"resque.yml"</span><span class="p">))[</span><span class="n">options</span><span class="p">[</span><span class="ss">:rails_env</span><span class="p">]]</span>
<span class="no">Resque</span><span class="o">::</span><span class="no">Job</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span><span class="n">options</span><span class="p">[</span><span class="ss">:queue</span><span class="p">],</span> <span class="s1">'Backgrounded::Handler::ResqueHandler'</span><span class="p">,</span> <span class="n">clazz</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="nb">method</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="no">Backgrounded</span><span class="o">::</span><span class="no">CLI</span><span class="p">.</span><span class="nf">start</span>
</code></pre></div></div>
<p>Use cron for it’s excellent scheduling capabilities and take advantage of your background processing infrastructure to handle the incoming request!</p>
Cleaner RSpec/FactoryGirl Integration2011-10-04T00:00:00+00:00https://codecrate.com/2011/10/cleaner-rspecfactorygirl-integration<p><a href="http://www.flickr.com/photos/dawilson/3389046866/"></a></p>
<p>For the past few days, I’ve been re-thinking how to integrate <a href="https://github.com/thoughtbot/factory_girl">FactoryGirl</a> fixtures into my <a href="https://www.relishapp.com/rspec">RSpec</a> tests. The transition from Test::Unit to RSpec has taken me some time and I’m still “Unlearning what I have learned” and adapting to the RSpec way of doing things. It’s not that Test::Unit style tests are wrong, it just that I need to think a bit differently in order to take full advantage of the expressiveness of RSpec tests.</p>
<p>One common pattern for Rails application tests is to instantiate fixture data and perform assertions on the instances:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="no">User</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'basic user'</span> <span class="k">do</span>
<span class="n">before</span> <span class="k">do</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">create</span> <span class="ss">:user</span>
<span class="k">end</span>
<span class="n">it</span> <span class="p">{</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">should</span> <span class="n">be_inactive</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">should_not</span> <span class="n">be_happy</span> <span class="p">}</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>According to <a href="/2010/12/anatomy-of-effective-unit-test.html">The Anatomy of an Effective Unit Test</a>the before block in this example is playing the role of both fixture setup <em>and_test execution. The ambiguous definition of the beforemethod is analogous to how horrible it is to use API’s with incredibly useful methods such as run or execute. Sure, we know _when</em> the block is executed, but method names are key to understanding their purpose as well.</p>
<p>I’m a strong proponent of <a href="/2005/02/document-code-with-units-of-work.html">expressive method names</a> as a way to self document your code and that’s exactly what we need in this scenario. We need a clear and concise way to encapsulate our fixture data initialization outside of the before method and hook it into the RSpec test lifecycle. This will help remove the ambiguous purpose of the before method in this example.</p>
<p>Luckily, The RSpec DSL can be easily be extended. The new <a href="https://github.com/wireframe/factory_girl_rspec">factory_girl_rspec gem</a> adds the with method which is a seriously clean and concise DSL for initializing your fixtures:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="no">User</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'basic user'</span> <span class="k">do</span>
<span class="n">with</span> <span class="ss">:user</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">user</span><span class="p">.</span><span class="nf">should</span> <span class="n">be_inactive</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">user</span><span class="p">.</span><span class="nf">should_not</span> <span class="n">be_happy</span> <span class="p">}</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The with method is a simple utility that maps directly to the FactoryGirl fixtures that you have defined for your test environment. Each execution of with will create your fixture instance and define a local method within your test context retrieve the instance. Compare the readability of this test with the previous incarnation. It reads like a story right? Watch out <a href="http://cukes.info/">Cucumber</a>, who needs text processing stories when you’ve got human readable ruby code!</p>
<p>Deviations of fixture data are extremely common in unit tests as well, and the with method expresses differences in an equally concise manner:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="no">User</span> <span class="k">do</span>
<span class="n">context</span> <span class="s1">'user with first_name == "Jim"'</span> <span class="k">do</span>
<span class="n">with</span> <span class="ss">:user</span><span class="p">,</span> <span class="ss">:first_name</span> <span class="o">=></span> <span class="s2">"Jim"</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">user</span><span class="p">.</span><span class="nf">should</span> <span class="n">be_inactive</span> <span class="p">}</span>
<span class="n">it</span> <span class="p">{</span> <span class="n">user</span><span class="p">.</span><span class="nf">should</span> <span class="n">be_happy</span> <span class="p">}</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
Guard JSLint on Rails Released!2011-09-14T00:00:00+00:00https://codecrate.com/2011/09/guard-jslint-on-rails-released<p><a href="http://4.bp.blogspot.com/-87kA7x9PKz8/TnFuNzks7jI/AAAAAAAAADA/ihGp062mQu0/s1600/HolyGrail117_edit.jpg"></a></p>
<p>Continuous testing has changed my life and <a href="https://github.com/guard/guard">Guard</a> is top dog when it comes to continuous testing for Rails development. It’s simple, reliable and <a href="https://github.com/guard/guard/wiki/List-of-available-Guards">extremely easy to extend</a>. <a href="http://www.zenspider.com/ZSS/Products/ZenTest/">Autotest</a> and <a href="https://github.com/mynyml/watchr">Watchr</a> don’t hold a candle to Guard.</p>
<p>It is imperative when building Javascript heavy applications that you add <a href="http://jslint.com/">JSLint</a> to your workflow. The excellent <a href="https://github.com/psionides/jslint_on_rails">jslint-on-rails gem</a> makes it absolutely trivial, so if you haven’t done so already, do it now! (Don’t worry. I’ll wait for you. Seriously, it only takes a few minutes.)</p>
<p>Some people whine and complain that <a href="http://webreflection.blogspot.com/2010/02/jslint-bad-part.html">JSLint is evil</a> and there may be some legitimacy to that claim, but the simple fact is that JSLint has saved my ass more than once. Before JSLint, a single missing semicolon would take down an entire application for IE6/7 users, but ever since we’ve introduced JSLint into our development flow, we’ve had zero issues.</p>
<p>Integrating JSLint into your continuous testing flow is now possible with the new <a href="https://github.com/wireframe/guard-jslint-on-rails">guard-jslint-on-rails plugin</a>. Catch those pesky lint issues before you deploy to production. Catch them even before your continuous integration process runs. Heck, now you’ll catch them before you commit them to your version control repository!</p>
<h3 id="first-install-the-gem">First: install the gem…</h3>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gem install guard-jslint-on-rails
</code></pre></div></div>
<h3 id="next-configure-guard">Next: configure guard…</h3>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ guard init jslint-on-rails
</code></pre></div></div>
<p>And voila! Each time you tweak your Javascript files, your changes will be validated against your JSLint config!</p>
JSLint Rails Javascript Responses2011-06-27T00:00:00+00:00https://codecrate.com/2011/06/jslint-rails-javascript-responses<p>Unit testing Javascript has quickly become an absolute requirement for building a modern web application. It’s not uncommon for most web applications to have more Javascript code/libraries than serverside logic. There are plenty of frameworks javascript testing frameworks available for unit testing your standalone javascript components (<a href="http://www.jsunit.net/">JSUnit</a>, <a href="http://docs.jquery.com/Qunit">QUnit</a>, etc), but how do you test Javascript responses generated by Rails?</p>
<p>Let’s start by describing problem in a bit more detail. Here are a few snippits of code that you’ll find in pretty much any AJAX heavy Rails application.</p>
<p>Example Rails form for creating a new blog post via AJAX:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># app/views/blogs/new.html.haml</span>
<span class="o">=</span> <span class="n">form_for</span> <span class="no">Blog</span><span class="p">.</span><span class="nf">new</span><span class="p">,</span> <span class="ss">:remote</span> <span class="o">=></span> <span class="kp">true</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span>
<span class="err"> </span><span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="nf">text_area</span> <span class="ss">:body</span>
<span class="err"> </span><span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span>
</code></pre></div></div>
<p>Example Rails controller to create blog post:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># app/controllers/blog_controller.rb</span>
<span class="k">class</span> <span class="nc">BlogController</span> <span class="err"> </span><span class="k">def</span> <span class="nf">create</span>
<span class="err"> </span><span class="vi">@blog</span> <span class="o">=</span> <span class="no">Blog</span><span class="p">.</span><span class="nf">create</span> <span class="n">params</span><span class="p">[</span><span class="ss">:blog</span><span class="p">]</span>
<span class="err"> </span><span class="n">respond_with</span> <span class="vi">@blog</span>
<span class="err"> </span><span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Example Rails Javascript ERB response to return new blog post:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">#</span> <span class="nx">app</span><span class="o">/</span><span class="nx">views</span><span class="o">/</span><span class="nx">blogs</span><span class="o">/</span><span class="nx">create</span><span class="p">.</span><span class="nx">js</span><span class="p">.</span><span class="nx">erb</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">#new_blog_form</span><span class="dl">'</span><span class="p">).</span><span class="nx">trigger</span><span class="p">(</span><span class="dl">'</span><span class="s1">reset</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">body</span><span class="dl">'</span><span class="p">).</span><span class="nx">append</span><span class="p">(</span><span class="dl">'</span><span class="s1"><h2>New Blog Post has been created!</h2></span><span class="dl">'</span><span class="p">);</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">body</span><span class="dl">'</span><span class="p">).</span><span class="nx">append</span><span class="p">(</span><span class="dl">'</span><span class="s1"><div /></span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>
<p>Now this is a very simple example, but how can you effectively assert that the Javascript response is doing what you expect? Sure, you can use selenium or some other heavyweight testing library to boot up a browser and exercise your Javascript, but there’s got to be a quicker way to get the job done.</p>
<p>With a few simple solutions, you can get a lot of bang for your buck without introducing more complex and finicky end to end testing frameworks.</p>
<h2 id="move-javascript-logic-to-static-component">Move Javascript Logic to Static Component</h2>
<p>Refactoring your Javascript response to use the “Fat Component, Skinny Response” pattern is the <a href="http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model">same pattern we’ve been using for building our controllers</a>, and it moves all of the logic out of your ERB templates and into a standalone (and testable) Javascript component.</p>
<p>Example refactored Javascript response:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">#</span> <span class="nx">app</span><span class="o">/</span><span class="nx">views</span><span class="o">/</span><span class="nx">blogs</span><span class="o">/</span><span class="nx">create</span><span class="p">.</span><span class="nx">js</span><span class="p">.</span><span class="nx">erb</span>
<span class="nx">myApp</span><span class="p">.</span><span class="nx">createBlog</span><span class="p">();</span>
</code></pre></div></div>
<p>Example Javascript component:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">#</span> <span class="kr">public</span><span class="o">/</span><span class="nx">javascripts</span><span class="o">/</span><span class="nx">application</span><span class="p">.</span><span class="nx">js</span>
<span class="nx">myApp</span> <span class="o">=</span> <span class="p">{</span>
<span class="err"> </span><span class="na">createBlog</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="err"> </span><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">#new_blog_form</span><span class="dl">'</span><span class="p">).</span><span class="nx">trigger</span><span class="p">(</span><span class="dl">'</span><span class="s1">reset</span><span class="dl">'</span><span class="p">);</span>
<span class="err"> </span><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">body</span><span class="dl">'</span><span class="p">).</span><span class="nx">append</span><span class="p">(</span><span class="dl">'</span><span class="s1"><h2>New Blog Post has been created!</h2></span><span class="dl">'</span><span class="p">);</span>
<span class="err"> </span><span class="kd">var</span> <span class="nx">content</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">p</span><span class="dl">'</span><span class="p">).</span><span class="nx">text</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span>
<span class="err"> </span><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">body</span><span class="dl">'</span><span class="p">).</span><span class="nx">append</span><span class="p">(</span><span class="nx">content</span><span class="p">);</span>
<span class="err"> </span><span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>
<p>Now you can effectively unit test your component using traditional Javascript testing libraries.</p>
<h2 id="jslint-the-rails-response">JSLint the Rails Response</h2>
<p><a href="http://www.jslint.com/">JSLint</a> is a simple and very effective smoketest to ensure that any Javascript response is valid and without syntax errors. This prevents any extra semi-colons or simple syntax errors from breaking your user’s browser. All “modern” browsers are pretty forgiving when dealing with Javascript errors, but one browser in particular <em>cough</em> IE <em>cough</em> can really freak out if it encounters invalid Javascript</p>
<p>Rspec users can drop this <a href="https://gist.github.com/1042920">be_lintable helper</a> into there application for a quick sanity check that their JS responses should be operational. Not using RSpec? The <a href="https://github.com/psionides/jslint_on_rails">JSLint on Rails plugin</a> is pretty simple to integrate into any application.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">describe</span> <span class="s1">'xhr post :create'</span> <span class="k">do</span>
<span class="err"> </span><span class="n">before</span> <span class="p">{</span> <span class="n">xhr</span> <span class="ss">:post</span><span class="p">,</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:blog</span> <span class="o">=></span> <span class="p">{</span><span class="ss">:body</span> <span class="o">=></span> <span class="s1">'test'</span><span class="p">}</span> <span class="p">}</span>
<span class="err"> </span><span class="n">it</span> <span class="p">{</span> <span class="n">response</span><span class="p">.</span><span class="nf">body</span><span class="p">.</span><span class="nf">should</span> <span class="n">be_lintable</span> <span class="p">}</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Now go forth and test those Javascript Rails responses!</p>
Email Preview + Transactions and Factories2011-06-15T00:00:00+00:00https://codecrate.com/2011/06/email-preview-transactions-and<p><a href="http://www.flickr.com/photos/pacdog/4968422200/"></a></p>
<p>The <a href="http://github.com/wireframe/email_preview">email_preview</a> gem has undergone a serious overhaul in the last week. After some extensive real-world project use, a new version has been released with some major improvements.</p>
<h2 id="transactional-fixtures">Transactional Fixtures</h2>
<p>At a high level, email_preview fixtures are very similar in nature to Rails test fixtures. They are a snapshot of data with a particular configuration and are not intended to be long lived outside of the email_preview. The setup and teardown of previewed emails should follow the same setup/teardown of fixture data used during unit testing. Now each email_preview action is wrapped in a database transaction and rolled back after completion to avoid polluting your sandbox with unnecessary data!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># config/initializers/email_preview.rb</span>
<span class="no">EmailPreview</span><span class="p">.</span><span class="nf">register</span> <span class="s1">'User activation email'</span> <span class="k">do</span>
<span class="n">u</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create</span> <span class="ss">:email</span> <span class="o">=></span> <span class="s1">'foo@example.com'</span>
<span class="no">UserMailer</span><span class="p">.</span><span class="nf">activation</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>
<h2 id="factories">Factories</h2>
<p>Why duplicate the setup of fixture data when building your email preview templates? You already use a factory library for your unit tests right? The email_preview gem now works great with any factory framework you choose (<a href="https://github.com/thoughtbot/factory_girl">FactoryGirl</a>, <a href="https://github.com/notahat/machinist">Machinist</a>, etc).</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># config/initializers/email_preview.rb</span>
<span class="c1"># example FactoryGirl fixture</span>
<span class="no">EmailPreview</span><span class="p">.</span><span class="nf">register</span> <span class="s1">'User activation email'</span> <span class="k">do</span>
<span class="n">u</span> <span class="o">=</span> <span class="no">Factory</span><span class="p">.</span><span class="nf">create</span> <span class="ss">:user</span>
<span class="no">UserMailer</span><span class="p">.</span><span class="nf">activation</span> <span class="n">u</span>
<span class="k">end</span>
</code></pre></div></div>
<h2 id="categories">Categories</h2>
<p>Email is still a critical component of most web applications, and it’s very easy to rack up lots of templates when working with a large application. To help organize your fixtures, you can now use an optional :category option to group related fixtures.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># config/initializers/email_preview.rb</span>
<span class="no">EmailPreview</span><span class="p">.</span><span class="nf">register</span> <span class="s1">'User activation email'</span><span class="p">,</span> <span class="ss">:category</span> <span class="o">=></span> <span class="ss">:user</span> <span class="k">do</span>
<span class="n">u</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span> <span class="ss">:email</span> <span class="o">=></span> <span class="s1">'foo@example.com'</span>
<span class="no">UserMailer</span><span class="p">.</span><span class="nf">activation</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The email_preview UI received a considerable overhaul as well and any suggestions are greatly welcome. A solid update all around, and special thanks go to Lars Klevan for <a href="https://gist.github.com/1013155">inspiring</a> several of these updates!</p>
Realtime Search: Solr vs Elasticsearch2011-05-31T00:00:00+00:00https://codecrate.com/2011/05/realtime-search-solr-vs-elasticsearch<h2 id="who-will-win-the-crown-for-the-king-of-realtime-search">Who will win the crown for the King of Realtime Search?</h2>
<p>Oh the suspense! The results are available on the Socialcast Engineering blog…</p>
<p><a href="http://engineering.socialcast.com/2011/05/realtime-search-solr-vs-elasticsearch/">http://engineering.socialcast.com/2011/05/realtime-search-solr-vs-elasticsearch/</a></p>
Multitenant Ruby Gem2011-03-03T00:00:00+00:00https://codecrate.com/2011/03/multitenant-locking-down-your-app-and<p>Multitenant: locking down your app and making cross tenant data leaks a thing of the past…since 2011</p>
<p>Designing multi-tenant applications has increasingly becoming the norm for software developers. The benefits of building an application with a multi-tenant architecture are almost too many to list (cost savings, data mining, simplified operations, etc). But, let there be no doubt that building a multi-tenant application increases the overall complexity of the application.</p>
<p>The <a href="https://github.com/wireframe/multitenant">Multitenant gem</a> helps alleviate that complexity and ensures that all SQL queries executed adhere to the scoping of the current tenant. It works with any Rails3 compatible application without any modifications to your existing schema.</p>
<p>To configure, add the belongs_to_multitenant declaration to any model that has an association to a particular tenant. This will inject a new SQL scope into your model.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="n">belongs_to</span> <span class="ss">:tenant</span>
<span class="n">belongs_to_multitenant</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Now, all queries executed within the Multitenant.with_tenant block will automatically be scoped to the current tenant. No longer must you worry about a stray MyModel.all call exposing data to the wrong users! Also, any new records created within this block will automatically be associated to the current tenant. Another win for ensuring data separation!</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># use an Rails around_filter to setup this block</span>
<span class="no">Multitenant</span><span class="p">.</span><span class="nf">with_tenant</span> <span class="n">current_tenant</span> <span class="k">do</span>
<span class="c1"># queries within this block are automatically</span>
<span class="c1"># scoped to the current tenant</span>
<span class="no">User</span><span class="p">.</span><span class="nf">all</span>
<span class="c1"># records created within this block are</span>
<span class="c1"># automatically assigned to the current tenant</span>
<span class="no">User</span><span class="p">.</span><span class="nf">create</span> <span class="ss">:name</span> <span class="o">=></span> <span class="s1">'Bob'</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Unintentionally leaking data between tenants should be the NUMBER ONE concern when building multi-tenant apps and it surprises me how few resources are available to assist developers in building multi-tenant apps and ensuring data separation between tenants. So, if you’re building a multi-tenant Rails app, make sure the <a href="https://github.com/wireframe/multitenant">Multitenant gem</a> is in your toolbox!</p>
<p>Source code is 100% opensource and available on Github:</p>
<p><a href="https://github.com/wireframe/multitenant">https://github.com/wireframe/multitenant</a></p>
<p>Gem is available on rubygems:</p>
<p><a href="https://rubygems.org/gems/multitenant">https://rubygems.org/gems/multitenant</a></p>
Stay Connected with the ensure_connected gem2011-01-31T00:00:00+00:00https://codecrate.com/2011/01/stay-connected-with-ensureconnected-gem<p>This is your application when “MYSQL has gone away”</p>
<p>Most developers working with long running background processes will eventually run into the infamous “MySQL server has gone away” error. This error is thrown when the background processes are idle for an extended period of time and lose their active connection to the database.</p>
<p>There are a few <a href="http://gist.github.com/238999">workarounds</a> floating around the interwebs to deal with this exception, but the <a href="https://github.com/wireframe/ensure_connected">ensure_connected gem</a> is a clean and programmatic solution to take care of this issue once and for all.</p>
<p>The <a href="https://github.com/wireframe/ensure_connected">ensure_connected gem</a> wraps any method with a check to ensure that you are connected to the database before performing work.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Worker</span>
<span class="k">def</span> <span class="nf">do_something</span>
<span class="c1">#do your work here.</span>
<span class="c1">#you're connected to the database baby!</span>
<span class="k">end</span>
<span class="n">ensure_connected</span> <span class="ss">:do_something</span>
<span class="k">end</span>
</code></pre></div></div>
<p>And Resque users have it even better with the <a href="https://github.com/wireframe/resque-ensure-connected">resque-ensure-connected plugin</a>. Simply drop this gem into your project and all of your background job invocations will be wrapped with the ensure_connected check. This works with the Backgrounded Resque integration as well!</p>
<p>As always, sourcecode is 100% opensource and available on Github.</p>
<p><a href="https://github.com/wireframe/ensure_connected">https://github.com/wireframe/ensure_connected</a></p>
<p><a href="https://github.com/wireframe/resque-ensure-connected">https://github.com/wireframe/resque-ensure-connected</a></p>
<p>Gems are available for download through Gemcutter.</p>
Send Mail with Backgrounded Mail2011-01-18T00:00:00+00:00https://codecrate.com/2011/01/send-mail-with-backgrounded-mail<p><a href="http://1.bp.blogspot.com/_yocpuDtbm4c/TTZ3K2kg0MI/AAAAAAAAABc/2qB_m-gopNE/s1600/mailroom_sendmail.jpg"></a></p>
<p>This is what life was like before backgrounded_mail…</p>
<p>Don’t tie up your precious resources blocking on a synchronous call to sendmail or SMTP! Use the <a href="https://github.com/wireframe/backgrounded_mail">backgrounded_mail gem</a> to make your application more responsive and deliver email using your background processing library.</p>
<p>The background_mail API is very straightforward. Instead of invoking ‘deliver’ on the mail object, simply use the ‘deliver_backgrounded’ method to push the email into your background processing queue.</p>
<p>ex:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">UserNotifier</span><span class="p">.</span><span class="nf">welcome</span><span class="p">(</span><span class="n">user</span><span class="p">).</span><span class="nf">deliver_backgrounded</span>
</code></pre></div></div>
<p>The backgrounded_mail gem is compatible with Rails3 or any project using the <a href="https://github.com/mikel/mail">mail gem</a>. It is built on the world class <a href="https://github.com/wireframe/backgrounded">backgrounded library</a> to enqueue email delivery using your background processing library of choice (ex: resque, delayed job, workling, etc).</p>
<p>Sourcecode is available on Github.</p>
<p><a href="https://github.com/wireframe/backgrounded_mail">https://github.com/wireframe/backgrounded_mail</a></p>
The 3 E's of Engineering2011-01-14T00:00:00+00:00https://codecrate.com/2011/01/3-es-of-engineering<p>Anyone that calls themself an engineer knows “the look”. The one that strangers give when you first tell them that you’re a Software Engineer. The blank stare, the glazed eyes and the usual lame response about how smart, lucky or rich you must be.</p>
<p>I’ve had the great privilege over the years to train new developers and mentor developers of the future, and the most important event of someone’s first day is for me to burst that great big pink bubble and bring them back to reality.</p>
<p>Software development is hard. It’s equal parts art and science, and being a real engineer is anything but easy. Engineer has three e’s and every single engineer needs to master The 3 E’s of Engineering.</p>
<h2 id="estimate">Estimate</h2>
<p>A good software engineer needs to estimate tasks accurately. It takes a lot of practice and gets easier the more experience and domain knowledge you have with a given product or area of expertise.</p>
<p>Estimation is about giving a level of effort “guesstimate” for how difficult a task will be. An estimate should be stated in difficulty, not duration. Estimating using hours is an extremely common and <a href="http://scrum.jeffsutherland.com/2010/04/story-points-why-are-they-better-than.html">disastrous</a><a href="http://www.agilegamedevelopment.com/2006/03/hours-vs-story-points.html">mistake</a> and all estimates should be given in points or a it is as simple as stating a low, medium, or high level of effort for a given task.</p>
<p>An estimate is almost always resource agnostic meaning that if a task that is estimated as “difficult”, it will be difficult regardless of who actually does the work. For example, an experienced developer may be able to complete a difficult task quicker than a less experienced developer, but this is explained by each developer having a different personal velocity and does not change the fact that the task was labeled as “difficult”.</p>
<p>An estimate is an agreement for how difficult a task will be, but it is not a contract. It is not intended to answer, “How long will this take?” or “When will this be done?”. The estimate is only one part of the equation necessary for building an effective product roadmap and you need to understand all the other variables before you can see the whole picture (prioritization and resource allocation are the other critical components, but that topic is for another blog post!). :)</p>
<h2 id="evaluate">Evaluate</h2>
<p>A good software engineer needs to evaluate risk and more importantly to minimize unnecessary risk whenever possible. This is another area where practice and experience are the best ways to improve, but there are a few rules of thumb that should help every developer.</p>
<p>Be fluid, react quickly, and over-communicate changes or risks as they occur. If waterfall software development has taught me anything (other than how horribly broken it is), it is that you can never plan every aspect of a project before starting implementation. Even the best planned and estimated project will still encounter bumps along the way and need adjust accordingly. Over-communicating possible risks to the rest of your team and business is the perfect place for <a href="http://www.socialcast.com/">Socialcast</a>. Avoid excessive meetings and endless email threads when raising a red flag.</p>
<p>Use <a href="http://code.flickr.com/blog/2009/12/02/flipping-out/">feature flags</a> to roll out new features and test changes incrementally. Support turning on (and off) features at a granular level for an individual user or subset of users before going live for everyone.</p>
<p>Without monitoring, success is just a guess. How do you know that releasing a feature actually improved your product? How do you rollback a change if it negatively impacts your user experience?</p>
<p>Beware the word “re-write” and never ever listen to someone that says you need to “re-write and start over”. It’s a <a href="http://www.joelonsoftware.com/articles/fog0000000069.html">death sentence</a>.</p>
<p>If something doesn’t feel right, it probably isn’t. Put the breaks on when changes make the task no longer relevant. Failing fast is actually a huge success! Don’t linger on the time you’ve invested on something that get’s thrown away. Dwell on the time saved not finishing the irrelevant project.</p>
<h2 id="execute">Execute</h2>
<p>A good software engineer needs to execute and complete tasks quickly and efficiently. Excellence in this area boils down to following a few very simple rules.</p>
<p>Build the absolute simplest thing that could possibly work. No more. No less</p>
<p>It’s not done until it’s tested and if it’s not tested, it’s already broken (you just don’t know it yet).</p>
<p>Don’t check it off as complete until it’s in production. Minimize risk to get that shit done and out the door!</p>
Anatomy of an Effective Unit Test2010-12-08T00:00:00+00:00https://codecrate.com/2010/12/anatomy-of-effective-unit-test<p><a href="http://1.bp.blogspot.com/_yocpuDtbm4c/TQBR1QacfVI/AAAAAAAAABU/FqFtno1aIbE/s1600/doogietest.png"></a></p>
<p>Writing an effective and expressive unit test is just as important as writing clean application code. Unfortunately, there are not nearly enough resources for how to write good unit tests.</p>
<p>Dr. Sonnek is in the house today with a prescription. Let’s start by defining the “Anatomy of an Effective Unit Test”.</p>
<p>Every single unit test should be composed of 4 parts: Description, Setup, Execution, Assertion.</p>
<p>To be perfectly clear, I’m not encouraging writing complex unit tests in any way, shape or form. These 4 aspects of a unit test can, and should be, fulfilled in as few as 5 lines of code. Each testing library will have a slightly different feel, but the majority of old school testing frameworks rely on procedural execution or conventions to express these rules (JUnit, JSUnit, TestUnit, etc).</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#this is teh old school way to write tests</span>
<span class="c1">#test description</span>
<span class="k">def</span> <span class="nf">test_creating_blog_sends_email</span>
<span class="c1">#setup</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
<span class="c1">#execute</span>
<span class="n">blog</span> <span class="o">=</span> <span class="n">user</span><span class="p">.</span><span class="nf">blogs</span><span class="p">.</span><span class="nf">create!</span>
<span class="c1">#assert</span>
<span class="n">assert</span> <span class="no">Mail</span><span class="p">.</span><span class="nf">sent?</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Several modern testing frameworks have introduced a clearer separation between these important aspects and use structural separation between setup/execution and assertion which makes it easier to scan tests and read what they are trying to accomplish. Here’s a basic example, and I’ll break down each section afterwards.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#this is teh new hotness for writing tests</span>
<span class="c1">#describe the execution context (data, environment, etc)</span>
<span class="n">context</span> <span class="s2">"creating blog post with new user"</span> <span class="k">do</span>
<span class="n">setup</span> <span class="k">do</span>
<span class="c1">#setup</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">create!</span>
<span class="c1">#execute</span>
<span class="n">blog</span> <span class="o">=</span> <span class="n">user</span><span class="p">.</span><span class="nf">blogs</span><span class="p">.</span><span class="nf">create!</span>
<span class="k">end</span>
<span class="c1">#assert</span>
<span class="n">should</span> <span class="s1">'send email to author'</span> <span class="k">do</span>
<span class="n">assert</span> <span class="no">Mail</span><span class="p">.</span><span class="nf">sent?</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>I’ll use shoulda syntax for these examples, but the same principles apply to RSpec, JSspec, etc. Now, let’s dive into the Anatomy of an Effective Unit Test…</p>
<h3 id="description">Description</h3>
<p>Separating the setup/execution/assertions into separate blocks creates self documenting and highly readable tests. The “description” component for each part of your test (setup, execute, assertion) is used to construct a sentence for your test. This is a welcome change from the uglified test naming convention used by legacy test frameworks. The previous example would read:</p>
<p>“creating blog post with new user should send email to author”</p>
<h3 id="setup">Setup</h3>
<p>Test setup is used to initialize environmental or data dependencies before execution and assertion. The description for your setup block should clearly describe these dependencies.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">context</span> <span class="s2">"with new user"</span> <span class="k">do</span>
<span class="n">setup</span> <span class="k">do</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h3 id="execute">Execute</h3>
<p>Execution is just another form of setup, and lives alongside other environmental or data setup. The description for your execution context should match the method you are invoking and what parameters are being used for this particular invocation.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">context</span> <span class="s2">"creating blog"</span> <span class="k">do</span>
<span class="n">setup</span> <span class="k">do</span>
<span class="n">blog</span> <span class="o">=</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">blogs</span><span class="p">.</span><span class="nf">create!</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<h3 id="assert">Assert</h3>
<p>One assertion per test. No more…no less. Old school unit tests very commonly have multiple assertions per test but Shoulda makes it super simple to encapsulate each assertion and re-use common setup/execution contexts.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">should</span> <span class="s1">'send email to author'</span> <span class="k">do</span>
<span class="n">assert</span> <span class="no">Mail</span><span class="p">.</span><span class="nf">sent?</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Writing effective unit tests is never easy, but structuring your unit tests correctly and understanding the importance of each aspect should make your job just a little bit easier.</p>
Backgrounded Class Methods2010-10-30T00:00:00+00:00https://codecrate.com/2010/10/stay-class-y-backgrounded-backgrounded<h2 id="stay-class-y-backgrounded">Stay “Class-y” Backgrounded!</h2>
<p>Backgrounded was originally intended to only run ActiveRecord instance methods in the background but as the library has matured, its focus has broadened into an <strong>elegant proxy to arbitrary background processors</strong>.</p>
<p>There are lots of usecases where it’s necessary to run a background method on a non-ActiveRecord instance, and the latest Backgrounded release now supports running any class level method with backgrounded! All out of the box back-ends have been updated to respect this new configuration.</p>
<p>Backgrounded class methods work exactly the same as instance methods and there are no client API changes required to use them. Just reference your class level method with a class level backgrounded declaration and you’re all set.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>class User
class << self
backgrounded :my_instance_method
def my_instance_method
end
end
end
#run the instance method in the background
=> User.my_instance_method_backgrounded
</code></pre></div></div>
<p>Sourcecode on Github.</p>
<p><a href="http://github.com/wireframe/backgrounded">http://github.com/wireframe/backgrounded</a></p>
<p>Latest gem on Gemcutter.</p>
<p><a href="https://rubygems.org/gems/backgrounded">https://rubygems.org/gems/backgrounded</a></p>
New Relic + Backgrounded + Resque = Awesome2010-10-14T00:00:00+00:00https://codecrate.com/2010/10/new-relic-backgrounded-resque-awesome<p>If you’re writing a rails app, you’re already using new relic to monitor your app right? Wouldn’t it be great to get the same performance monitoring of your Backgrounded operations as well?</p>
<p>Fork it up, now you can!</p>
<p>I’ve published a fork of the rpm_contrib gem that will automatically instrument and monitor your Backgrounded operations with absolutely <strong>no</strong> code changes! That’s right, all you need to do is include the wireframe-rpm_contrib gem and your Backgrounded Resque tasks will automatically be tracked!</p>
<p>Sourcecode available on github (fork of <a href="http://github.com/newrelic/rpm_contrib">rpm_contrib</a>):</p>
<p><a href="http://github.com/wireframe/rpm_contrib">http://github.com/wireframe/rpm_contrib</a></p>
<p>Gem available on gemcutter:</p>
<p><a href="https://rubygems.org/gems/wireframe-rpm_contrib">https://rubygems.org/gems/wireframe-rpm_contrib</a></p>
<p>The default rpm_contrib gem adds instrumentation for Resque jobs, but is not aware of Backgrounded jobs so all of the jobs were recorded as Backgrounded::Handler::ResqueHandler#perform. My little patch fixes that so that Backgrounded Resque jobs have the correct classname/method context.</p>
Advanced Backgrounded Configuration2010-10-11T00:00:00+00:00https://codecrate.com/2010/10/advanced-backgrounded-configuration<h3 id="mr-sparkle-says-wow-backgrounded-is-super-terrific-loose-translation">Mr. Sparkle says, “Wow! Backgrounded is super terrific!” (loose translation)</h3>
<p>In the wake of the backgrounded ruby gem release, only two complaints have been raised about the library…</p>
<p>First: the backgrounded API is just too damn intuitive. It is literally so beautiful that every other background processing API feels like a giant turd. Using backgrounded abstracts implementation details between various frameworks so developers can focus on writing kick ass apps. Sorry folks, but I have no intention of fixing this issue. :)</p>
<p>Second: The elegance and simplicity of the backgrounded abstraction has proven too limiting for developers that need greater control ‘under the hood’. The 0.6.0 release of backgrounded should satisfy these power hungary devs by supporting an optional configuration hash for each backgrounded method. Any options specified in your backgrounded class will be passed through to tweak the specific background processing handler in use.</p>
<p>The first backgrounded handler to honor the optional configuration is the <a href="/2010/09/backgrounded-resque-support.html">Resque integration</a> which now supports configuration of the particular queue the backgrounded method will be run in. The default behavior is to run all backgrounded methods in a single default queue (named backgrounded) and this can be overridden by passing in the optional :queue name for any backgrounded method.</p>
<p>It is vitally important that the introduction of these advanced configuration options not break the existing API. The beauty and simplicity of the original backgrounded API is still very much intact and all existing clients will continue with the default behavior with no change. Here’s an example to show how the original backgrounded methods can be configured right alongside with advanced backgrounded methods.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Blog</span>
<span class="n">backgrounded</span> <span class="n">save_to_filesystem</span><span class="p">,</span> <span class="ss">:email_followers</span> <span class="o">=></span> <span class="p">{</span><span class="ss">:queue</span> <span class="o">=></span> <span class="ss">:low</span><span class="p">}</span>
<span class="k">def</span> <span class="nf">email_followers</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">save_to_filesystem</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Sourcecode on Github.</p>
<p><a href="http://github.com/wireframe/backgrounded">http://github.com/wireframe/backgrounded</a></p>
<p>Latest gem on Gemcutter.</p>
<p><a href="https://rubygems.org/gems/backgrounded">https://rubygems.org/gems/backgrounded</a></p>
Backgrounded Resque Support2010-09-27T00:00:00+00:00https://codecrate.com/2010/09/backgrounded-resque-support<p><a href="http://www.flickr.com/photos/stark23x/55575164/"></a></p>
<p>After an extended rest, Backgrounded is back in action with support for Resque.</p>
<p><a href="http://github.com/defunkt/resque">Resque</a> is one of the newer background processing frameworks for ruby applications created by the amazing folks at Github. A weekend of hacking with Resque easily persuaded me to add official support for Resque to the Backgrounded 0.4.1 release.</p>
<p>After getting Resque up and running, the Backgrounded configuration is simple (as always).</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#config/initializers/backgrounded.rb
require 'backgrounded/handler/resque_handler'
Backgrounded.handler = Backgrounded::Handler::ResqueHandler.new
</code></pre></div></div>
<p>The benefits of Backgrounded really shine when new libraries like Resque pop up. One of the primary goals of Backgrounded is to make it trivial to swap out different backend implementations and not change a single line of your application code. Just update your configuration file and restart. It’s a thing of beauty…</p>
<p>Sourcecode on Github.</p>
<p><a href="http://github.com/wireframe/backgrounded">http://github.com/wireframe/backgrounded</a></p>
<p>Latest gem on Gemcutter.</p>
<p><a href="https://rubygems.org/gems/backgrounded">https://rubygems.org/gems/backgrounded</a></p>
email_preview Rails Plugin2010-06-09T00:00:00+00:00https://codecrate.com/2010/06/emailpreview-rails-plugin<p>As a developer, working with email pretty much sucks. Crafting emails is a time consuming task where you constantly refine and tweak markup to get the <strong>perfect</strong> layout for your message. Heck, it’s easier to do cross browser testing of your application for IE6!</p>
<p>The email_preview engine is a new Rails 3 plugin I’ve released to help developers build kick ass emails for your Rails 3 app. It provides a quick and easy way to preview sample emails from within your web browser and see how they will look in the end user’s email client.</p>
<p>The developer API is extremely simple. You can use the standard Rails ActionMailer interface to configure each instance, or manually configure each email using the excellent <a href="http://github.com/mikel/mail">mail library</a>.</p>
<p>#config/email_preview.rb</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">EmailPreview</span><span class="p">.</span><span class="nf">register</span> <span class="s1">'user activation email'</span> <span class="k">do</span>
<span class="n">u</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span> <span class="ss">:email</span> <span class="o">=></span> <span class="s1">'foo@example.com'</span>
<span class="no">UserNotifier</span><span class="p">.</span><span class="nf">activation</span>
<span class="k">end</span>
<span class="no">EmailPreview</span><span class="p">.</span><span class="nf">register</span> <span class="s1">'simple example email'</span> <span class="k">do</span>
<span class="no">Mail</span><span class="p">.</span><span class="nf">new</span> <span class="k">do</span>
<span class="n">to</span> <span class="s1">'tom@example.com'</span>
<span class="n">from</span> <span class="s1">'me@foo.com'</span>
<span class="n">body</span> <span class="s1">'check this out'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="no">EmailPreview</span><span class="p">.</span><span class="nf">register</span> <span class="s1">'multipart email (html + text)'</span> <span class="k">do</span>
<span class="no">Mail</span><span class="p">.</span><span class="nf">new</span> <span class="k">do</span>
<span class="n">from</span> <span class="s1">'mikel@test.lindsaar.net'</span>
<span class="n">to</span> <span class="s1">'you@test.lindsaar.net'</span>
<span class="n">subject</span> <span class="s1">'This is a test email'</span>
<span class="n">text_part</span> <span class="k">do</span>
<span class="n">body</span> <span class="s1">'This is plain text'</span>
<span class="k">end</span>
<span class="n">html_part</span> <span class="k">do</span>
<span class="n">content_type</span> <span class="s1">'text/html; charset=UTF-8'</span>
<span class="n">body</span> <span class="s1">'<h1>this is HTML</h1>'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Once you’ve configuring your sample emails, startup your Rails 3 application and preview them in any web browser at <a href="http://localhost:3000/email_preview">http://localhost:3000/email_preview</a>. All email templates are re-rendered with each request so you can tweak/save/refresh to instantly preview how your emails will look for your users. Talk about quick turnaround time!</p>
<p>Need more assurance that your emails will look correct? If your dev environment is configured to send emails, you can send any of your email previews to your inbox by filling out the convenient form at the top of each page.</p>
<p>This plugin is 100% opensource and the code is available on github at <a href="http://github.com/wireframe/email_preview">http://github.com/wireframe/email_preview</a>. Patches are <em>always</em> welcome, and if you have any questions or suggestions, please drop me a line.</p>
Zillow Google Chrome Extension2010-03-22T00:00:00+00:00https://codecrate.com/2010/03/zillow-google-chrome-extension<p>Incase you haven’t heard, <a href="/2010/02/mailinator-google-chrome-extension.html">I love</a>
<a href="/2009/12/delicious-google-chrome-extension.html">me some</a> Google Chrome extensions.
And now <a href="https://chrome.google.com/extensions/detail/hpfpmhoefhblnbnipeapenjojpcbifpo/">the Zillow Google Chrome extension</a> just made looking for a new house a heck of a lot easier.</p>
<p>Grab an address, pop open the Zillow Google Chrome extension and find the estimated property value in no time!</p>
<p>The Zillow Google Chrome extension is a mashup using
<a href="http://code.google.com/apis/maps/documentation/v3/introduction.html">the Google Maps API</a> and
<a href="http://www.zillow.com/howto/api/GetZestimate.htm">the Zillow API</a> to quickly find
as much detail about a property while avoiding the cluttered and slow ass real-estate websites.
Consider this the “official” successor to my
<a href="/2009/03/zillow-ubiquity-plugin_04.html">original Zillow Ubiquity plugin</a>.
Ubiquity was cool but this extension is the cat’s meow!</p>
<p>The Zillow Google Chrome extension shows the estimated property value along with the estimated high/low range value. A direct link to the detailed estimate on Zillow is also available if you want more information about the property.</p>
<p>The property location is displayed with an embedded Google map along with a direct link to a full property map to dive into the street view (on Google Maps of course). Using Google’s geolocation service also makes it possible to quickly find a location even if you don’t know the full address!</p>
<p>The <a href="http://github.com/wireframe/zillow-chrome-extension">code is 100% opensource and available on github</a> and here are a few ideas for future improvements. fork away!</p>
<ul>
<li>an extension browser action could detect when the user selects an address on the page</li>
<li>prefill the popup address based on the user selected address on the page</li>
<li>hovering over address could display an inline popup bubble with the estimate information</li>
</ul>
Rails "Good Touch"/"Bad Touch"2010-03-12T00:00:00+00:00https://codecrate.com/2010/03/rails-good-touchbad-touch<p>Rails is bit like a dirty old man.</p>
<p>Consider this example</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span> <span class="err"> </span>
<span class="n">after_save</span> <span class="ss">:do_something_expensive</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Rails makes it trivial to update timestamps, and I found out the hard way that the underlying implementation leaves a lot to be desired.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">User</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">touch</span>
</code></pre></div></div>
<p>Easy, right? But, did you know that this useful little method will fire all of your after_save callbacks? This led to some nasty performance problems recently, and now you can now stop Rails from having it’s way with you! Bad Touch Rails!</p>
<p>The good_touch project is now available on <a href="http://github.com/wireframe/good_touch">github</a> and <a href="http://rubygems.org/gems/good_touch">gemcutter</a> and eliminates the overhead for updating a simple timestamp attribute. It’s as easy as using the standard/bad touch method without all the horseplay.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">User</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">good_touch</span>
</code></pre></div></div>
<p>Let the touching continue…</p>
Improvements for apn_on_rails2010-02-08T00:00:00+00:00https://codecrate.com/2010/02/improvements-for-apnonrails<p>If you’re using Rails and integrate with Apple Push Notifications, you are more than likely familiar with the <a href="http://github.com/markbates/apn_on_rails">apn_on_rails gem</a>. It’s a fantastic library and has been critical for getting off the ground with push notifications quickly. The project is <a href="http://www.metabates.com/2009/12/21/apn-on-rails-needs-a-home/">currently in flux</a> and has been missing some critical features, so I decided to dig into the source myself and hack away.</p>
<p>Using <a href="http://developer.apple.com/IPhone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW15">custom metadata to each push notification</a> was needed right off the bat. Basic push notifications support a “badge”, “alert”, and “sound”, but custom attributes can be used to push metadata that would be useful for your native application. The original apn_on_rails plugin does not support custom attributes, but after building on the <a href="http://github.com/lmarburger/apn_on_rails">work done by lmarburger</a>, custom payload attributes are working great.</p>
<p>Truncation of alert text is another critical feature that needed some love. Apple limits push notifications to a maximum of 255 characters which includes the alert text and all custom attributes so it is very important to optimize the data you’re sending down and not go over the 255 character limit. The initial gem used a very simple implementation for truncating the text, which worked fine until you started to push custom attributes as well. Those valuable characters got eaten up in a hurry and the truncation of the alert text needed to be aware of your entire payload length.</p>
<p>With a few hours of work, the entire truncation algorithm has been rewritten (with tests) and is working great. This new algorithm will dynamically truncate your alert text based on your entire payload body. This is a much better algorithm for text truncation and I’ve seen a 20% increase in the amount of text sent with push alerts before the truncation kicks in (average from 179 to 215 characters).</p>
<p>I also fixed a pretty major bug when truncating notifications with multibyte characters. Anyone using apn_on_rails for an internationalized app should definitely consider the update.</p>
<p>My fork of the original apn_on_rails gem is available <a href="http://github.com/wireframe/apn_on_rails">on github</a> and the updated gem is published and available <a href="http://gemcutter.org/gems/wireframe-apn_on_rails">on gemcutter</a>.</p>
Mailinator Google Chrome Extension2010-02-07T00:00:00+00:00https://codecrate.com/2010/02/mailinator-google-chrome-extension<p>Have you ever visited a website that required an email registration form, but you really didn’t want to give out your primary email address? <a href="http://www.mailinator.com/">Mailinator</a> is a wonderful service that helps rid the world of junk mail, one garbage email address at a time.</p>
<p>Using a one-time use email inbox is a great way to keep unsolicited email out of your way. And now the <a href="https://chrome.google.com/extensions/detail/bcnflfkionidoobcineimfoollmbalbp">Mailinator Google Chrome extension</a> makes it even easier to generate a one-time email address to get you through those annoying site registration forms.</p>
<p>Features include:</p>
<ul>
<li>one click generation of a random email address</li>
<li>popup widget to check your mailinator email inbox</li>
</ul>
<p>Under the covers, the plugin is very simple. Mailinator provides a pretty decent <a href="http://www.mailinator.com/widgetmaker.jsp">iframe integration</a> out of the box, and generating a <a href="http://www.broofa.com/Tools/Math.uuid.js">random email inbox in Javascript</a> is pretty trivial.</p>
<p>The code is <a href="http://github.com/wireframe/mailinator-chrome-extension">100% open source and available on github</a>. I’d love to add in a “Copy address to clipboard” feature, but it <a href="http://stackoverflow.com/questions/127040/put-text-on-the-clipboard-with-firefox-safari-and-chrome">looks like Flash is the only way to accomplish that</a>. Let me know if you have any other suggestions.</p>
<p>I have no affiliation with Mailinator. I’m just a hacker that is very sick of sites requiring email addresses and not offering open ID integration. :)</p>
#airfail for HTML Developers2010-01-10T00:00:00+00:00https://codecrate.com/2010/01/airfail-for-html-developers<p><a href="http://amplicate.com/sucks/adobe-air">Opinions on ADOBE AIR</a></p>
<p>Incase you haven’t heard, <a href="/2009/08/end-of-adobe-air.html">Adobe AIR is a complete and utter failure for developing desktop applications with HTML/CSS/Javascript technologies</a>.
It’s primary purpose is to provide Flash/Flex developers the ability to exploit the desktop.
It’s secondary purpose is to simply frustrate and antagonize HTML/CSS developers past the point of frustration.</p>
<p>Here is a short list of the very real issues I’ve encountered while building and deploying AIR applications. This is not simply a list of problems dug up from an issue tracker or forum. Every one is an issue I’ve worked through to the point of pulling my hair out. This list should serve as a warning to any potential developers considering Adobe AIR. You’ll regret it…mark my words. The fact that Adobe advertises AIR as a viable runtime for HTML/CSS developers is one of the greatest crimes against humanity I have witnessed in recent history.</p>
<p>No HTTP Headers sent with file uploads</p>
<p>Dealing with HTTP headers is an extremely standard requirement especially when working with secured services that require Basic Authentication. The AIR SDK has fairly well documented methods to configure sending HTTP headers with outgoing requests, BUT for some reason <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7cb2.html">the SDK fine print states that “custom HTTP request headers are not supported in uploads or downloads”</a>. Excuse me? You’re kidding right? Multipart HTTP multipart headers are already being sent with file uploads so why the hell prevent other headers from being added? Why support HTTP headers for every remote request except for file uploads? The AIR SDK gives you direct access to a Socket for God’s sake. Do I have to write my own fucking multipart upload?</p>
<p>Every single application that relies on Flash technology, which includes web based SWF projects as well as HTML and Flex AIR apps, suffer from this bug. This blatant hole is yet another reason Flash will be dead as soon as HTML5 is more widely adopted.</p>
<p>random “corrupt” installation file</p>
<p>Try to install an app and <a href="http://www.bryanbartow.com/wp-content/uploads/2008/06/capture-1.png">receive a “corrupt file” error</a>. reinstall the app and it works fine. Awesome. Our QA team has encountered this issue frequently enough that it’s become standard issue to just ignore the errors.</p>
<h3 id="integration-with-native-os-or-lack-there-of">Integration with Native OS (Or lack there of)</h3>
<p>AIR offers so little integration with “native” features, that it’s hard to call out any particular failures and I guess that’s one of my biggest gripes with AIR. If you’re building a runtime for desktop applications, having integration with the native desktop OS is a pretty necessary and compelling feature.</p>
<p>No Integration with Native Notification Systems</p>
<p>Adobe supposedly was working on this <a href="http://www.mikechambers.com/blog/2008/11/13/growl-support-for-adobe-air-applications/">back in 2008</a>. Seriously? It takes two years to integrate with one of the most standard core features provided by modern day operating systems? Growl has been around on Mac for years. Linux has libnotify and Windows has Snarl. Titanium has had this built into their SDK since practically day one.</p>
<p>Sure, you can <a href="http://github.com/wireframe/growl-air">emulate these notifications with AIR</a>, but it is such a horrible, horrible hack and forces every single app to reinvent the wheel.</p>
<p>no integration with dock icons</p>
<p>most commonly used on Mac, but applicable to other platforms as well. Fluid is a perfect example of exposing a simple api to control dock icons. This is a minor issue and not directly a “bug” but this came up frequently in our business requirements and AIR was unable to perform the expected task.</p>
<p>sharing cookies with browser</p>
<p>This is just plain disgusting. Why in the world would you build a runtime that is <a href="http://www.12robots.com/index.cfm/2009/9/22/AIR-Tip-Cookie-Sharing">coupled to the underlying OS session/cookie management system</a>? This extremely unexpected behavior which has cost me tons of troubleshooting time where a user could log into a site using their web browser and essentially “hijack” the credentials of the AIR application.</p>
<p>Window Handcuffs</p>
<p>The AIR windowing API is clunky and frustrating pile. Not only that, but it also is broken.</p>
<ul>
<li><a href="/2009/12/air-lightweight-windows-steal-focus-by.html">lightweight windows stealing window focus</a></li>
<li>hidden application windows on OSX will be activated and focused when receiving popup notification. (blog post coming soon)</li>
</ul>
<p>No global mouse move events</p>
<p>With no way to detect mouse pointer location when outside of your application, it is absolutely impossible for you to build headless applications that listen and react to mouse gestures.</p>
<h3 id="crippled-webkit">Crippled Webkit</h3>
<p>Webkit is an extremely fast moving project. There are new features being added every day, and when Adobe chose to include Webkit into their runtime, I’d expect them to <a href="http://stackoverflow.com/questions/1569541/what-version-of-webkit-does-adobe-air-use">include info on the version of Webkit that is included</a>. Is CSS3 available? is HTML5 available? Well, it’s up to the developer to find out with good old trial and error. Here are some of the more “common” things I was unable to do with the specific version of webkit included in AIR 1.5.</p>
<ul>
<li>doesn’t support webkit custom scrollbars</li>
<li>Sporadic support for HTML5 attributes. placeholder attribute available for text input, but not textarea</li>
<li>doesn’t support title attribute for very standard browser tooltips.</li>
</ul>
<p>I consider these Adobe’s issues because the version of Webkit included in the AIR runtime is ridiculously out of date. I’ve been implementing these features in actual web apps for nearly a year now (and there’s no reason the title attribute doesn’t work). AIR2 will <a href="http://labs.adobe.com/wiki/index.php/AIR_2:Release_Notes#New%5FFeatures%5Fin%5FAIR%5F2">“supposedly” be updating it’s version of Webkit</a>, but I highly doubt that Adobe will be smart enough to provide reference documentation for developers to know what features are available.</p>
<h3 id="cross-platform-issues">Cross Platform Issues</h3>
<p>No multiplatform runtime is perfect, but web browsers are by far the best technology available to provide a consistent cross platform experience. Webkit was an excellent starting point for AIR, but the underlying runtime has plenty of cross platform issues. Here are some of the major issues I’ve run into</p>
<p>Windows</p>
<ul>
<li><a href="http://forums.adobe.com/thread/469531?tstart=0">Antialiasing causes purple text</a></li>
<li><a href="http://forums.adobe.com/thread/525228">System alerts for Unknown/untrusted certificates</a></li>
<li><a href="http://forums.adobe.com/thread/462791">autoupdate causes process process to hang on windows</a></li>
</ul>
<p>Linux</p>
<ul>
<li><a href="http://forums.adobe.com/thread/525225">Images hosted on SSL CDN cause system alerts</a></li>
</ul>
<p>Mac</p>
<ul>
<li><a href="http://forums.adobe.com/thread/529807">Keychain prompts for PrivateEncryptedData</a></li>
</ul>
<h3 id="performance">Performance</h3>
<p>I’m very aware that there is a cost to run an application in a runtime environment. I’ve built Java applications for years and had to deal with the memory bloat for apps running in a Java runtime, but I don’t think I’m asking a lot here.</p>
<p>The majority of AIR applications are mashup/widgets that are intended to be always on background services, but nearly every AIR application sits idle at ~10% CPU on a dual core Macbook Pro. It’s simply ridiculous and again all fingers point to the underlying flash runtime. One common trick is to <a href="http://www.gskinner.com/blog/archives/2009/05/idle_cpu_usage.html">manually override the flash framerate</a> to improve performance. It’s pretty ridiculous that the runtime isn’t smart enough to handle this when your application is minimized or otherwise hidden.</p>
AIR Lightweight Windows Steal Focus By Default2009-12-23T00:00:00+00:00https://codecrate.com/2009/12/air-lightweight-windows-steal-focus-by<p>Lightweight windows are intended for AIR applications to show simple popup windows and notifications (like my <a href="http://github.com/wireframe/growl-air">emulated growl notification system</a>). This is pretty standard stuff and there are a number of <a href="http://articles.sitepoint.com/article/html-based-adobe-air">documented tutorials</a> and examples that go over this.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">options</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">air</span><span class="p">.</span><span class="nx">NativeWindowInitOptions</span><span class="p">();</span>
<span class="nx">options</span><span class="p">.</span><span class="nx">type</span> <span class="o">=</span> <span class="nx">air</span><span class="p">.</span><span class="nx">NativeWindowType</span><span class="p">.</span><span class="nx">LIGHTWEIGHT</span><span class="p">;</span>
<span class="nx">options</span><span class="p">.</span><span class="nx">systemChrome</span> <span class="o">=</span> <span class="nx">air</span><span class="p">.</span><span class="nx">NativeWindowSystemChrome</span><span class="p">.</span><span class="nx">NONE</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">visible</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">scrollbars</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">bounds</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">air</span><span class="p">.</span><span class="nx">Rectangle</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="mi">250</span><span class="p">,</span> <span class="mi">300</span><span class="p">,</span> <span class="mi">400</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">htmlLoader</span> <span class="o">=</span> <span class="nx">air</span><span class="p">.</span><span class="nx">HTMLLoader</span><span class="p">.</span><span class="nx">createRootWindow</span><span class="p">(</span><span class="nx">visible</span><span class="p">,</span> <span class="nx">options</span><span class="p">,</span> <span class="nx">scrollbars</span><span class="p">,</span> <span class="nx">bounds</span><span class="p">);</span>
<span class="nx">htmlLoader</span><span class="p">.</span><span class="nb">window</span><span class="p">.</span><span class="nx">nativeWindow</span><span class="p">.</span><span class="nx">alwaysInFront</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="nx">htmlLoader</span><span class="p">.</span><span class="nx">load</span><span class="p">(</span><span class="k">new</span> <span class="nx">air</span><span class="p">.</span><span class="nx">URLRequest</span><span class="p">(</span><span class="dl">"</span><span class="s2">myfile.html</span><span class="dl">"</span><span class="p">));</span>
</code></pre></div></div>
<p>Executing this simple example will show one very odd and obvious interaction issue. Your supposedly “lightweight” window will steal the focus from your main application window. Huh, that doesn’t seem very lightweight to me. </p>
<p>The issue is that any window that is created with “visible” set to “true” will automatically be activated once content is loaded. What a nice little gotcha. Thanks for the info Adobe!</p>
<p>In order to work around this issue and get your lightweight window to behave as expected, you need to initialize it to hidden and then flip it to visible after the content is loaded using a completely unnecessary extra event listener.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">htmlLoader</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="nx">air</span><span class="p">.</span><span class="nx">Event</span><span class="p">.</span><span class="nx">COMPLETE</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="err"> </span><span class="nx">htmlLoader</span><span class="p">.</span><span class="nb">window</span><span class="p">.</span><span class="nx">nativeWindow</span><span class="p">.</span><span class="nx">visible</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">});</span>
</code></pre></div></div>
<p>#airfail</p>
Delicious Google Chrome Extension2009-12-16T00:00:00+00:00https://codecrate.com/2009/12/delicious-google-chrome-extension<p>I use <a href="http://delicious.com/">Delicious</a>. A LOT.</p>
<p>It’s one of the few web services that I have used religiously for years. One of the main reasons I continue to use Delicious is sheer number of great integrations with their <a href="http://delicious.com/help/api">developer API</a>. The Delicious plugin for Firefox is quite good and there is nothing equivalent available for my new default browser, Google Chrome…until now!</p>
<p>I’m excited to officially announce the release of my <a href="https://chrome.google.com/extensions/detail/maegjfahmbklahdfelffbmnkaoicphdm">Delicious Chrome extension</a>!</p>
<p>The Delicious Chrome extension adds a browser action that will save your current page as a Delicious bookmark. The extension will also show popular and recommended tags for the current page and you can add these tags to your bookmark with a simple click.</p>
<p>But that’s not all! The Delicious Chrome extension also integrates with the standard Chrome bookmark stars. Starring a page will automatically save the page on Delicious as well! This should greatly help users add Delicious to their existing browsing behavior without having to learn a new tool.</p>
<p>This extension is <a href="http://github.com/wireframe/delicious-chrome-extension">100% opensource</a> and contributions are always welcome! Please leave any feedback here or on the <a href="https://chrome.google.com/extensions/detail/maegjfahmbklahdfelffbmnkaoicphdm">extension install page</a>.</p>
Batch Javascript Execution2009-11-25T00:00:00+00:00https://codecrate.com/2009/11/batch-javascript-execution<p>Let’s say you’re in a bit of a mess with the performance of your fancy web application’s Javascript. Your application needs to do a lot of work on the front end. I’m talking a lot of repetitive work that takes a long time. Since Javascript is single threaded the end user’s experience is pretty horrible. Their web browser essentially “locks up” while you do all of your work and Firefox users will even be prompted with “Unresponsive script” alerts. How are you going to optimize this?</p>
<p>The “correct” answer is to either reduce the number of times you need to do the work, or to make each execution as fast as humanly possible. Although that is a great suggestion, it’s also potentially expensive and time consuming. There comes a point of diminishing returns when you’ve fixed all the low-hanging fruit and you’re only shaving off milliseconds with each change. What if we could get a great user experience without going through all that work? Well, now you can!</p>
<p>The trick is to allow the browser to breathe between executions. Executing your work in batches gives the browser time to re-draw and keeps the UI from locking up. Although we’re actually increasing the total execution time for doing your work due to the extra delays, the browser remains much more responsive and it greatly improves the end user experience.</p>
<p>As an example, consider an application that is constructing a <em>huge</em> table via javascript. (Let’s ignore the fact that the unit of work is not optimized like it should be)</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="nx">myHugeArray</span><span class="p">,</span> <span class="nx">appendTable</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">appendTable</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1"><tr><td>test</td></tr></span><span class="dl">'</span><span class="p">).</span><span class="nx">appendTo</span><span class="p">(</span><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">#myTable</span><span class="dl">'</span><span class="p">));</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This is your Javascript…</p>
<p>Given enough iterations, this implementation will cause the browser to grind to a halt until the work is complete. Instead of doing all the work at once, we can break it up into batches to help the end user experience. Now, let’s look at this solution that does the exact same work, just broken up into batches.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">doInBatchesWithDelay</span><span class="p">(</span><span class="nx">myHugeArray</span><span class="p">,</span> <span class="nx">appendTable</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">appendTable</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1"><tr><td>test</td></tr></span><span class="dl">'</span><span class="p">).</span><span class="nx">appendTo</span><span class="p">(</span><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">#myTable</span><span class="dl">'</span><span class="p">));</span>
<span class="p">}</span>
<span class="kd">function</span> <span class="nx">doInBatchesWithDelay</span><span class="p">(</span><span class="nx">array</span><span class="p">,</span> <span class="nx">callback</span><span class="p">,</span> <span class="nx">batchSize</span><span class="p">,</span> <span class="nx">delay</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">x</span><span class="p">;</span> <span class="nx">x</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">array</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span><span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">callback</span><span class="p">(</span><span class="nx">array</span><span class="p">.</span><span class="nx">pop</span><span class="p">());</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">array</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">doInBatchesWithDelay</span><span class="p">(</span><span class="nx">array</span><span class="p">,</span> <span class="nx">callback</span><span class="p">,</span> <span class="nx">batchSize</span><span class="p">,</span> <span class="nx">delay</span><span class="p">);</span>
<span class="p">},</span> <span class="nx">delay</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p><a href="http://www.hulu.com/watch/17201/saturday-night-live-sloths"></a></p>
<p>This is your Javascript in BATCHES! It’s still slow, but it’ll kick your face in a punch fight!</p>
<p>This might be considered a hack, but not so! The end user experience is all that matters, and they have no concern for what tricks we have to use to keep the UI snappy. The cost to profile and optimize applications is usually quite high and this is something you can easily drop in today and quiet the complaints of application sluggishness. Addressing their problem with this small change will give you some headroom to work on rearchitecting your slow-ass implementation if needed.</p>
<p>Now, go forth and batch!</p>
The Closure Taste Test2009-11-24T00:00:00+00:00https://codecrate.com/2009/11/closure-taste-test<p>Since the release of the <a href="http://code.google.com/closure/library/">Google Closure library</a>, I’ve spent several weeks going through their source code and giving it a fair shake with some small demos. I have not yet been able to build out a full fledged application using Closure, so let this serve as a full disclaimer that I am a jQuery Junkie and still relatively a Closure newb.</p>
<h2 id="documentation">Documentation</h2>
<p>The source code for the Closure library is chock full of great tips and is a delight to browse through. I’d recommend anyone interested in playing around with Closure to download the library via SVN and poke around.</p>
<p>Don’t even bother looking through the <a href="http://closure-library.googlecode.com/svn/trunk/closure/goog/docs/index.html">online docs</a>. They simply pale in comparison to browsing the extremely well documented source code. I expected the online reference to be much more usable than their current state.</p>
<h2 id="oo">OO</h2>
<p>The Google Closure library is heavily object oriented. For better or worse, it looks and feels more like a Java library and less like a scripting language than any Javascript library I’ve used. They definitely have put a lot of work into making Javascript behave like <a href="http://stackoverflow.com/questions/107464/is-javascript-object-oriented">object oriented developers expect</a>. The goog.inherits() function is an example of how Closure tries to emulate traditional object oriented programming patterns.</p>
<h2 id="what-is-this">What is “this”?</h2>
<p>Remember the good old days when your code was littered with <a href="http://api.prototypejs.org/language/function.html#bind-instance_method">Prototype’s bind() method</a>? Closure uses a lot of Javascript prototype-ing and you often need to worry about what scope/context your functions are executing in. The majority of the Google API’s make setting your context pretty straightforward.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">goog</span><span class="p">.</span><span class="nx">iter</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">myArray</span><span class="p">,</span> <span class="nx">myFunction</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">myFunction</span><span class="p">(</span><span class="nx">eachObject</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">element</span> <span class="o">=</span> <span class="nx">goog</span><span class="p">.</span><span class="nx">dom</span><span class="p">.</span><span class="nx">createDom</span><span class="p">(</span><span class="dl">'</span><span class="s1">div</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">dom</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">myContainer</span><span class="p">,</span> <span class="nx">element</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>I’ve never been a fan of how jQuery always redefines “this” for it’s callbacks, so the Closure API feels more natural to me. jQuery overrides “this” so frequently, that you don’t truly know what “this” you’re working with. I frequently add a little comment within each of my functions to explain what “this” actually is.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="nx">myArray</span><span class="p">,</span> <span class="nx">myFunction</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">myFunction</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">//this == eachObject in array</span>
<span class="p">}</span>
</code></pre></div></div>
<h2 id="events">Events</h2>
<p>Events are a very core aspect of Closure and I assume this is largely due to it’s use in Google Calendar <em>rimshot</em>.</p>
<p>Understanding DOM events and bubbling is one of the more advanced (and powerful) Javascript techniques and Google has done a very good job at making their event pattern usable to all developers for custom events.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">.</span><span class="nx">WORK_COMPLETE_EVENT</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">workcomplete</span><span class="dl">'</span><span class="p">;</span>
<span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">EventTarget</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
<span class="p">};</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">inherits</span><span class="p">(</span><span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">,</span> <span class="nx">goog</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">EventTarget</span><span class="p">);</span>
<span class="c1">//dispatches the work complete event for all listeners</span>
<span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">doWork</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">dispatchEvent</span><span class="p">({</span>
<span class="na">type</span><span class="p">:</span> <span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">.</span><span class="nx">WORK_COMPLETE_EVENT</span><span class="p">,</span>
<span class="na">someValue</span><span class="p">:</span> <span class="dl">'</span><span class="s1">test</span><span class="dl">'</span>
<span class="p">});</span>
<span class="p">};</span>
</code></pre></div></div>
<p>Now, any client can listen for your custom events with ease:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">widget</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">();</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">listen</span><span class="p">(</span><span class="nx">widget</span><span class="p">,</span> <span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">.</span><span class="nx">WORK_COMPLETE_EVENT</span><span class="p">,</span> <span class="nx">myCallback</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">myCallback</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">//do something with the event.</span>
<span class="nx">alert</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">someValue</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Closure’s event API outshines the jQuery event API. Closure event objects are a simple hash which essentially gives you named parameters which is much cleaner than the jQuery event API. jQuery event callbacks easily end up as functions with frankenstein-long argument lists and the required event argument as the first parameter totally blows. It’s like some kind of weird varargs inspired API that constantly bites me in the ass.</p>
<p>ex:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">myElement</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="dl">'</span><span class="s1">someCustomEvent</span><span class="dl">'</span><span class="p">,</span> <span class="nx">myCallback</span><span class="p">);</span>
<span class="kd">function</span> <span class="nx">myCallback</span><span class="p">(</span><span class="nx">e</span><span class="p">,</span> <span class="nx">someValue</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">//do stuff here</span>
<span class="p">});</span>
<span class="nx">myElement</span><span class="p">.</span><span class="nx">trigger</span><span class="p">(</span><span class="dl">'</span><span class="s1">someCustomEvent</span><span class="dl">'</span><span class="p">,</span> <span class="p">[</span><span class="nx">someValue</span><span class="p">]);</span>
</code></pre></div></div>
<p>The Closure Event API is not all sunshine and roses though. It’s very common to need to set your context for your event callback due to all the prototyping action (see above), but the method signature for declaring your scope is pretty weak.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//call myFunction with the right "this" context</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">listen</span><span class="p">(</span><span class="nx">widget</span><span class="p">,</span><span class="nx">mycompany</span><span class="p">.</span><span class="nx">FancyWidget</span><span class="p">.</span><span class="nx">WORK_COMPLETE_EVENT</span><span class="p">,</span> <span class="nx">myFunction</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span>
</code></pre></div></div>
<p>false, this, wha?!? the mandatory ‘false’ parameter really sucks when you need to set the context for your callback. Doesn’t Google know that <a href="http://www.jroller.com/alexRuiz/entry/boolean_arguments_can_be_evil">boolean parameters are evil</a>?!? Passing an hash as the last parameter with named entries for the scope/capturePhase would have been a much cleaner solution.</p>
<h2 id="ajax">Ajax</h2>
<p>jQuery kicks Closure’s ass around the block when it comes to Ajax. Google has done very little to abstract away the details of XHR and it definitely shows. With all of the crazy Web 2.0 Ajax-y goodness in every Google application, I was honestly expecting much more in this area.</p>
<p>ex:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">request</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">XhrIo</span><span class="p">();</span><span class="nx">goog</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">listenOnce</span><span class="p">(</span><span class="nx">request</span><span class="p">,</span> <span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">EventType</span><span class="p">.</span><span class="nx">SUCCESS</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">//do my work here</span>
<span class="p">});</span>
<span class="nx">request</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">http://mycompany.com</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">GET</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>
<p>The Closure example makes my skin crawl when compared with the elegance of jQuery.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">.</span><span class="kd">get</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">//do my work here</span>
<span class="p">});</span>
</code></pre></div></div>
<p>It’s perfectly acceptable for Closure to give you as much access to the raw request as possible, but I’m seriously at a loss why it doesn’t ship with a more accessible API for developers coming from jQuery/Prototype/MooTools/etc background. Something like this would do fine:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">SimpleXhr</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">XhrIo</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">event</span> <span class="k">in</span> <span class="nx">options</span><span class="p">.</span><span class="nx">events</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">listenOnce</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">event</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">events</span><span class="p">[</span><span class="nx">event</span><span class="p">]);</span>
<span class="p">}</span>
<span class="nx">request</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">url</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">method</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">inherits</span><span class="p">(</span><span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">SimpleXhr</span><span class="p">,</span> <span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">XhrIo</span><span class="p">);</span>
</code></pre></div></div>
<p>This would give you an API very similar to jQuery:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">SimpleXhr</span><span class="p">.</span><span class="k">new</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">http://mycompany.com</span><span class="dl">'</span><span class="p">,</span>
<span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">GET</span><span class="dl">'</span><span class="p">,</span>
<span class="na">events</span><span class="p">:</span> <span class="p">{</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">net</span><span class="p">.</span><span class="nx">EventType</span><span class="p">.</span><span class="na">SUCCESS</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">//callback here</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>
<h2 id="the-dom">The DOM</h2>
<p>Closure gets another kick in the pants here. Closure only supports static helper methods to for developers to work with the DOM.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">element</span> <span class="o">=</span> <span class="nx">goog</span><span class="p">.</span><span class="nx">dom</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="dl">'</span><span class="s1">div</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">goog</span><span class="p">.</span><span class="nx">dom</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span>
</code></pre></div></div>
<p>vs</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1"><div /></span><span class="dl">'</span><span class="p">).</span><span class="nx">appendTo</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span>
</code></pre></div></div>
<p>It’s not the extra line that bothers me. It’s the lack of context and Context is King in my world.
I constantly found myself second guessing things like,
“is the first argument to appendChild() the child or the parent element?”
Calling methods directly on the DOM element is so much more natural than using
these external helper methods even if
<a href="http://draft.blogger.com/goog_1259040188124">method chaining</a>
<a href="http://draft.blogger.com/goog_1259040188124">does</a>
<a href="/2009/11/jquery-dom-manipulation-performance.html">have it’s own drawbacks</a>.</p>
<h2 id="dependencieslibraries">Dependencies/Libraries</h2>
<p>The require and provide functions are the right and left bauers that enable the <a href="http://code.google.com/closure/compiler/">Closure Compiler</a> and the <a href="http://code.google.com/closure/library/docs/calcdeps.html">dependency calculation script</a> do it’s thang.</p>
<p>The goog.provide() method makes it ridiculously simple to namespace your code. It has always been a best practice to namespace your code so why wouldn’t you use it?</p>
<p>The goog.require() function is pretty badass and solves a very common problem where you end up rolling all your javascript files into one bloated file. Have you ever seen the <a href="http://code.google.com/speed/page-speed/">PageSpeed plugin</a> complain that “90% of the Javascript on this page has not been invoked”? Not any more! Only import what you need. The Closure compiler helps take this very slick solution for dynamic imports and makes it ready for production deployment. If only they had a similar solution for css!</p>
<p>Using require and provide definitely feels Java-ish, but I think it’s a good thing! Explicitly declaring what your library provides and requires not only allows for “tooling support” (ex: the Closure compiler), but it also forces the developer to be aware of what they depend on and not to make any assumptions about what plugins the user will already have included on their page.</p>
<h2 id="components">Components!</h2>
<p>The number of widgets available is extremely impressive and each one is a great learning experience. Packaging executable demos along with the source is also extremely helpful to get started quickly. I’ve been very happy with my usage of jQuery plugins, but Google has definitely laid a strong foundation that third party widget developers should follow.</p>
<h2 id="testing">Testing</h2>
<p>Major props go to Google for including a robust test library with Closure. -1 for using JSUnit. :)</p>
<p>After using screw unit and it’s emphasis on “context” for testcases, the JSUnit pattern of “testMyFunctionDoesItsWorkWhenSetupInACertainWay” is a major turnoff.</p>
<p>The BlueRidge library might be able to take some pointers from Google. Using the Closure goog.require() method should be able to <a href="http://github.com/relevance/blue-ridge/issues#issue/13">fix it’s lack of Safari support</a>.</p>
<h2 id="in-conclosure">In Conclosure</h2>
<p>The Closure library brings a lot to the table and is incredibly exciting for the world of Web developers. I can’t wait to see the rippling impact some of the tools and techniques Closure introduces will have on the Web community. Closure is an incredible project that is pushing to show Javascript as a legitimate language, and squash the common opinion that Javascript is a “toy” language for wanna be web designers turned hackers. Make no mistake about it. Closure is built by engineers, for engineers.</p>
To Github We Go!2009-11-18T00:00:00+00:00https://codecrate.com/2009/11/to-github-we-go<p>Over the years, I’ve used a number of source repositories for my published projects. For a time, I hosted a public personal SVN repo, but the server upkeep was a major turnoff. Then, there was an extended period where my projects lived within the shell of a parent opensource project (wicketstuff) which was great until the repo structure became unwieldy.</p>
<p>I was recently contacted by someone looking for one of my old Wicket contributions and found out that nearly all of my wicket stuff projects had been relocated in the SVN repo which broke my direct links. It’s perfectly acceptable for the wicketstuff folks to re-arrange their repo as they see fit, but I no longer feel that the wicketstuff repo is the right place for my contributions. I am not vested in the wicketstuff project and would much rather have my personal projects all located in one central spot so it’s easy for me to publish new samples or integrations and not have to worry about finding the “right” repository structure. In my opinion, shared repo’s are simply too much politics and too little hacking.</p>
<p>Github is by far the best solution for these projects and so I have migrated my published projects from the Wicketstuff SVN repo to github. You can now find my contributed Wicketstuff projects here:</p>
<ul>
<li><a href="http://github.com/wireframe/wicketstuff-hibernate-behavior/">wicketstuff-hibernate-behavior</a>- Wicket integration to auto-configure your forms using Hibernate annotations.</li>
<li><a href="http://github.com/wireframe/wicketstuff-rome">wicketstuff-rome</a>- Wicket component for integrating with the ROME RSS/Atom library</li>
<li><a href="http://github.com/wireframe/wicketstuff-scriptaculous">wicketstuff-scriptaculous</a>- Web 2.0 Wicket components using the Scriptaculous Javascript library</li>
</ul>
<p>Unfortunately, the import from SVN to github has totally nuked the commit history for these projects. The commit history may have been lost due to the project rearrangement done by the wicketstuff devs (SVN fail). That’s really unfortunate, but since the majority of these projects are from one-night coding sessions, there’s not a lot of true “history” in them. It just sucks that to lose the author information. If anyone has some fix for this, please let me know. The projects are currently in read-only state, so I would have no issue re-importing them from the subversion repository if that would fix things.</p>
jQuery DOM Manipulation Performance2009-11-02T00:00:00+00:00https://codecrate.com/2009/11/jquery-dom-manipulation-performance<p>Everyone says that “avoiding DOM manipulation” is a key to improve javascript performance, but their understanding of the root issue is slightly skewed. In reality, manipulating elements is extremely fast until the element has been added to the DOM. No need to throw away the wonderful append/prepend jQuery API’s and drop down to the low level innerHtml tricks to get great performance. Just make sure that you’re manipulating element fragments before they’re added to the DOM.</p>
<p>The difference between these two blocks of code is subtle, but incredibly important.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//adds element to DOM and *then* does the manipulation</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1"><div>some text</div></span><span class="dl">'</span><span class="p">).</span><span class="nx">appendTo</span><span class="p">(</span><span class="nx">someElement</span><span class="p">).</span><span class="nx">doSomeManipulation</span><span class="p">();</span>
<span class="c1">//manipulates the element fragment *before* adding to the DOM</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1"><div>some text</div></span><span class="dl">'</span><span class="p">).</span><span class="nx">doSomeManipulation</span><span class="p">().</span><span class="nx">appendTo</span><span class="p">(</span><span class="nx">someElement</span><span class="p">);</span>
</code></pre></div></div>
<p>It’s extremely important to be aware of when elements have been added to the DOM and beware manipulating elements once they are in place.</p>
<p>You can make incredible improvements to your javascript performance by performing the majority of your work before adding your elements to the DOM. By simply reordering your chain invocation, I’ve seen as much as a 10x improvement in javascript performance with this one technique (500 millis down to 50 millis after this change).</p>
<p>This is not necessarily a global fix for all javascript performance issues. There may be times when you actually need the element inserted into the DOM before doing more work (ex: embedding flash content), but it’s worth a shot to see if this approach works with your application!</p>
Rails Fail with Unicode JSON2009-10-29T00:00:00+00:00https://codecrate.com/2009/10/rails-fail-with-unicode-json<h2 id="how-to-break-nearly-any-rails-app-usingjsonin-3-simple-steps">How to break nearly any Rails app using JSON in 3 simple steps</h2>
<ol>
<li>Store unicode characters in the database (\020 or \221 or pretty much any other unicode character)</li>
<li>Request JSON representation of data</li>
<li>Watch your clients crash and burn (IE7 and PHP parsers in particular will hack and die on the JSON response)</li>
</ol>
<p>Here’s a quick testcase to show the issue. Fire up your script/console to try it out:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="s1">'bad characters'</span><span class="p">.</span><span class="nf">concat</span><span class="p">(</span><span class="mi">16</span><span class="p">).</span><span class="nf">to_json</span> <span class="o">=></span> <span class="s2">""</span><span class="n">bad</span> <span class="n">characters</span><span class="p">\</span><span class="mo">020</span><span class="s2">""</span>
</code></pre></div></div>
<p>Notice anything special about the rendered string? How about the fact that it’s invalid JSON?!? Unicode characters need to be escaped, and the proper response should be:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#=> ""bad characters\u0010""</span>
</code></pre></div></div>
<p>The most common way I’ve seen these unicode characters get into the database is when someone copies text from a word document and pastes it into my application. It’s not extremely common, but that’s no excuse for rendering invalid responses.</p>
<p>The <a href="http://json.rubyforge.org/">ruby json gem</a> encodes the unicode characters correctly and the Rails implementation is pretty busted. Rails has a pluggable backend for parsing JSON (ActiveSupport::JSON.backend), so why not delegate the ActiveSupport::JSON.encode method to the same implementation?</p>
<p>Please vote for this lighthouse ticket to get JSON encoding in Rails up to snuff!</p>
<p><a href="https://rails.lighthouseapp.com/projects/8994/tickets/3345-to_json-does-not-escape-unicode-characters#ticket-3345-1">https://rails.lighthouseapp.com/projects/8994/tickets/3345-to_json-does-not-escape-unicode-characters#ticket-3345-1</a></p>
<p><strong>UPDATE:</strong> A patch has been <a href="http://github.com/rails/rails/commit/a9002056761a481589852d6e8680f752a5b823b7">submitted and accepted</a> into the rails core that should fix this issue with the next release. Hopefully this doesn’t have to wait till the Rails 3.0 release!</p>
Backgrounded ActiveRecord Callbacks2009-10-29T00:00:00+00:00https://codecrate.com/2009/10/backgrounded-activerecord-callbacks<p>ActiveRecord callbacks are pretty amazing. They are an incredibly useful way to declare
specific behavior that is tied to the lifecycle of your model objects.</p>
<p>One very common pattern is to perform "house keeping" activities when an object is updated.
This could mean anything from updating related model objects to logging or updating usage statistics.
Here’s a simple example.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span>
<span class="n">after_create</span> <span class="ss">:update_stats</span>
<span class="k">def</span> <span class="nf">update_stats</span>
<span class="c1"># do your heavy lifting here</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The majority of these lifecycle callbacks are not in the critical path for saving
your model object and should be pushed to the background to improve end user response times.
The backgrounded API makes transitioning ActiveRecord callbacks to the background incredibly easy.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span>
<span class="n">backgrounded</span> <span class="ss">:update_stats</span>
<span class="n">after_create</span> <span class="ss">:update_stats_backgrounded</span>
<span class="k">def</span> <span class="nf">update_stats</span>
<span class="c1"># do your heavy lifting here</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>As a side note, <a href="http://gemcutter.org/gems/backgrounded">the backgrounded gem is now available on gemcutter</a>
so that we can join the cool kids club!</p>
CSS Sentences with jQuery fallback2009-10-26T00:00:00+00:00https://codecrate.com/2009/10/css-sentences-with-jquery-fallbackTwitter Style Alerts In Rails2009-10-03T00:00:00+00:00https://codecrate.com/2009/10/twitter-style-alerts-in-rails<p><a href="http://twitter.com/">Twitter</a> has a very elegant solution for user feedback messages. They display the message by sliding the text down from the top of the screen in a semi-transparent block and hide the message after a few moments. It’s a very slick design and one of the more appealing solutions I’ve seen (and I’ve worked with a lot of feedback designs).</p>
<p><a href="http://img.skitch.com/20091003-x7i4ydi1wuk2jjxpe6kepxxre1.jpg"></a></p>
<p>[</p>
<p>](http://img.skitch.com/20091003-x7i4ydi1wuk2jjxpe6kepxxre1.jpg)</p>
<h2 id="why-this-solution-rocks">Why this solution rocks</h2>
<ul>
<li>Feedback at the top of the screen prevents hiding important elements in the page body. This avoids a very common problem with alert/lightbox feedback solutions.</li>
<li>The blind down effect draws your attention, yet is not visually jarring. Apple does an excellent job with similar effects within their products.</li>
<li>Absolute positioning the overlay abovethe page content prevents page height popping when sliding down the alert message.</li>
<li>Automatically hiding the alert after a time period removes the need for a dismiss button.</li>
</ul>
<p>Apparently, Twitter rules the world and everything Twitter does needs to be copied by every other application. I’ve seen <a href="http://briancray.com/2009/05/06/twitter-style-alert-jquery-cs-php/">this solution ported to PHP</a>, so I figured I might as well save people time and show how to accomplish Twitter style alert messages in Rails. All it takes is a little SASS and jQuery and you’ll be set…</p>
<p>See the solution in action at:</p>
<p><a href="http://twitteralerts.heroku.com/">http://twitteralerts.heroku.com/</a></p>
<p>Code for the demo is available on github at:</p>
<p><a href="http://github.com/wireframe/twitteralerts">http://github.com/wireframe/twitteralerts</a></p>
<p>Wire up your layout to have a pretty standard container div for your alert content…</p>
<div class="language-haml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">#app</span>/views/layouts/application.html.haml
<span class="nt">%html</span>
%body
- if flash[:notice] || flash[:warning]
%div{:class => "alert <span class="si">#{</span><span class="s1">'warning'</span> <span class="k">if</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:warning</span><span class="p">]</span><span class="si">}</span>", :style => 'display: none'}
= flash[:notice] || flash[:warning]
= yield
</code></pre></div></div>
<p>JQuery does all the work to show/hide the alert message.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//public/javascripts/jquery.alertfeedback.js</span>
<span class="nx">$</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
<span class="err"> </span> <span class="kd">var</span> <span class="nx">alert</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">.alert</span><span class="dl">'</span><span class="p">);</span>
<span class="err"> </span> <span class="k">if</span> <span class="p">(</span><span class="nx">alert</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="err"> </span> <span class="nx">alert</span><span class="p">.</span><span class="nx">show</span><span class="p">().</span><span class="nx">animate</span><span class="p">({</span><span class="na">height</span><span class="p">:</span> <span class="nx">alert</span><span class="p">.</span><span class="nx">outerHeight</span><span class="p">()},</span> <span class="mi">200</span><span class="p">);</span>
<span class="err"> </span> <span class="nb">window</span><span class="p">.</span><span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="err"> </span><span class="nx">alert</span><span class="p">.</span><span class="nx">slideUp</span><span class="p">();</span>
<span class="err"> </span> <span class="p">},</span> <span class="mi">3000</span><span class="p">);</span>
<span class="err"> </span> <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>
<p>Some fancy CSS to make the alert messages look good.</p>
<div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//public/stylesheets/sass/application.sass</span>
<span class="nc">.alert</span>
<span class="err"> </span> <span class="nd">:overflow</span> <span class="nt">hidden</span>
<span class="err"> </span> <span class="nd">:z-index</span> <span class="nt">999</span>
<span class="err"> </span> <span class="nd">:width</span> <span class="nt">100</span><span class="nv">%</span>
<span class="err"> </span> <span class="nd">:text-align</span> <span class="nt">center</span>
<span class="err"> </span> <span class="nd">:position</span> <span class="nt">absolute</span>
<span class="err"> </span> <span class="nd">:top</span> <span class="nt">0</span>
<span class="err"> </span> <span class="nd">:left</span> <span class="nt">0</span>
<span class="err"> </span> <span class="nd">:background-color</span> <span class="nt">rgb</span><span class="o">(</span><span class="nt">161</span><span class="o">,</span><span class="nt">195</span><span class="o">,</span><span class="nt">0</span><span class="o">)</span>
<span class="err"> </span> <span class="nd">:background-color</span> <span class="nt">rgba</span><span class="o">(</span><span class="nt">161</span><span class="o">,</span><span class="nt">195</span><span class="o">,</span><span class="nt">0</span><span class="o">,</span><span class="nc">.8</span><span class="o">)</span>
<span class="err"> </span> <span class="nd">:height</span> <span class="nt">0</span>
<span class="err"> </span> <span class="nd">:color</span> <span class="nn">#fff</span>
<span class="err"> </span> <span class="nd">:padding</span> <span class="nt">9px</span> <span class="nt">0</span>
<span class="err"> </span> <span class="nd">:text-shadow</span> <span class="nt">rgba</span><span class="o">(</span><span class="nt">99</span><span class="o">,</span><span class="nt">130</span><span class="o">,</span><span class="nt">0</span><span class="o">,</span><span class="nc">.75</span><span class="o">)</span> <span class="nt">1px</span> <span class="nt">1px</span> <span class="nt">1px</span>
<span class="err"> </span><span class="nd">:font-size</span> <span class="nt">21px</span>
<span class="err"> </span><span class="k">&</span><span class="nc">.warning</span>
<span class="err"> </span> <span class="nd">:background-color</span> <span class="nn">#800</span>
</code></pre></div></div>
Text Truncation With CSS/SASS/Javascript2009-10-01T00:00:00+00:00https://codecrate.com/2009/10/text-truncation-with-csssassjavascript<h2 id="trimming-text-in-style">Trimming Text In Style</h2>
<p>It’s a very common request to have text elements truncated to prevent breaking your layout. In the past I’ve relied on character counting solutions, but that’s about as effective as using Java to build a modern day webapp. Variable width fonts effectively break all character counting solutions. Each browser/OS has a different font rendering engine which makes truncating based on character counts a fragile and fundamentally flawed solution.</p>
<p>Overflow hidden is the de-facto standard solution to prevent long text from breaking your layout, but it leaves a lot to be desired on the UI side. It’s just not cool to chop off text in mid character.</p>
<p>The text-overflow ellipsis CSS property is the perfect solution to this problem. It truncates your text at the correct length and inserts the standard “…” ellipsis at the end. Here’s a simple Sass mixin that will add all of the appropriate properties necessary to trigger the text-overflow behavior.</p>
<div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">=truncate</span><span class="p">(</span><span class="o">!</span><span class="n">width</span><span class="p">)</span>
<span class="err"> </span> <span class="nd">:text-overflow</span> <span class="nt">ellipsis</span>
<span class="err"> </span> <span class="nd">:overflow</span> <span class="nt">hidden</span>
<span class="err"> </span> <span class="nd">:white-space</span> <span class="nt">nowrap</span>
<span class="err"> </span><span class="nd">:display</span> <span class="nt">block</span>
<span class="err"> </span> <span class="nd">:width</span><span class="o">=</span> <span class="o">!</span><span class="nt">width</span>
</code></pre></div></div>
<p>Now, you can reuse this chunk of logic in your Sass styles to truncate elements without changing any of your markup!</p>
<div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//truncate this element at 160 pixels</span>
<span class="nc">.my_container</span>
<span class="err"> </span><span class="o">+</span><span class="nt">truncate</span><span class="o">(</span><span class="nt">160</span><span class="o">)</span>
<span class="c1">//truncate at 200 pixels</span>
<span class="nc">.header</span>
<span class="err"> </span><span class="o">+</span><span class="nt">truncate</span><span class="o">(</span><span class="nt">200</span><span class="o">)</span>
</code></pre></div></div>
<p>This solution degrades gracefully and defaults to using overflow hidden if the client does not support the text-overflow property. Surprisingly, Firefox is the only modern browser that still doesn’t support this CSS property. Even more surprising is that IE was the first browser to implement this feature!</p>
<p>Javascript can used to emulate the same CSS truncation for browsers that do not support the text-overflow feature. Here’s a great jQuery plugin that does the dirty work so that all clients can see the same sexy truncation.</p>
<p><a href="http://devongovett.wordpress.com/2009/04/06/text-overflow-ellipsis-for-firefox-via-jquery/">http://devongovett.wordpress.com/2009/04/06/text-overflow-ellipsis-for-firefox-via-jquery/</a></p>
Rails Tips: Default Page Content2009-09-27T00:00:00+00:00https://codecrate.com/2009/09/rails-tips-default-page-content<p>Using Rails layouts is a great way to abstract away commonly rendered elements. Over the past year, I have found myself creating multiple layouts which were essentially the same, and just needed to customize a portion of the content. It’s an expensive process to maintain multiple layouts, so I decided to find a more DRY approach.</p>
<p>Here’s a simple solution for your layouts to provide the default content, and expose an extension point to allow your templates to override with their own content.</p>
<div class="language-haml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">#app</span>/views/layouts/application.html.haml
<span class="nt">%html</span>
<span class="nt">%body</span>
<span class="nf">#header</span>
<span class="p">-</span> <span class="n">header</span> <span class="o">=</span> <span class="k">yield</span> <span class="ss">:header</span>
<span class="p">=</span> <span class="n">header</span><span class="p">.</span><span class="nf">blank?</span> <span class="p">?</span> <span class="n">render</span><span class="p">(</span><span class="ss">:partial</span> <span class="o">=></span> <span class="s1">'header'</span><span class="p">)</span> <span class="p">:</span> <span class="n">header</span>
<span class="p">=</span> <span class="k">yield</span>
</code></pre></div></div>
<p>Now each of your views can “inherit” the default markup, or they can override the content by declaring a content_for block like so:</p>
<div class="language-haml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nf">#app</span>/views/posts/index.html.haml
<span class="p">-</span> <span class="n">content_for</span> <span class="ss">:header</span> <span class="k">do</span>
<span class="nc">.my_special_header</span>
custom content goes here
</code></pre></div></div>
<p>Simple, elegant and much more maintainable!</p>
Continuous Deployment for Rails2009-09-15T00:00:00+00:00https://codecrate.com/2009/09/continuous-deployment-for-rails<p>It’s literally been months since I’ve manually typed “cap production deploy”. For the past several months, we’ve been implementing a <a href="http://www.startuplessonslearned.com/">lean startup process</a> and using continuous deployment to push code to production. Continuous deployment’s core premise is to deploy code to production with every commit. From my standpoint, it’s been a dream come true.</p>
<p>Just Ship It!</p>
<p>The theory behind continuous deployment is rather simple, “unreleased code is a liability”. Features that takes weeks to build without getting real feedback are distracting you from focusing on what your customers are seeing every day. Using continuous deployment forces you to think differently about feature development. Large complex features become incremental deployments with user feedback at each step to ensure you’re headed in the right direction (and to pull the plug as quickly as possible if you’re not). If you’re able to adjust your feature during the development cycle, you save time (and money) that would be wasted on going in a wrong direction.</p>
<p>Effective and thorough testing are all that stands between a bad commit and a busted production environment, which means that continuous integration is absolutely critical. The Testing Nazi in me taken full advantage of this to push the envelope on the importance of testing. I’ve even hired a set of angry midgets to enforce proper testing standards…</p>
<p>If it’s not tested, it’s CRAP!</p>
<p><a href="http://cruisecontrolrb.thoughtworks.com/">Cruisecontrol.rb</a> is the heart and soul of our continuous deployment, but it’s actually a very simple process. We register a custom rake task which runs our complete testsuite and if all tests pass, cruisecontrol flips the switch and deploys the code. Our rake task looks something like this:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#lib/tasks/cruisecontrol.rake</span>
<span class="n">desc</span> <span class="s1">'Run all continuous integration tests'</span>
<span class="n">task</span> <span class="ss">:cruise</span> <span class="k">do</span>
<span class="c1">#run all tests</span>
<span class="c1">#see rails/lib/taks/testing.rake</span>
<span class="n">errors</span> <span class="o">=</span> <span class="sx">%w(units functionals integration javascripts acceptance)</span><span class="p">.</span><span class="nf">collect</span> <span class="k">do</span> <span class="o">|</span><span class="n">task</span><span class="o">|</span>
<span class="k">begin</span>
<span class="no">Rake</span><span class="o">::</span><span class="no">Task</span><span class="p">[</span><span class="s2">"test:</span><span class="si">#{</span><span class="n">task</span><span class="si">}</span><span class="s2">"</span><span class="p">].</span><span class="nf">invoke</span>
<span class="kp">nil</span>
<span class="k">rescue</span> <span class="o">=></span> <span class="n">e</span>
<span class="n">task</span>
<span class="k">end</span>
<span class="k">end</span><span class="p">.</span><span class="nf">compact</span>
<span class="nb">abort</span> <span class="s2">"Errors running </span><span class="si">#{</span><span class="n">errors</span><span class="p">.</span><span class="nf">to_sentence</span><span class="p">(</span><span class="ss">:locale</span> <span class="o">=></span> <span class="ss">:en</span><span class="p">)</span><span class="si">}</span><span class="s2">!"</span> <span class="k">if</span> <span class="n">errors</span><span class="p">.</span><span class="nf">any?</span>
<span class="nb">system</span> <span class="s2">"cap production deploy"</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Our testsuite started off as a standard rails deployment and has grown over time to accommodate our evolving testing practices. Building a modern Web 2.0 application means you’ll be spending a lot of time dealing with web browsers, so we’ve spent extensive time integrating tools for testing web browsers and javascript. Our current testsuite includes:</p>
<ul>
<li>unit tests (Test::Unit)</li>
<li>functional tests (ActionController::TestCase)</li>
<li>integration tests (ActionController::IntegrationTest)</li>
<li>javascript tests (<a href="http://github.com/relevance/blue-ridge/tree/master">BlueRidge</a>/<a href="http://github.com/nkallen/screw-unit">ScrewUnit</a>)</li>
<li>acceptance tests (<a href="http://seleniumhq.org/">Selenium</a>)</li>
</ul>
<p>It’s important to remember that you shouldn’t go overboard building out infrastructure to support a continuous deployment process. The same rule of “undeployed code is a liability” applies to your testing environment. You absolutely can not afford to waste time building out a suite of tools until you need it. Simply take incremental steps from where you are today and slowly add in infrastructure as needed. Each step will incrementally move you towards a better system overall.</p>
Backgrounded 0.3.0 Released2009-08-18T00:00:00+00:00https://codecrate.com/2009/08/backgrounded-030-released<p>The <a href="/2009/07/backgrounded-background-processing-done.html">initial release of Backgrounded</a> seems to have struck <a href="http://www.rubyinside.com/backgrounded-a-simple-wrapper-for-ruby-background-tasks-2100.html">a chord</a> with <a href="http://railsenvy.com/2009/8/5/rails-envy-podcast-episode-089-08-05-09">the Ruby community</a> and it appears to be gaining momentum. The response has been very positive, but there has been some confusion on why Backgrounded exists I’d like to take a moment to clarify that.</p>
<h2 id="api-above-all">API Above All</h2>
<p>The API for calling background jobs needs to be clear and concise. No extra Worker/Job classes, and the method signature for invoking background jobs needs to make sense.</p>
<p>The optional delayed_job API is okay, but not great. It is nowhere near as usable as as the Backgrounded syntax. </p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#delayed_job API</span>
<span class="no">MyObject</span><span class="p">.</span><span class="nf">handle_asynchronously</span><span class="p">(</span><span class="ss">:my_action</span><span class="p">)</span>
</code></pre></div></div>
<p>Workling’s implementation is workable (pun intended), but not ideal either. I constantly find myself wondering if the method name starts with “async” or “asynch” and the lack of method completion (due to method_missing usage) makes this problem even worse.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#workling API</span>
<span class="no">MyObject</span><span class="p">.</span><span class="nf">async_my_action</span>
</code></pre></div></div>
<p>The Backgrounded API is an evolutionary API inspired by these other implementations. After several iterations, the Backgrounded API was born as the definitive implementation for clear and concise invocation.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#Backgrounded API</span>
<span class="no">MyObject</span><span class="p">.</span><span class="nf">my_action_backgrounded</span>
</code></pre></div></div>
<h2 id="testability">Testability</h2>
<p>The vast majority of background processing libraries I’ve worked with have not been particularly good about integrating with unit tests. Maybe their recommended best practice is to not unit test background jobs, but that’s not exactly a good idea. Backgrounded integrates smoothly with testing environments by running background operations synchronously which means you can perform assertions without jumping through hoops or waiting for background operations to complete.</p>
<h2 id="portability">Portability</h2>
<p>You should be able to swap in a new background processing framework with no changes to your code. Backgrounded is an extremely thin wrapper around any backend processing framework and should work seemlessly with whatever implementation you choose (DelayedJob, JobFu, Workling, etc). DelayedJob and JobFu work out of the box and It’s extremely easy to implement your own handler for other libraries.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># config/initializers/backgrounded.rb</span>
<span class="k">class</span> <span class="nc">MyHandler</span>
<span class="k">def</span> <span class="nf">request</span><span class="p">(</span><span class="n">object</span><span class="p">,</span> <span class="nb">method</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="c1">#process the call however you want!</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="no">Backgrounded</span><span class="p">.</span><span class="nf">handler</span> <span class="o">=</span> <span class="no">MyHandler</span><span class="p">.</span><span class="nf">new</span>
</code></pre></div></div>
<p><a href="http://github.com/jnstq">Jon Stenqvist</a> stepped up to the plate this last week and knocked out a few awesome additions to Backgrounded. Major props to Jon for the patches and to Github for making it so damn easy to integrate his changes into the codebase.</p>
<p>Backgrounded now supports passing method parameters to your async operation which should make it even easier to integrate Backgrounded into your project since you shouldn’t need to change method signatures. You should be aware that your method parameters will be marshaled and unmarshaled in order to pass the arguments to the separate process which may have some side effects if you’re passing around complex objects. In my experience, it is best to either use no-argument methods or use simple data types and avoid passing entire serialized objects. This is the same advise used when <a href="http://railscasts.com/episodes/13-dangers-of-model-in-session">storing information in your HTTP session</a>.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#Backgrounded now supports method params!</span>
<span class="no">MyObject</span><span class="p">.</span><span class="nf">save_username_backgrounded</span><span class="p">(</span><span class="s1">'new username'</span><span class="p">)</span>
</code></pre></div></div>
<p>Jon also added first class Backgrounded support for the <a href="http://github.com/jnstq/job_fu/tree/master">JobFu library</a> which is an alternative to DelayedJob. I haven’t played around with JobFu yet, but I’m excited at how easy it was for Jon to integrate JobFu with Backgrounded. It just goes to show how trivial it is to write a custom handler for processing background events. If anyone else would like to contribute an extension, let me know!</p>
<p>The new JobFu contribution leads me to my next question, what is the best way to distribute the Backgrounded handlers for various frameworks? JobFu does an <em>excellent</em> job by packaging the handler directly with their plugin, but not all frameworks will follow that lead. Would it be most beneficial to have each implementation as a separate gem (ex: workling-backgrounded, delayed_job-backgrounded, etc), or include each implementation directly with the backgrounded core (like delayed_job currently is)? I’m personally leaning towards having separate gems for each integration which would allow for a quicker release schedule and lower barrier to entry for new integrations. Any thoughts?</p>
<p>With the 0.3.0 release now out the door, it’s time to look forward. Coming soon to Backgrounded…background ActionMailer delivery. Stay tuned!</p>
Socialcast Developer API Released2009-08-12T00:00:00+00:00https://codecrate.com/2009/08/socialcast-developer-api-released<p><a href="http://www.flickr.com/photos/wireframe/3816583420/"></a></p>
<p>Incase you missed the announcement, today we unveiled <a href="http://blog.socialcast.com/socialcast-announces-official-release-of-developer-api/">the official release of our Socialcast Developer API.</a> It’s a 100% REST API designed to open your Socialcast community to a new generation of integrations.</p>
<p>I’m very excited to see new and unconventional integrations pop-up now that this is in the wild. The API has been a blast to build (mainly attributed to it’s REST-full nature), and the current set of features is pretty compelling. The possible uses of the API are nearly endless, and our official desktop application is a great example of what can be achieved with the current API.</p>
<p>Just to give folks a little incentive, I’d like to send out a personal challenge for developers to integrate with the Socialcast API. Anything from Javascript mashups to desktop widgets to command line scripts are possible. Just build something cool and put it out there! </p>
<p>What’s that? A little contest you say?</p>
<ul>
<li>no rules</li>
<li>no limitations</li>
<li>no judges (except me of course) </li>
<li>it’s a no holds barred hack-a-thon!</li>
</ul>
<p>Oh, but of course there are prizes!</p>
<ul>
<li>I will personally buy anyone that gets something working a BEER! Unfortunately, this offer only applies to folks in the Twin Cities (or San Francisco when I’m in the area). If you are not a resident of the Twin Cities, I’ll be sending you a one of a kind flickr <em>picture of beer</em> which you can then print out on your fancy printer and hang on the wall next to your picture of Captain Picard!</li>
<li>Socialcast swag. T-Shirts and the like are developer’s gold!</li>
<li>Okay, so the prizes aren’t that exciting, but think of the GLORY! This is out of my own pocket and not an “official” Socialcast competition, so please be understanding.</li>
</ul>
<p>If you have questions or comments, please see <a href="http://getsatisfaction.com/socialcast/products/socialcast_socialcast_developer_api">the Socialcast API developer support group</a> or feel free to contact me directly. Now get out there and build some kick ass apps!</p>
<p>P.S. Anyone implementing a Socialcast <a href="http://ubiquity.mozilla.com/">Ubiquity plugin</a> might earn TWO beers! :)</p>
jQuery Snazzy Select Plugin2009-08-06T00:00:00+00:00https://codecrate.com/2009/08/jquery-snazzy-select-plugin<p>HTML Select inputs are notorious for being difficult to style. Every operating system/browser styles them differently, and there are no standard CSS hooks available to customize their look. The new jQuery Snazzy Select plugin available on github solves this problem and will turn your ugly ass select fields into sexy works of art!</p>
<p><a href="http://github.com/socialcast/jquery.snazzyselect">http://github.com/socialcast/jquery.snazzyselect</a></p>
<p>Since you can’t style the select input directly, you’ll need to make a few markup changes to work with the Snazzy Select plugin. You only need to wrap your existing select input with a div and add another div as a sibling to the select input. Add the class of “snazzy_selected” to the sibling div and you’re ready to go!</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>!-- add a wrapper div around the select input --<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>select<span class="ni">&gt;</span>
<span class="ni">&lt;</span>option<span class="ni">&gt;</span>value 1<span class="ni">&lt;</span>/option<span class="ni">&gt;</span>
<span class="ni">&lt;</span>option<span class="ni">&gt;</span>value 2<span class="ni">&lt;</span>/option<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/select<span class="ni">&gt;</span>
<span class="ni">&lt;</span>!-- add a placeholder div where the selected value will be displayed --<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div class="snazzy_selected"<span class="ni">&gt;</span>placeholder<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Initialize the component by calling the snazzySelect() jQuery method, and you’ll have some spankin’ hot dropdowns! </p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">select</span><span class="dl">'</span><span class="p">).</span><span class="nx">snazzySelect</span><span class="p">();</span>
</code></pre></div></div>
<p>Default CSS styling is included, but it the look is completely customizable.</p>
<p>No changes are necessary for your existing serverside processing. The html select element will continue to post the existing form field. The Snazzy Select plugin is simply a visual wrapper around the select input. This also means that your existing jQuery onchange bindings will still work with no modifications.</p>
<p>This marks the first of hopefully many opensource components released from our <a href="http://www.socialcast.com/">Socialcast</a> toolbox. The Snazzy Select plugin has been battle tested in our production application and tested in all major browsers (including IE6). A comprehensive test suite (using Blue Ridge and ScrewUnit) is also included.</p>
<p>Enjoy your snazzy new world!</p>
The End of Adobe AIR2009-08-03T00:00:00+00:00https://codecrate.com/2009/08/end-of-adobe-air<p>I have a dream where our developer children will hear the name “Adobe” and not cringe. I can see a day where we won’t need proprietary and hacky plugins to solve our most basic web application (and rich desktop) needs. HTML5 is the light on the horizon and Google is her knight in shining armor.</p>
<p>I’ve built my fair share of cross platform desktop applications in Java, and over the past several months, I’ve built a fairly successful AIR app. I have no doubt that it was the right decision at the time the project started, but I wouldn’t make the same choice again. The Adobe AIR platform’s days are numbered, and here’s why…</p>
<p>AIR claims to be the perfect solution for both Flash/Flex developers and HTML/CSS developers. Unfortunately, that’s a load of crap and any web developer that has tested the waters with the AIR platform knows that it’s only good for one thing, Twitter clients. AIR is 100% geared towards Flash/Flex developers and the HTML/CSS/Javascript API’s are a bolt-on hacked into the SDK. The amount of information available for developing HTML/CSS/Javascript applications using AIR is laughable at best. Nearly every article of documentation/forums/blogs refer to the Flex API’s and it’s an exercise for the reader to reverse engineer the Javascript API (if even possible).</p>
<p>My very “scientific” research shows that nearly 15 ka-jillion webpages that have been built over the past 10 years. To say the least, web technologies have proven insanely successful and the number of developers that are familiar with HTML/CSS/Javascript technologies is ridiculous. By comparison, there are roughly 5 million Java developers, 3 million .NET developers and 2 million Flash developers. Adobe is targeted at Flash/Flex developers, Sun is pushing Java FX and Microsoft is promoting Silverlight as the rich desktop solution. That leaves a huge open market of web developers with the skillset needed to apps with HTML/CSS/Javascript technologies. <a href="http://titaniumapp.com/">Titanium</a> is emerging as the current market leader, and Google will be entering into this market very soon with the <a href="http://googleblog.blogspot.com/2009/07/introducing-google-chrome-os.html">Google Chrome OS</a>.</p>
<p>The web browser has already proven to be the best cross-platform runtime environment and Webkit has become the de-facto standard for embedded browsers. You’d think that using Webkit with AIR would be a good thing. Unfortunately, the version of Webkit packaged with AIR is stripped down and makes even simple things like customizing the scrollbars impossible. Adobe had an opportunity to really push browser rendering forward by embracing HTML Canvas, but instead they’ve done a wonderful job at crippling the browser environment in such a way to force developers to use Flex/Flash to build visually compelling applications.</p>
<p>The Adobe AIR security model has literally put me at my wits end. From sandboxing to certificate signing, I can’t count the number of number of grey hairs on my head due to the ridiculous restrictions of the AIR SDK. My question is why put such extreme handcuffs on the developer? If something is technically feasible, why put in <em>extra</em> development work to restrict the SDK API’s? A sandboxed environment makes sense on the web, but not for distributed desktop applications. The majority of popular AIR applications use self signed certificates, but this is taboo according to Adobe in an effort to push purchasing potentially expensive code-signing certificates. Signed applications are important, but whenever I install any application, I need to trust the developer regardless of the signed certificate.</p>
<p>Hell, all I want from a desktop SDK is the ease of auto-updating clients as if I was deploying a website. <a href="http://forums.adobe.com/thread/462791">AIR can’t seem to get that right either</a>…</p>
<p>HTML5 has the very real opportunity to give web developers the API’s needed to build great rich desktop applications without proprietary components. Audio/Video and filesystem API’s will give web developers a real chance to build kick ass stuff. Browser extensions like Greasemonkey and Google Gears have proven the technology stack is viable, and we’ve seen the iPhone and Palm Pre’s SDK’s successfully leverage these technologies. Now, we need to push this stack onto every desktop. Waiting for HTML5 capable browser marketshare to reach end users is not realistic, but providing bundled desktop apps with HTML5 embedded browsers seems like a very real solution in today’s market.</p>
Backgrounded - Background Processing Done Right2009-07-22T00:00:00+00:00https://codecrate.com/2009/07/backgrounded-background-processing-done<p>I’m going to come right out and say it…</p>
<p>Every ruby background job solution sucks.</p>
<p>I’ve used a number of the popular libraries on various projects over the past year, and have yet to find one that “feels right”. They took an incredibly complex problem and made and even more complex solution. It really shouldn’t be this hard. All I want to do is take a unit of work from my model and kick it off into “magical background job land”. I don’t want to create separate “Worker” or “Job” classes which only exist to call back into my model object. If your background jobs are doing more work than that, you’re doing something wrong!</p>
<p>This is the API I want:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
<span class="n">user</span><span class="p">.</span><span class="nf">do_stuff_backgrounded</span>
</code></pre></div></div>
<p>This is the contract I envision for enabling background processing:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span>
<span class="err"> </span> <span class="n">backgrounded</span> <span class="ss">:do_stuff</span>
<span class="err"> </span> <span class="k">def</span> <span class="nf">do_stuff</span>
<span class="err"> </span> <span class="c1">#long running process here</span>
<span class="err"> </span> <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>I’ve released a Backgrounded on github at <a href="http://github.com/wireframe/backgrounded">http://github.com/wireframe/backgrounded</a> as a simple and concise API for invoking background jobs. It also provides a thin wrapper around the underlying job handler framework to support pluggable implementations. DelayedJob is supported out of the box, but it’s trivial to drop in support for bj, workling, or any other implementation.</p>
<p>Backgrounded also works great in unit tests as well by providing a “synchronous” handler so that your tests don’t need to wait for the background work to complete. No need for Thread.sleep!</p>
<p>I’m excited about this API for a number of reasons. The meta programming declaration doubles as documentation and makes it very clear what the developer is intending to do. It also allows for backgrounded internals to declaratively create the backgrounded methods ahead of time and remove the need for ugly “method_missing” handling. Yay for clean stacktraces and accurate listing of methods (including IRB method autocompletion)!</p>
<p>DelayedJob supports a slightly similar <em>alternative</em> API (ex: User.send_later(:do_something)), but their primary usecase revolves around creating a secondary Job class to perform your work. I’ve thought about forking the delayed job project to support my syntax, but for now I’ll leave it as a separate project. Let me know if there’s any interest in having this merged into the core delayed_job project.</p>
notify_if_invalid Plugin Released2009-07-13T00:00:00+00:00https://codecrate.com/2009/07/notifyifinvalid-plugin-released<p>Rails does a great job at making some of the headaches of building stateful webapps go away. In particular, form validation has always been a complex area in web frameworks, and Rails handles this beautifully. It’s absolutely trivial to re-render a form and give decent feedback to the user what went wrong.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">UsersController</span>
<span class="k">def</span> <span class="nf">create</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span> <span class="n">params</span><span class="p">[</span><span class="ss">:user</span><span class="p">]</span>
<span class="k">if</span> <span class="n">user</span><span class="p">.</span><span class="nf">save</span>
<span class="c1">#looks good!</span>
<span class="n">redirect_to</span> <span class="n">user_path</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="k">else</span>
<span class="c1">#something is wrong, re-render the form</span>
<span class="n">render</span> <span class="ss">:action</span> <span class="o">=></span> <span class="ss">:new</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This is all well and good, but there’s a slight issue with this pattern. Re-rendering the form is a great user interaction, but we’ve effectively hidden the fact that the user encountered an error. The fact that the user was unable to save the form is a very important fact to record. It could mean that:</p>
<ul>
<li>the model object is not able to be constructed given the information on the page (ex: missing attributes)</li>
<li>the design is not intuitive and user’s missed important information</li>
</ul>
<p>Either way, it is important to record and measure these events. In my experience, it has been applicable to consider these validation errors as important as actual application errors. The fact that the user was able to construct an “invalid” object is just another opportunity for the user to drop out of your application, never to return.</p>
<p>I’ve built a plugin that will assist in recording these events in <a href="http://hoptoadapp.com/">HopToad</a> (my preferred error monitoring tool). The notify_if_invalid plugin is a Rails plugin that will record a ValidationError in HopToad anytime a user creates an invalid ActiveRecord Model. This plugin is available on github at <a href="http://github.com/wireframe/notify_if_invalid">http://github.com/wireframe/notify_if_invalid</a> and has a super simple API.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span>
<span class="n">notify_if_invalid</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Done!</p>
<p>I’m open to any suggestions for naming this plugin, and I still need to convert this to a gem. I’m not a fan of Rails plugins, but they are so damn easy to create! Let me know if you see opportunities for improvement!</p>
Testing is a Roadblock2009-07-12T00:00:00+00:00https://codecrate.com/2009/07/testing-is-roadblock<p>Testing are vital part of any development process for a lot of reasons.
I’ve talked about testing quite <a href="/2006/04/running-code-doesn-lie.html">frequently</a>
<a href="/2005/07/actions-speak-louder-than-words.html">on this</a>
<a href="/2008/04/say-it-do-it-prove-it.html">blog</a>, and over the past year,
I’ve learned a new key benefit of testing:
<strong>Testing creates a roadblock to prevent unnecessary code/features from being written</strong>.</p>
<p>Some people claim that simple code don’t need tests. My response is, “if code doesn’t have tests, it wasn’t worth writing in the first place.” If it’s so trivial that you don’t need tests, why are you writing it? Is it boilerplate code for getter/setters required by your framework? That’s a sign you’re using the wrong tool/language for the job.</p>
<p>Writing tests forces you to put what you’re thinking in your head down into writing. If it’s not worth the effort to take a moment and reflect on how it’s supposed to work, it’s not worth putting into code and it doesn’t deserve to be in your system!</p>
<p>This barrier to entry also prevents the “wouldn’t it be cool” features that provide absolutely nocore business value. All that’s usually needed is to simply ask, “How are we going to test this?” to stop the conversation dead in it’s tracks. By carrying around the Big Testing Stick (BTS), you can knock these features flat on their ass if no one is willing to invest the time to actually think through the feature at hand.</p>
<p>At a very practical level, this mentality has led me to invest time extracting or reusing plugins from the Rails community to accomplish tasks that I were not worth me taking the time to describe and test. Sure, most of these helper plugins are fairly trivial and I could have cranked out the code in a matter of minutes, but this mantra has kept my project codebase a bit leaner. This has additional benefits by reducing the long term maintenance cost of your application and lowers the cognitive load required to get new developers up and running.</p>
Adios JRoller2009-07-12T00:00:00+00:00https://codecrate.com/2009/07/adios-jroller<p>I’ve talked about migrating off of JRoller for a long time, and the time has finally come. The new home for this blog is officially at:</p>
<p><a href="http://blog.codecrate.com/">http://blog.codecrate.com</a></p>
<p>Unfortunately, there’s no good way to migrate blog entries between systems, so my old blog will stay up in an “archived” state at <a href="http://jroller.com/wireframe">http://jroller.com/wireframe</a> from here on out. You’d think with all of the standardization on RSS and Atom that it would be relatively simple to migrate posts (I’m not concerned with migrating comments). I’ve tested out various <a href="http://code.google.com/p/google-blog-converters-appengine/wiki/BloggerExportTemplate">atom export/import hacks</a> with no luck thus far.</p>
<p>The focus of this blog will remain primarily the same. Technology is in my blood, so there will continue to be regular posts about programming, software development, testing, etc. In addition, I will be expanding my posts to include a little bit more about myself and personal interests. We’ll see where it goes and I welcome any feedback.</p>
<p>Anyone subscribed to the feedburner RSS feed should automatically be updated to the new blog location.</p>
acts_as_stripped Now Available2009-06-27T00:00:00+00:00https://codecrate.com/2009/06/actsasstripped-now-available_2653<p>In my experience, it’s very common for web frameworks to automatically strip extra whitespace from posted forms. Wicket, for example just does the “right thing” by default, and it genuinely surprised me when I found out that Ruby on Rails does not do this by default.</p>
<p>Rails is a wonderfully pluggable framework, and so I’ve published a Ruby gem which will strip out extra whitespace for any string attributes. It’s called acts_as_stripped and can be found on github at <a href="http://github.com/wireframe/acts_as_stripped/">http://github.com/wireframe/acts_as_stripped/</a>. The Rails community is all about sexy project names, but I just couldn’t make myself name this little plugin “stripper”. :)</p>
<p>Usage of this plugin is incredibly simple:</p>
<h1 id="strip-whitespace-from-all-string-attributes">strip whitespace from <em>all</em> string attributes</h1>
<p>class User acts_as_stripped</p>
<p>end</p>
<h1 id="strip-whitespace-from-select-string-attributes">strip whitespace from <em>select</em> string attributes</h1>
<p>class Post acts_as_stripped :title, :summary</p>
<p>end</p>
<p>Drop me a line if there are any questions or suggestions. The nice benefit of using this plugin is that it works with any ActiveRecord model object and is not directly tied to the Rails web framework. </p>
<p>This plugin was inspired by this post: <a href="http://granth.ca/2006/02/strip-whitespace">http://granth.ca/2006/02/strip-whitespace</a></p>
CSS Sentences2009-06-19T00:00:00+00:00https://codecrate.com/2009/06/css-sentences_19<p>CSS psuedo selectors are pretty awesome and on my current project I’ve been able to take advantage of them for a fairly complex task, creating a humane sentence out of a list of items.</p>
<p>Here’s the markup I’m working with:</p>
<p> - Ryan</p>
<p> - Tom</p>
<p> - Bill</p>
<p>And here’s the output I want the users to see:</p>
<p>“Ryan, Tom and Bill found this interesting.”</p>
<p>Normally, I would use serverside processing (ex: rails helper) or javascript to do all the work, but CSS psuedo selectors are able to accomplish the same thing!</p>
<p>/* makes the list display inline */</p>
<p>ul { list-style-type: none; margin: 0; padding: 0; display: inline; }</p>
<p>ul li { background: none; margin: 0; padding: 0; display: inline; }</p>
<p>/* display a comma before the element */</p>
<p>ul li:before { content: ‘, ‘; }</p>
<p>/* use ‘ and ‘ instead of a comma for the last element */</p>
<p>ul li:last-child:before { content: ‘ and ‘; }</p>
<p>/* remove the prefix from the very first element */</p>
<p>ul li:first-child:before { content: ‘’; }</p>
<p>/* use a suffix to complete the sentance */</p>
<p>ul li:last-child:after { content: ‘ found this interesting.’; }</p>
<p>This solution isn’t applicable for most web applications if they need to support crappy web browsers <em>cough</em> IE <em>cough</em>, but for this project, I only need to support Webkit, and it works like a dream.</p>
Monitoring workling/starling queue with GOD2009-04-15T00:00:00+00:00https://codecrate.com/2009/04/monitoring-worklingstarling-queue-with_15<p><em>Everyone</em> knows that there’s no decent ruby solution for monitoring server side processes.</p>
<p><a href="http://god.rubyforge.org">GOD</a> is the best option we have (<a href="http://twitter.com/wireframe6464/status/1511506770">for now</a>), and we have to make do with the tools at hand. It is an absolutely cryptic and arcane library to work with, but luckily it is easily extensible to add new functionality.</p>
<p>I’ve been using starling/workling in my current project and needed to monitor the health of my starling queue. There can be sudden bursts of load on my starling queue, and the workling processes may fall behind and not process items in the queue fast enough. There is a starling_status script that can be used to manually check on the health of the queue, but I got a little tired of sitting at my keyboard day after day periodically running the script.</p>
<p>So, I wrote up a monitoring task that will notify me when the queue is backed up, and when/if it recovers back to a good state. Just drop this into your existing GOD configuration script, and tweak for the queue you need to monitor.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
God.task do |w|
w.name = "starling-queue"
w.interval = 1.minute
w.valid_states = [:healthy, :backed_up]
w.initial_state = :healthy
require 'yaml'
config = YAML.load_file("#{RAILS_ROOT}/config/workling.yml")[RAILS_ENV]
w.transition(:healthy, :backed_up) do |on|
on.condition(:queue_size) do |c|
c.port = config['listens_on']
c.queue = 'queue_my_workers__my_queue_items'
c.greater_than_size = 100
end
end
w.transition(:backed_up, :healthy) do |on|
on.condition(:queue_size) do |c|
c.port = config['listens_on']
c.queue = 'queue_my_workers__my_queue_items'
c.less_than_size = 100
end
end
end
</code></pre></div></div>
<p>Here is the GOD extension to connect and monitor the health of the starling queue. To install it, simply copy this code into your GOD configuration script as well.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
module God
module Conditions
class QueueSize require 'starling'
attr_accessor :port, :queue, :less_than_size, :greater_than_size
def initialize
super
self.port = nil
self.queue = nil
self.less_than_size = nil
self.greater_than_size = nil
end
def valid?
valid = true
valid &= complain("Attribute 'port' must be specified", self) if self.port.nil?
valid &= complain("Attribute 'queue' must be specified", self) if self.queue.nil?
valid &= complain("Attribute 'less_than_size' or 'greater_than_size' must be specified", self) if self.greater_than_size.nil? && self.less_than_size.nil?
valid
end
def test
server = Starling.new(self.port)
remaining = server.stats[self.port][self.queue]
if self.less_than_size
remaining.to_i else
remaining.to_i > self.greater_than_size
end
end
end
end
end
</code></pre></div></div>
<p>I only wish there was another option other than GOD to do this. Writing the extension was fairly straight forward, but the DSL for configuring transitions is absolutely awful. Maybe someone can write a <strong>usable</strong> DSL that re-uses the GOD extensions and exposes a more “humane” interface.</p>
Unit Test Valid SASS2009-03-25T00:00:00+00:00https://codecrate.com/2009/03/unit-test-valid-sass_25<p>How do you ensure that hacker developers like myself don’t check in invalid SASS? I can’t count the number of times I’ve checked in that “one tiny change”, that ended up breaking the layout of a page.</p>
<p>Continuous integration is obviously the best solution available, and here’s a test you can use in your application to ensure that all of the SASS will compile to valid CSS files.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="no">File</span><span class="p">.</span><span class="nf">dirname</span><span class="p">(</span><span class="kp">__FILE__</span><span class="p">)</span> <span class="o">+</span> <span class="s1">'/../test_helper'</span>
<span class="k">class</span> <span class="nc">SassTest</span> <span class="err"> </span>
<span class="k">def</span> <span class="nf">test_valid_sass</span>
<span class="err"> </span> <span class="n">run_cmd</span><span class="p">(</span><span class="s1">'rake sass:generate_css'</span><span class="p">)</span>
<span class="err"> </span> <span class="k">end</span>
<span class="err"> </span> <span class="kp">private</span>
<span class="err"> </span> <span class="k">def</span> <span class="nf">run_cmd</span><span class="p">(</span><span class="n">cmd</span><span class="p">)</span>
<span class="err"> </span> <span class="nb">puts</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">Running: </span><span class="si">#{</span><span class="n">cmd</span><span class="si">}</span><span class="s2">"</span>
<span class="err"> </span> <span class="n">assert</span> <span class="nb">system</span><span class="p">(</span><span class="n">cmd</span><span class="p">),</span> <span class="s2">"</span><span class="si">#{</span><span class="n">cmd</span><span class="si">}</span><span class="s2"> failed"</span>
<span class="err"> </span> <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
Simple Themes With SASS2009-03-05T00:00:00+00:00https://codecrate.com/2009/03/simple-themes-with-sass_05<p><a href="http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html">SASS</a> is an amazing library to have in your toolbox. Here’s a simple trick to make skinning your website drop dead easy…AND MAINTAINABLE!!</p>
<p>Let’s start with a simple HAML page that includes a specific stylesheet depending on the user’s current theme.</p>
<p>index.html.haml</p>
<div class="language-haml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">%html</span>
%head
//dynamically write in whichever theme the user has configured
= stylesheet_link_tag 'theme_default.css'
%body
hello world
%p.fancy_text
SASS is the bomb
</code></pre></div></div>
<p>Now, let’s create the SASS file for the specific theme. We’ll define all of our themeable properties as SASS variables, which will be used later on.</p>
<p>theme_default.sass</p>
<div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">!</span><span class="nt">textcolor</span> <span class="o">=</span> <span class="nt">red</span>
<span class="k">@import</span> <span class="s">themable.sass</span>
</code></pre></div></div>
<p>Can’t get much simpler than that! Now, we’ll define all of our themed elements and reference the variables declared in the specific theme file.</p>
<p>themable.sass</p>
<div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">.fancy_text</span>
<span class="err"> </span> <span class="nd">:color</span><span class="o">=</span> <span class="o">!</span><span class="nt">textcolor</span>
</code></pre></div></div>
<p>That’s it! Now, anytime you want to create a new theme, simply create a new SASS file, declare your variables, and import the common include file! Here’s a quick example…</p>
<p>theme_blue.sass</p>
<div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">!</span><span class="nt">textcolor</span> <span class="o">=</span> <span class="nt">blue</span>
<span class="k">@import</span> <span class="s">themable.sass</span>
</code></pre></div></div>
Zillow Ubiquity Plugin2009-03-04T00:00:00+00:00https://codecrate.com/2009/03/zillow-ubiquity-plugin_04<p>Let’s face it. The majority of house hunting websites out there suck. They’re slow, unusable and more often than not, make me want to put my head through a window.</p>
<p><a href="http://www.zillow.com">Zillow.com</a> is the first real estate website I’ve come across has a very compelling user experience complete with all the flashy web 2.0 features I’ve come to expect (especially mapping).</p>
<p>Unfortunately, I don’t currently have the ability to manage everything I need in Zillow, so I find myself flipping back and forth from real estate listing sites into Zillow. I finally had enough and decided to whip up a Ubiquity command to integrate with the Zillow API. This allows me to keep cruising on my current website, and mash up the great estimation features of Zillow.</p>
<p> Here’s how it works.</p>
<p>1. Install the <a href="http://gist.github.com/74198">Zillow Ubiquity command available on github</a>.</p>
<ol>
<li>
<p>Search the web for a property that interests you.</p>
</li>
<li>
<p>Highlight the address that you want to inquire about.</p>
</li>
<li>
<p>Invoke the Zillow Ubiquity command.</p>
</li>
</ol>
<p> </p>
<p>Voila! Now you have access to the property estimated value while keeping you in the flow of browsing your current site.</p>
<p> As an added bonus, you can open up the Zillow page for that property by pressing enter on the Ubiquity preview window.</p>
<p> </p>
<p>One drawback of the current implementation is that the Zillow API is very picky about passing an address with a zip code. Ideally, I could use a mashup with google maps to decipher the zipcode without forcing the user to enter one. Any suggestions would be helpful!</p>
The Science Of Random2009-02-12T00:00:00+00:00https://codecrate.com/2009/02/science-of-random<p>How Darwinistic Evolution has survived any amount of scientific scrutiny is beyond me. At its core, any scientific theory based on randomness (ie: random genetic mutations), is no theory at all. In order to prove the theory, you would need to assert that randomness is indeed true and since randomness is equivalent to chaos, it is neither true nor false and can never be proven.</p>
<p>Given a controlled environment, the simplest of “random” events (ex: flipping a coin) can be most assuredly “proven” to flip either heads or tails on command. The “randomness” that we perceive is nothing more than a list of factors that influence a given event to go one way or another (ex: wind + spin + gravity + other minute details our tiny brains can not comprehend).</p>
<p>My point is that there is no such thing as a “random” event. A person who believes in a designed plan and order to life has a much more solid philosophical and scientific foundation for the definition of truth than the fool who believes blindly in the percieved “truth” of randomness.</p>
Real Love2009-01-28T00:00:00+00:00https://codecrate.com/2009/01/real-love<p>A old man and woman have been married for fifty years and love each other very much. Every evening they eat toast for supper. The toaster they own is a real junker and always burns one piece while leaving the other piece uncooked.</p>
<p>Now, the old man loves burnt toast, but every evening he eats the untoasted bread thinking to himself that his wife would enjoy the piece of burnt toast.</p>
<p>The old woman loves untoasted bread, but every evening she eats the burnt toast thinking to herself that her husband would enjoy the piece of untoasted bread.</p>
<p>This is real love…</p>
3 keys to decision making2009-01-28T00:00:00+00:00https://codecrate.com/2009/01/3-keys-to-decision-making<ol>
<li>Truly have to believe that you’re making the right choicegiven the options and information at hand.</li>
<li>Rely on a strong foundationfor your decision making. Scripture based teaching is key.</li>
<li>Know that the outcome is in God’s hands. No matter the seemingly “good” or “bad” outcome of our decision, it all works according to God’s plan.</li>
</ol>
<p>Romans 8:28</p>
<p>And we know that in all thingsGod works for the good of those who love him, who have been called according to his purpose.<a href="http://christianity.about.com/od/faqhelpdesk/p/newinternationa.htm">(NIV)</a></p>
<p> </p>
The Quest for Correct Content Types2009-01-09T00:00:00+00:00https://codecrate.com/2009/01/quest-for-correct-content-types_09<p><a href="http://github.com/technoweenie/attachment_fu/tree/master%20">Attachment Fu is a kick ass rails plugin</a> for handling file uploads within your rails application. It greatly simplifies the ordeal of supporting file uploads and even supports some really amazing features like using Amazon S3 as a backend to store your files. My only gripes thus far have been finicky thumbnail generation…</p>
<p>_<strong>And</strong>_correct detection of the file content type…</p>
<p>I’m using a <a href="http://developer.yahoo.com/yui/uploader/%20">flash widget for file uploads</a> in my app and it’s been a pretty good solution except for the fact that flash kind of “forgets” to send the file content type to the server. <em>Oooppps</em>! You see, browsers are responsible for including the content type when they post the file to the server and not having the correct content type causes all sorts of funky issues when the file is downloaded. For example, a MS Word document will open with the wrong application if you don’t have the correct content type.</p>
<p>Since <a href="http://swfupload.org/forum/generaldiscussion/166%20">web browsers are not exactly any more trustworthy than flash</a><em>*cough* IE *cough*</em>, it would be prudent to have the server do it’s best to detect and/or correct the mime type sent by the client browser. This led me to create <a href="http://github.com/wireframe/attachment_fu%20">a fork of the attachment_fu project</a> and improve the support for determining content types if/when the browser was unable to do so.</p>
<p>My solution is to determine the file content type by checking a chain of different mime type decision points. First and foremost, the content type from the browser is used if available. If one is not given, or if the browser is unable to determine the content type, a series of fallback implementations try to reconcile the issue.</p>
<p>The first fallback is to rely on the file extension to lookup the mime type. This is a very simple and flexible solution that allows for easy addition/customization of accepted mime types. Registering new mime types in rails is a snap, and this solution was necessary for me to support the new ms office 2007 document types.</p>
<p>Using the unix ‘file’ command to detect the content type is the next fallback. This solution inspects the contents of the file to determine the file type. It works relatively well except for when file contents are not necessarily unique. For example, <a href="http://www.mediawiki.org/wiki/Manual_talk:Mime_type_detection%20">all ms-office documents are reported as application/msword due to the file contents being nearly identical</a>.</p>
<p>If all else fails, we simply set the content type to “application/octet-stream” which basically means “unknown binary data”.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># example code for the implementation.</span>
<span class="c1"># real code available at github</span>
<span class="k">def</span> <span class="nf">uploaded_data</span><span class="o">=</span><span class="p">(</span><span class="n">file_data</span><span class="p">)</span>
<span class="n">default_mime_type</span> <span class="o">=</span> <span class="s1">'application/octet-stream'</span>
<span class="n">browser_content_type</span> <span class="o">=</span> <span class="p">(</span><span class="n">file_data</span><span class="p">.</span><span class="nf">respond_to?</span><span class="p">(</span><span class="ss">:content_type</span><span class="p">)</span> <span class="p">?</span> <span class="n">file_data</span><span class="p">.</span><span class="nf">content_type</span> <span class="p">:</span> <span class="n">file_data</span><span class="p">[</span><span class="s1">'content_type'</span><span class="p">]).</span><span class="nf">to_s</span><span class="p">.</span><span class="nf">strip</span>
<span class="n">browser_content_type</span> <span class="o">=</span> <span class="kp">nil</span> <span class="k">if</span> <span class="n">browser_content_type</span><span class="p">.</span><span class="nf">blank?</span> <span class="o">||</span> <span class="n">browser_content_type</span> <span class="o">==</span> <span class="n">default_mime_type</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">content_type</span> <span class="o">=</span> <span class="n">browser_content_type</span> <span class="o">||</span> <span class="n">file_extension_content_type</span> <span class="o">||</span> <span class="n">native_content_type</span> <span class="o">||</span> <span class="n">default_mime_type</span>
<span class="k">end</span>
<span class="c1"># uses the os’s “file” utility to determine the file type, yanked and modified slightly from file_column.</span>
<span class="c1"># see http://blog.vixiom.com/2007/12/28/hacking-attachment_fu-to-work-with-flashflex-uploads-and-crop-square-images/</span>
<span class="k">def</span> <span class="nf">native_content_type</span>
<span class="k">begin</span>
<span class="c1">#mac osx uses -I instead of -i</span>
<span class="n">file_flags</span> <span class="o">=</span> <span class="p">(</span><span class="no">RUBY_PLATFORM</span><span class="p">.</span><span class="nf">index</span><span class="p">(</span><span class="s1">'darwin'</span><span class="p">)</span> <span class="p">?</span> <span class="s1">'-bI'</span> <span class="p">:</span> <span class="s1">'-bi'</span><span class="p">)</span>
<span class="n">file</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">temp_path</span><span class="p">)</span>
<span class="n">content_type</span> <span class="o">=</span> <span class="sb">`file </span><span class="si">#{</span><span class="n">file_flags</span><span class="si">}</span><span class="sb"> "</span><span class="si">#{</span><span class="n">file</span><span class="si">}</span><span class="sb">" 2> /dev/null`</span><span class="p">.</span><span class="nf">chomp</span>
<span class="k">return</span> <span class="kp">nil</span> <span class="k">if</span> <span class="n">content_type</span><span class="p">.</span><span class="nf">blank?</span> <span class="o">||</span> <span class="o">!</span><span class="vg">$?</span><span class="p">.</span><span class="nf">success?</span>
<span class="n">content_type</span><span class="p">.</span><span class="nf">gsub!</span><span class="p">(</span><span class="sr">/;.+$/</span><span class="p">,</span><span class="s2">""</span><span class="p">)</span>
<span class="k">rescue</span>
<span class="kp">nil</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="c1"># determine the content_type based on the file extension.</span>
<span class="k">def</span> <span class="nf">file_extension_content_type</span>
<span class="n">types</span> <span class="o">=</span> <span class="no">MIME</span><span class="o">::</span><span class="no">Types</span><span class="p">.</span><span class="nf">type_for</span><span class="p">(</span><span class="nb">self</span><span class="p">.</span><span class="nf">filename</span><span class="p">)</span>
<span class="n">types</span><span class="p">.</span><span class="nf">empty?</span> <span class="p">?</span> <span class="kp">nil</span> <span class="p">:</span> <span class="n">types</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">content_type</span>
<span class="k">end</span>
</code></pre></div></div>
<p>I’ve been using this solution in my app for the past several months and have been very happy with the results. Leave me any comments if you have other ideas/suggestions for improvements!</p>
Giving is a gift2009-01-04T00:00:00+00:00https://codecrate.com/2009/01/giving-is-gift<p>NOT an obligation.</p>
<p>It is such a blessing to be a part of the work that God is doing here on earth.</p>
<p>Why do so many organizations guilt people into giving instead of focusing on the JOY that comes from it?</p>
<p>It’s a problem of transparency. People can not rejoice in good that their gifts do if they don’t know what their giving is actually doing. </p>
Every Choice is the Culmination of Your Life2009-01-04T00:00:00+00:00https://codecrate.com/2009/01/every-choice-is-culmination-of-your<p>“Every moment in your life has built you for the decision at hand. No matter how insignificant, the outcome will shape you for the next decision ahead.”</p>
<ul>
<li>Me</li>
</ul>
Fork it up - assert valid markup2008-12-22T00:00:00+00:00https://codecrate.com/2008/12/fork-it-up-assert-valid-markup_22<p>Unit testing view layers has always been a difficult problem for me. I haven’t run across a lot of libraries that I’ve found valuable, mainly because they’re too slow. I’ve found that no matter how good the tests are, if they’re slow, they don’t get run.</p>
<p>I was pretty excited when I ran across the <a href="http://github.com/wr0ngway/assert_valid_markup/tree/master">assert_valid_markup plugin</a> which allows me to unit test that my pages are xhtml compliant. It’s wicked fast because it relies on locally installed binaries (xmllint), but it also has a nice fallback to use the w3c xml validation service.</p>
<p>The syntax for the plugin is very slick and doesn’t require any unnecessary setup.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>class FooControllerTest assert_valid_markup :index, :show
end
</code></pre></div></div>
<p>I’ve been using this plugin for about a month, and ran across a pretty major issue today when running my unit tests on our continuous integration server (Cruisecontrol). All tests ran great on my local instance, but tests were failing in our shared environment with some very cryptic error messages.</p>
<p>_no such file to load – FileUtils</p>
<p>/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in</p>
<p>`gem_original_require’</p>
<p>/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in</p>
<p>`require’</p>
<p>/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in</p>
<p>`require’</p>
<p>/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in</p>
<p>`new_constants_in’</p>
<p>/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in</p>
<p>`require’</p>
<p>/home/eventrobot/.cruise/projects/socialcast/work/vendor/plugins/assert_valid_markup/lib/assert_valid_markup.rb:5</p>
<p>/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require’ _
After digging through the plugin source code, I did what any inquisitive developer would do, <strong>FORK IT UP</strong>! <a href="http://github.com/wireframe/assert_valid_markup/commit/637088fbd8ff8d1d507a8d07403ca92e04b9a684%20%20">A small change</a> to the plugin and I was back up and running…almost. Another issue cropped up when running the tests through Cruisecontrol.</p>
<p>_/usr/local/bin/ruby -Ilib:test</p>
<p>“/usr/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb”</p>
<p>/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in</p>
<p>`gem_original_require’: no such file to load –</p>
<p>active_support/breakpoint (MissingSourceFile)</p>
<p>from</p>
<p>/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in</p>
<p>`require’</p>
<p>from</p>
<p>/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in</p>
<p>`require’</p>
<p>from</p>
<p>/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in</p>
<p>`new_constants_in’</p>
<p>from</p>
<p>/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in</p>
<p>`require’</p>
<p>from ./vendor/plugins/ez-where/test/test_helper.rb:6 _</p>
<p>Tracking down this issue was a real pain. I spend the majority of my afternoon banging my head against the wall, but <a href="http://github.com/wireframe/assert_valid_markup/commit/5883b603b5cf6381fc75364756d496f30c886cdf%20%20">I eventually tracked it down</a>. Tests are now up and running, and I have a github project with all of my fixes available for anyone to check out. I’m still not 100% clear on the differences between my local environment and cruisecontrol, but that’s for another time.</p>
<p>I may take this fork a bit further and turn it into a ruby gem instead of a rails plugin. It seems better suited that way now that I ripped out the rails initializer code.</p>
Fork it up - CSS Browser Selectors2008-12-19T00:00:00+00:00https://codecrate.com/2008/12/fork-it-up-css-browser-selectors_19<p>If you’re really passionate about designing great websites, browser specific CSS is a necessary evil. We all wish it wasn’t needed, but thanks to web browsers that suck ass <em>cough</em> IE <em>cough</em>, we need an effective way to alter our CSS styles based on browsers.</p>
<p>There are lots of different solutions for how to implement browser specific CSS. Options range from <a href="http://rafael.adm.br/css_browser_selector/">javascript</a> or <a href="http://www.quirksmode.org/css/condcom.html">conditional comments</a> to <a href="http://latimes.rubyforge.org/svn/plugins/css_browser_selector/">server side solutions</a>. The Ruby on Rails <a href="http://github.com/latimes/css_browser_selector/tree/master">CSS Browser Selector plugin</a> is by far</p>
<p>the best solution I’ve used. It is a very simple plugin that</p>
<p>automatically adds some extra CSS classes to your html so that you’re</p>
<p>able to apply extra styling based on browser (or operating system). </p>
<p>It’s drop dead easy to integrate into your project, and allows you to</p>
<p>keep your browser specific hacks in context with the rest of your styling. </p>
<p>example rendered html source:</p>
<p>
hello world
===========</p>
<p>example css for browser specific styles:</p>
<p>span.date {</p>
<p> color: blue;</p>
<p>}</p>
<p>body.ie6 span.date {</p>
<p> padding: 2px;</p>
<p>}</p>
<p>If you want to make these browser specific hacks even more managable, take a look at SASS:</p>
<p>span.date</p>
<p> :color blue</p>
<p> body.ie6 &</p>
<p> :padding 2px</p>
<p>I have not seen server side solution like this for the Java world, but maybe one of those wicked Wicket developers can whip something up! =)</p>
<p>That’s enough backstory on this awesome plugin. The real point of this post was to announce that I have <a href="http://github.com/wireframe/css_browser_selector/tree/master">forked the CSS Browser Selector plugin</a></p>
<p>to run on Rails 2.2 with no deprecation warnings. Super small change,</p>
<p>but it should make your life a bit better by removing the annoying</p>
<p>deprecation warnings. Check it out on <a href="http://github.com/wireframe/css_browser_selector/tree/master">github</a>.</p>
<p>Oh, and my personal favorite browser specific CSS trick is this:</p>
<p>body.ie6 {</p>
<p> display: none;</p>
<p>}</p>
Life Motto (3)2008-12-02T00:00:00+00:00https://codecrate.com/2008/12/life-motto-3<p>“Do your job…..plus one….”</p>
<ul>
<li>Me</li>
</ul>
<p>This is somewhat related to my previous post, but slightly different. My previous post was about not putting off to to tomorrow what you can do today. This is about going the extra mile in what you do. It’s very easy to “Just do your job”, which inevitably leads to shoddy work with plenty of loose ends. If you really care about what you’re doing, it’s necessary to take the extra step to put the final touches on things.</p>
<p>Similar quote:</p>
<p>“It takes 90% effort to complete 90% of the work. It takes another 90% effort to complete the job.”</p>
Life Motto (2)2008-12-02T00:00:00+00:00https://codecrate.com/2008/12/life-motto-2<p>If you don’t do it, who will?</p>
<ul>
<li>Me</li>
</ul>
<p>Valuable life lesson I’ve learned time and time again. You can not leave a job undone and expect someone else to pick up the pieces. This is very valuable to me right now because with my amazing wife working so hard, I can no longer sit idol and expect that things will magically get done.</p>
My Strongest Strength2008-11-28T00:00:00+00:00https://codecrate.com/2008/11/my-strongest-strength<p>Today I took a personality survey called “<a href="https://www.strengthsfinder.com/">The Strengh Finder</a>”, and it got me thinking. The test rated my top five strengths as:</p>
<ul>
<li>
<p>Belief -</p>
</li>
<li>
<p>Connections - understanding the cause/effect connectedness of things.</p>
</li>
<li>
<p>Responsibility -</p>
</li>
<li>
<p>Relatable - bond with small group of people that I can be very open around.</p>
</li>
<li>
<p>Intellectual -</p>
</li>
</ul>
<p>Is my belief really a talent that I was born with? A natural resource that is deep inside me waiting to be tapped to it’s fullest potential? I’ve always thought that the strength of my belief has come from years of personal discovery and investigation, but maybe there is something more to it then that. I’ve always wanted to believe in something. There has always been a deep yearning inside me to believe in things greater than myself.</p>
<p>There is a significant challenge that stands before me now. I know I am not challenging my belief and pushing it to the next level. I’m happy to stand quietly on the sidelines and cheer others on as they blaze a trail for Christ. This is not who God intended me to be. I was built with passion as one of the strongest fibers in my being. I’ve learned to use that passion for my work. I need to use that same level of intense, deep passion for my faith life. God has been so gracious, but how many second chances do I have to get my act together? I need to start living, really living, right now!</p>
Life Motto2008-11-28T00:00:00+00:00https://codecrate.com/2008/11/life-motto<p>“How are you going to change the world? Right here. Right now.”</p>
<ul>
<li>Me</li>
</ul>
Fork it up - acts_as_state_machine2008-11-04T00:00:00+00:00https://codecrate.com/2008/11/fork-it-up-actsasstatemachine_04<p>Consider the following class definition:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Door</span>
<span class="n">acts_as_state_machine</span> <span class="ss">:initial</span> <span class="o">=></span> <span class="ss">:open</span>
<span class="n">state</span> <span class="ss">:closed</span>
<span class="n">state</span> <span class="ss">:open</span>
<span class="n">event</span> <span class="ss">:lock</span> <span class="k">do</span>
<span class="n">transitions</span> <span class="ss">:from</span> <span class="o">=></span> <span class="ss">:open</span><span class="p">,</span> <span class="ss">:to</span> <span class="o">=></span> <span class="n">closed</span>
<span class="k">end</span>
<span class="n">event</span> <span class="ss">:unlock</span> <span class="k">do</span>
<span class="n">transitions</span> <span class="ss">:from</span> <span class="o">=></span> <span class="ss">:closed</span><span class="p">,</span> <span class="ss">:to</span> <span class="o">=></span> <span class="nb">open</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Now, what is wrong with this script?</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">door</span> <span class="o">=</span> <span class="no">Door</span><span class="p">.</span><span class="nf">new</span>
<span class="n">door</span><span class="p">.</span><span class="nf">lock!</span> <span class="c1">#=> closes the door</span>
<span class="n">door</span><span class="p">.</span><span class="nf">lock!</span> <span class="c1">#=> doesn't do anything. door is already closed</span>
</code></pre></div></div>
<p>The script <strong><em>should</em></strong> produce an error because the _lock_event does not have a valid transition when the door is already in the _closed_state. Instead, the current _acts_as_state_machine_plugin quietly returns _false_if
there is no valid transition. That definitely isn’t what I expected
and seriously took me several hours to track down this mysterious
behavior.</p>
<p>I have published [a fork of the <em>acts_as_state_machine_project](http://github.com/wireframe/acts_as_state_machine/tree/master) which _<strong>correctly</strong></em> raises exceptions if there are no valid transitions available. The code change is very minor if you want to apply a patch to your own install.</p>
<p>There’s an entire rant just ripe for the picking, but I’ll save that for
another time. For now, I’ve “scratched my own itch” and have made a
library work much more intuitively for me. I’m happy… =)</p>
Delicious Ubiquity Command2008-08-27T00:00:00+00:00https://codecrate.com/2008/08/delicious-ubiquity-command_27<h2 id="now-with-100-more-ajax">Now with 100% more AJAX!</h2>
<p>I couldn’t resist spending some more time with Ubiquity after yesterdays exciting release. My <a href="/2008/08/ubiquity-is-like-crack_26.html">first version of a delicious bookmarking command</a> worked, but it definitely wasn’t flashy. This was a perfect opportunity to learn the <a href="http://jquery.com/">JQuery javascript library</a> for AJAX interactions. I’m quite pleased with how it’s turned out.</p>
<p>The new version posts the current page to delicious using ajax and posts whatever tags you type into the preview panel. Feedback and error handling is <em>much_improved, and it will automatically prompt you for your delicious username/password on first use (just like the twitter integration). I’ve already been using it personally for posting my bookmarks and it’s amazing how intuitive this tool is. I don’t think I’ll ever go back. The official delicous bookmarklet and even the slick delicous firefox extension pale in comparison since it requires _evil</em> mouse interaction! </p>
<p>I’ve published my Ubiquity command on <a href="http://www.github.com">github</a>, and hopefully it’ll find a way onto the <a href="https://labs.toolness.com/ubiquity-herd/">official Ubiquity Herd</a> sometime in the future. In the meantime, I’d love to hear feedback or ideas for improvement! Feel free to fork my version, and tweak it to your hearts content!</p>
<p>You can download the command directly from github at <a href="http://gist.github.com/7516%20">http://gist.github.com/7516</a> or just copy this command into your command editor. Ubiquity can also auto-detect changes to the latest version if you subscribe to the command using <a href="http://gist.github.com/7516.txt">this link</a>.</p>
Ubiquity is Like Crack2008-08-26T00:00:00+00:00https://codecrate.com/2008/08/ubiquity-is-like-crack_26<p>Okay, I KNOW I might be jumping the gun here, but I just have to say that the new <a href="https://wiki.mozilla.org/Labs/Ubiquity">Firefox Ubiquity Plugin</a> is the greatest piece of software written. EVER.</p>
<p>Well, maybe that is jumping the gun a bit, but I am extremely excited to see where this project goes. I have been very interested in language driven UI’s and this is the first time I’ve seen such an aggressive push for enabling non-developers to write extensions. This could be huge. Just think of all the wanna be hackers out there with just a little bit of javascript experience being able to create and deploy mashups that had previously been behind developer’s lock and key.</p>
<p>They have done an excellent job of giving you all the tools you need to succeed. The editor is built in. No SDK, no extra installation, and best of all, dynamic reloading of your commands (no restarts needed!). Seriously, I’m a total hack at javascript, and I was able to whip up this simple little integration with <a href="http://www.delicious.com">delicious</a> in about 20 minutes.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">CmdUtils</span><span class="p">.</span><span class="nx">CreateCommand</span><span class="p">({</span>
<span class="err"> </span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">delicious</span><span class="dl">"</span><span class="p">,</span>
<span class="err"> </span> <span class="na">homepage</span><span class="p">:</span> <span class="dl">"</span><span class="s2">http://ryan.codecrate.com/</span><span class="dl">"</span><span class="p">,</span>
<span class="err"> </span> <span class="na">author</span><span class="p">:</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Ryan Sonnek</span><span class="dl">"</span><span class="p">,</span> <span class="na">email</span><span class="p">:</span> <span class="dl">"</span><span class="s2">ryan@codecrate.com</span><span class="dl">"</span><span class="p">},</span>
<span class="err"> </span> <span class="na">contributors</span><span class="p">:</span> <span class="p">[</span><span class="dl">"</span><span class="s2">Ryan Sonnek</span><span class="dl">"</span><span class="p">],</span>
<span class="err"> </span> <span class="na">license</span><span class="p">:</span> <span class="dl">"</span><span class="s2">MIT</span><span class="dl">"</span><span class="p">,</span>
<span class="err"> </span> <span class="na">description</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Tags the current site using delicious</span><span class="dl">"</span><span class="p">,</span>
<span class="err"> </span> <span class="na">preview</span><span class="p">:</span> <span class="dl">"</span><span class="s2">bookmark the current url on delicious</span><span class="dl">"</span><span class="p">,</span>
<span class="err"> </span> <span class="na">execute</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="err"> </span> <span class="kd">var</span> <span class="nb">document</span> <span class="o">=</span> <span class="nx">context</span><span class="p">.</span><span class="nx">focusedWindow</span><span class="p">.</span><span class="nb">document</span><span class="p">;</span>
<span class="err"> </span> <span class="kd">var</span> <span class="nx">selected_text</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getSelection</span><span class="p">();</span>
<span class="err"> </span> <span class="kd">var</span> <span class="nx">params</span> <span class="o">=</span> <span class="nx">Utils</span><span class="p">.</span><span class="nx">paramsToString</span><span class="p">({</span>
<span class="err"> </span> <span class="na">url</span><span class="p">:</span> <span class="nb">document</span><span class="p">.</span><span class="nx">location</span><span class="p">,</span>
<span class="err"> </span> <span class="na">title</span><span class="p">:</span> <span class="nb">document</span><span class="p">.</span><span class="nx">title</span><span class="p">,</span>
<span class="err"> </span> <span class="na">notes</span><span class="p">:</span> <span class="nx">selected_text</span>
<span class="err"> </span> <span class="p">});</span>
<span class="err"> </span> <span class="nx">Utils</span><span class="p">.</span><span class="nx">openUrlInBrowser</span><span class="p">(</span><span class="dl">'</span><span class="s1">http://delicious.com/save</span><span class="dl">'</span><span class="o">+</span><span class="nx">params</span><span class="p">);</span>
<span class="err"> </span> <span class="p">}</span>
<span class="p">})</span>
</code></pre></div></div>
<p>Now we just need a <a href="http://www.github.com">github</a> repo to create these commands and fork away!</p>
The End Of Dependency Injection2008-08-09T00:00:00+00:00https://codecrate.com/2008/08/end-of-dependency-injection_09<p>Dependency Injection is a common technique in Java applications. I have a long history of Java development in a Test Driven Development environment so Dependency Injection has been a way of life for a long time. It’s a tried and true practice and is an absolute requirement when developing Java software, but it’s simply not needed when working with a dynamic language like Ruby. Why?</p>
<p>If you want to write testable Java code, you NEED Dependency Injection. Let’s start with an example.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//Without Dependency Injection</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="err"> </span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">doWork</span><span class="o">()</span> <span class="o">{</span>
<span class="err"> </span> <span class="nc">DatabaseConnection</span> <span class="n">connection</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DatabaseConnection</span><span class="o">();</span>
<span class="err"> </span> <span class="n">connection</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>
<span class="err"> </span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>What makes this previous block of Java code untestable? It’s because of the “new” keyword. In Java, “new” is a magic keyword and there’s nothing you can do to circumvent the code that executes when it fires. In order to test the my code with various DatabaseConnection behavior, you need to inject the DatabaseConnection so unit tests can configure the expected behavior.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//With Dependency Injection</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="err"> </span> <span class="kd">private</span> <span class="kd">final</span> <span class="nc">DatabaseConnection</span> <span class="n">connection</span><span class="o">;</span>
<span class="err"> </span> <span class="kd">public</span> <span class="nf">MyService</span><span class="o">(</span><span class="nc">DatabaseConnection</span> <span class="n">connection</span><span class="o">)</span> <span class="o">{</span>
<span class="err"> </span> <span class="k">this</span><span class="o">.</span><span class="na">connection</span> <span class="o">=</span> <span class="n">connection</span><span class="o">;</span>
<span class="err"> </span> <span class="o">}</span>
<span class="err"> </span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">doWork</span><span class="o">()</span> <span class="o">{</span>
<span class="err"> </span> <span class="n">connection</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>
<span class="err"> </span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>It’s unfortunate that making my code “testable” doubles the amount of code. It also reduces context of the code and makes its purpose less clear. Is this really necessary? In Ruby, “new” is just another method that you can easily override to facilitate testing and you don’t need to make any changes to your class to inject test dependencies.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#Ruby Code</span>
<span class="k">class</span> <span class="nc">MyService</span>
<span class="err"> </span> <span class="k">def</span> <span class="nf">do_work</span>
<span class="err"> </span> <span class="n">connection</span> <span class="o">=</span> <span class="no">DatabaseConnection</span><span class="p">.</span><span class="nf">new</span>
<span class="err"> </span> <span class="n">connection</span><span class="p">.</span><span class="nf">commit</span>
<span class="err"> </span> <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This Ruby code is just as testable as the previous Java example and there’s no Dependency Injection required. Instead of having to “jump through hoops” and inject the DatabaseConnection object into my class, I can just override the DatabaseConnection.new method to return a testable mock implementation.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="s1">'mocha'</span>
<span class="k">class</span> <span class="nc">MyServiceTest</span>
<span class="err"> </span> <span class="k">def</span> <span class="nf">test_can_mock_connection</span>
<span class="err"> </span> <span class="n">fake_connection</span> <span class="o">=</span> <span class="n">mock</span>
<span class="err"> </span> <span class="n">fake_connection</span><span class="p">.</span><span class="nf">expects</span><span class="p">(</span><span class="ss">:commit</span><span class="p">)</span>
<span class="err"> </span> <span class="no">DatabaseConnection</span><span class="p">.</span><span class="nf">expects</span><span class="p">(</span><span class="ss">:new</span><span class="p">).</span><span class="nf">returns</span><span class="p">(</span><span class="n">fake_connection</span><span class="p">)</span>
<span class="err"> </span> <span class="n">service</span> <span class="o">=</span> <span class="no">MyService</span><span class="p">.</span><span class="nf">new</span>
<span class="err"> </span> <span class="n">service</span><span class="p">.</span><span class="nf">do_work</span>
<span class="err"> </span> <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This sample test uses the excellent <a href="http://mocha.rubyforge.org/">mocha mock library</a>, which is very similar to JMock, to inject the test implementation. You can accomplish the same thing with standard ruby code, but the mocha library provides a very nice API for injecting test dependencies. The real difference here is that Ruby is an open language that allows for overriding implementation details. The beauty of Ruby is that this same approach can be applied to other areas that are normally very tricky for testing Java code (ex: static methods).</p>
<p>Some may raise the argument that Dependency Injection is intended for externalizing configuration to allow for multiple implementations, and not intended for increasing testability. That is a joke. When was the last time you used more than one implementation for your injected object? In reality, there are only two implementations. The real implementation, and the mock implementation used for testing. Dependency Injection is used for testability, not configuration. Period.</p>
Recent Shard Developments2008-07-06T00:00:00+00:00https://codecrate.com/2008/07/recent-shard-developments_06<p>It’s been a busy few weeks now that <a href="http://dndinsider.com">4th edition Dungeons and Dragons</a> is out the door! I’ve spent the majority of my free time digging into the new rule books, and you can definitely call me a fan of the new system. I’m very impressed by the streamlined game engine that avoids any “rule lawyering” and keeps the focus on having FUN!</p>
<p>To coincide with the 4th edition release, I’ve continued development on <a href="http://shard.codecrate.com">shard</a>. My initial goals are to revamp the codebase and prepare for implementing as many 4th edition rules as possible. The shard-grid API is first up and there are a few really exciting features that are underway. Of particular interest is a brand new path</p>
<p>finding algorithm that will dynamically build a path around obstacles</p>
<p>AND avoids difficult terrain whenever possible.</p>
<p>Some may question whether shard conflicts with the upcoming 4th edition digital tools, but I just can’t stand to see tools created that only run on Windows. Seriously, what self respecting D&D nerd willingly runs Windows!? The fact that I run Linux at home and a Mac at work and neither of these platforms are supported means that I’m out of luck and will be looking to other options for running my digital D&D campaign.</p>
<p>In other news, the shard codebase has moved off of <a href="http://shard.dev.java.net">java.net</a> and onto <a href="http://github.com/wireframe/shard">github</a>! This shouldn’t be a big surprise since shard only used java.net as a source code repository, and CVS sucks major ass. Git is the absolute bomb, and I’m very excited to see folks experiment and enhance shard in a much more open fashion by using git. Hey, forking is good!</p>
<p> </p>
API Exploration2008-05-12T00:00:00+00:00https://codecrate.com/2008/05/api-exploration<p>For the past several years, my standard workflow for investigating new Java tools and technologies relied on writing a series of “bare bones” unit tests to explore functionality. These unit tests were absolutely vital for me to get up to speed quickly on new libraries like spring, lucene and hibernate.</p>
<p>The use of unit tests as a “launcher” has largely grown out of the difficulty of bootstrapping a simple Java application. Java is simply not built to be launched in the same way scripting languages like ruby and perl are. I suppose .NET has the same “limitation”.</p>
<p>Now that I’m in the wonderful world of Ruby, things are quite a bit different. The IRB console is a great and effective way to test out an API. Yesterday was a perfect example of this. I wanted to test out one of the <a href="http://docs.google.com/Doc?docid=acjpjppxjpcw_6ggg4t7g5&hl=en">google data api’s and they had an excellent walkthrough</a> based entirely in the IRB shell. It worked great, and I was very impressed with the overall experience. How would this tutorial have looked in Java? Not nearly as pretty…</p>
<p>Sure, Java has alternatives that are similar to the IRB console (beanshell, groovy, etc), but nothing comes pre-packaged and ready to go out of the box. This is a major hurdle when you want people to pickup and play with your API. It’s just not practical to spend twenty minutes setting up your environment just to play around with a new technology. The IRB shell is definitely a huge selling point of Ruby in my opinion.</p>
<p>One disadvantage to using the IRB shell is that knowledge is lost once the shell is terminated. The “throw away” unit tests written in Java can actually be checked into your codebase which may be useful for getting new developers up to speed with a new API. I’ve found myself coming back to pieces of code after several months wondering why I did things a certain way, and it’s pretty valuable to have the unit tests there for a quick refresher.</p>
<p>Both approaches have their pros and cons. Anyone else have an effective way to prototype API’s?</p>
Testing Managed Objects2008-05-05T00:00:00+00:00https://codecrate.com/2008/05/testing-managed-objects<p>My definition of “Managed” Objects:</p>
<p>Objects that are manipulated by a separate container with a pre-defined lifecycle.</p>
<p>Managed Objects are a very standard part of development projects.</p>
<ul>
<li>
<p>JSP taglibs are managed by the servlet container</p>
</li>
<li>
<p>ant/maven tasks are managed by their respective execution environment</p>
</li>
<li>
<p>tapestry/wicket components have a managed rendering lifecycle</p>
</li>
</ul>
<p>Unit testing these managed objects “correctly” is very difficult since you need in depth knowledge of how these objects will be invoked within the container. In my personal experience, it is best to extract as much logic out of your managed objects into standard POJO’s and unit test the heck out of them. The managed objects then become a very slim wrapper around your core business objects. Unit testing your POJO gives you the most bang for your buck versus actually unit testing the managed object.</p>
<p>To actually unit test your managed objects, it is very important to test them within the actual container. This may qualify as more of an integration test instead of a standard unit test, but that’s fine by me. The alternative is to write your unit test to invoke the managed object by emulating the behavior of the container. I have never had a high level of confidence that my “emulated container” is doing things 100% the way the “real container” will. Especially since containers do not necessarily adhere to the published lifecycle specification <em>cough</em> every JSP servlet container <em>cough</em>. Since one of the core purposes for unit tests is to remove fear of making changes, these integration tests are vital to ensure your object really works as you expect.</p>
<p>Some libraries provide lightweight stubs of their container in order to facilitate these kinds of integration tests. Spring has a whole suite of <a href="http://www.infoq.com/articles/testing-in-spring">abstract JUnit TestCase classes</a> to make in-container testing a breeze. Wicket provides an excellent <a href="">WicketTester class</a> to stub out the wicket runtime to execute your managed object in isolation without firing up an entire application. Maven has a <a href="http://maven.apache.org/plugin-developers/plugin-testing.html">few competing options</a> and they all suck pretty bad (but at least they’re trying). Anyone here remember the supposed <a href="http://jakarta.apache.org/cactus/">“holy grail” of in-container testing</a>? Wow, that brings back bad memories…</p>
Say It. Do It. Prove It!2008-04-30T00:00:00+00:00https://codecrate.com/2008/04/say-it-do-it-prove-it<p>There are lots of software development methodologies. I’ve voiced my opinions over the years on how to create great software, and these three small statements sum up a pretty large part of my software development philosophy.</p>
<h2 id="say-it">Say it.</h2>
<p>Document your code. Standard javadocs are fine. Stick to method/class level docs with none of that body comment crap. Give a humane overview of what you’re trying to accomplish with the block of code. This is also a great place to drop references to external documentation which may back up why a certain approach is being used.</p>
<h2 id="do-it">Do it.</h2>
<p>Write your code. Keep it clean and concise. Only do what you said you’re going to do and nothing more.</p>
<h2 id="prove-it">Prove it.</h2>
<p>Unit tests. I don’t believe you did what you said you were going to do without tests.</p>
<p>Traditional TDD heavily emphasizes writing unit tests which <em>can</em> be used as a form of documenting what you’re going to do, but I still find it valuable to have some level of documentation within the code itself (especially for interfaces).</p>
<p>Honestly, if more developers would just keep to these simple tips, we’d be a lot better off.</p>
Open Wide2008-04-21T00:00:00+00:00https://codecrate.com/2008/04/open-wide<p>I feel a bit like little Joe Miller in this <a href="http://youtube.com/watch?v=OXc5ltzKq3Y">classic video</a>…</p>
<p>This Wednesday will be a big day for me. I’ll be changing jobs for the first time in over four years. I’ve only gone through a few job changes in my professional career, and I’m very excited about this new opportunity. These are big changes in my life, and it’s a bit like taking a drink from that fire hose.</p>
<p>It’s time to bid farewell to the corporate world and move to a small startup company. I’m very excited to move to a smaller company where the people are really passionate about building kick ass software. A place where people are excited about what they do, and there are minimal roadblocks in the way of “Getting Things Done”. It may take a little time to adjust to the cultural differences between a large corporate enterprise-y company based in the suburbs and a small startup company in the downtown metro area, but I think I’ll manage… =)</p>
<p>I’ve been doing Java development (client and serverside) for the past ten years,
and this will be my first experience working with Ruby on Rails.
This will be a HUGE change. I’ve talked <a href="/2006/07/humane-object-iteration.html">about</a>
<a href="/2007/10/static-finders-in-java.html">ruby</a>
<a href="/2006/06/ruby-syntax-for-java-maps.html">and</a>
<a href="/2006/08/findertemplate.html">java</a> a number of times,
and I’m excited to dig more into the ruby language to see what it has to offer.
Don’t worry though; I’ll still be active in the Java community, especially with Wicket.
I’m still hoping to get <a href="http://groups.google.com/group/wicket-user-group-twincities">the twin cities wicket users group</a>
off the ground. Who knows, maybe a port of wicket to ruby is in my future? =)</p>
<p>I’ll finally be able to dive into the world of apple and use a macbook pro as my primary development platform. It feels so good for a workplace to run a decent operating system on their workstations (instead of crappy windows). It will take some time to <a href="http://en.wikiquote.org/wiki/Star_Wars_Episode_V:_The_Empire_Strikes_Back">“unlearn what I have learned”</a> from the wonderful world of windows and adapt the “mac way” of doing things (especially keyboard shortcuts). I’ve come across a few <a href="http://www.commoncraft.com/i-switched-mac-here-are-notes">good articles</a> for apple newbies, but please share any tips/tricks you may have!</p>
<p>Oh, and I think I know someone that looks an awful lot like Stanley Spadowski! =)</p>
Time To Toss the Cargo2008-04-16T00:00:00+00:00https://codecrate.com/2008/04/time-to-toss-cargo<p>Over the past year and a half, I’ve been heavily involved in migrating a large size application from OC4J appserver to tomcat. At the time, it seemed both logical and relatively smart to choose <a href="http://cargo.codehaus.org">cargo</a> for launching our application with a more application server neutral configuration. I now regret that I made the jump to use cargo so naively.</p>
<p>Let this post stand as a warning for others to avoid the same “cargo (strangle)hold”.</p>
<h3 id="limitations">Limitations</h3>
<p>There are a number of specific bells and whistles that each appserver provides that are not accessible through the cargo API. For example, it is impossible to tweak the location for tomcat’s webapp/work directories. Changing the tomcat server.xml file is essentially ignored/overwritten by cargo.</p>
<p>This boils down to cargo implementing the lowest common denominator between implementations.</p>
<h3 id="performance">Performance</h3>
<p>My simple testcase shows cargo taking ~30 seconds longer to startup our application (average startup time increased from ~85 seconds to ~120 seconds). This is <em>strictly</em> startup time within the appserver and does not account for all of the extra overhead from the cargo maven plugin. We’ve also noticed a <em>significant</em> change in performance at runtime. Using cargo causes the application to run ~20-30% slower than normal. Wow…</p>
<p>I intend to dig into this a bit deeper to identify the root cause, but initial investigation shows a fair amount of overhead for how cargo redirects/forks server output to files and the console.</p>
<h3 id="codehaus-aka---the-project-graveyard">codehaus (A.K.A. - The Project Graveyard)</h3>
<p>It’s common knowledge that all “good” Java projects that start codehaus migrate to a real OS community as quickly as possible <em>cough</em> wicket <em>cough</em>. =)</p>
<p>I’m serious here. Look at the track record that codehaus has going for it. Picocontainer, Maven Mojos, Cargo, etc. It’s inevitable that there will be lots of failures for every few shining successes, but thus far codehaus has a pretty poor batting average.</p>
<h3 id="abstractions--complexity">Abstractions == Complexity</h3>
<p>Abstracting away the complexity of appservers <em>sounds</em> like a good thing, but replacing it with a new layer of complexity which is completely foreign is much worse.</p>
<p>Tracking down <em>how</em> cargo is doing what is doing is very difficult. It actually appears to be using JMX to inspect and modify the tomcat runtime environment after it has started up!</p>
<p>Seriously, I was able to write a standalone tomcat launcher maven plugin with ~20 lines of code using ant tasks. It does everything I need including configuring JVM options. I’m not sure why the cargo plugin is so damn complex and bloated?</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
*
* @goal startTomcat
*/</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">StartTomcatMojo</span> <span class="kd">extends</span> <span class="nc">AbstractMojo</span> <span class="o">{</span>
<span class="cm">/**
* @parameter
* @required
*/</span>
<span class="kd">private</span> <span class="nc">File</span> <span class="n">tomcatHome</span><span class="o">;</span>
<span class="cm">/**
* @parameter
*/</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">javaOpts</span><span class="o">;</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">execute</span><span class="o">()</span> <span class="kd">throws</span> <span class="nc">MojoExecutionException</span> <span class="o">{</span>
<span class="n">getLog</span><span class="o">().</span><span class="na">info</span><span class="o">(</span><span class="s">"Starting tomcat: "</span> <span class="o">+</span> <span class="n">tomcatHome</span><span class="o">);</span>
<span class="nc">Project</span> <span class="n">project</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Project</span><span class="o">();</span>
<span class="n">project</span><span class="o">.</span><span class="na">setBaseDir</span><span class="o">(</span><span class="n">tomcatHome</span><span class="o">);</span>
<span class="n">project</span><span class="o">.</span><span class="na">addBuildListener</span><span class="o">(</span><span class="k">new</span> <span class="nc">AntToConsoleLogger</span><span class="o">());</span> <span class="c1">//redirect ant output to System.out</span>
<span class="nc">Java</span> <span class="n">java</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Java</span><span class="o">();</span>
<span class="n">java</span><span class="o">.</span><span class="na">setProject</span><span class="o">(</span><span class="n">project</span><span class="o">);</span>
<span class="n">java</span><span class="o">.</span><span class="na">setJar</span><span class="o">(</span><span class="k">new</span> <span class="nc">File</span><span class="o">(</span><span class="n">tomcatHome</span><span class="o">,</span> <span class="s">"bin/bootstrap.jar"</span><span class="o">));</span>
<span class="n">java</span><span class="o">.</span><span class="na">setFork</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="n">java</span><span class="o">.</span><span class="na">setFailonerror</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="n">java</span><span class="o">.</span><span class="na">createArg</span><span class="o">().</span><span class="na">setValue</span><span class="o">(</span><span class="s">"start"</span><span class="o">);</span>
<span class="n">java</span><span class="o">.</span><span class="na">createJvmarg</span><span class="o">().</span><span class="na">setValue</span><span class="o">(</span><span class="s">"-Dcatalina.base="</span> <span class="o">+</span> <span class="n">tomcatHome</span><span class="o">.</span><span class="na">getPath</span><span class="o">());</span>
<span class="n">java</span><span class="o">.</span><span class="na">createJvmarg</span><span class="o">().</span><span class="na">setValue</span><span class="o">(</span><span class="s">"-Dcatalina.home="</span> <span class="o">+</span> <span class="n">tomcatHome</span><span class="o">.</span><span class="na">getPath</span><span class="o">());</span>
<span class="n">java</span><span class="o">.</span><span class="na">createJvmarg</span><span class="o">().</span><span class="na">setValue</span><span class="o">(</span><span class="s">"-Djava.io.tmpdir="</span> <span class="o">+</span> <span class="k">new</span> <span class="nc">File</span><span class="o">(</span><span class="n">tomcatHome</span><span class="o">,</span> <span class="s">"temp"</span><span class="o">).</span><span class="na">getPath</span><span class="o">());</span>
<span class="n">getLog</span><span class="o">().</span><span class="na">debug</span><span class="o">(</span><span class="s">"Using JAVA_OPTS: "</span> <span class="o">+</span> <span class="n">javaOpts</span><span class="o">);</span>
<span class="n">java</span><span class="o">.</span><span class="na">createJvmarg</span><span class="o">().</span><span class="na">setLine</span><span class="o">(</span><span class="n">javaOpts</span><span class="o">);</span>
<span class="n">java</span><span class="o">.</span><span class="na">execute</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>To be fair, cargo might be intended for a different audience. It could be the <em>perfect</em> tool for Java system administrators that manage lots of various applications with a heterogeneous deployment infrastructure. My issues with cargo may be acceptable for others to deal with, but for me, it’s time to move on.</p>
Consume RSS Feeds Within Wicket2008-03-31T00:00:00+00:00https://codecrate.com/2008/03/consume-rss-feeds-within-wicket<p>In the past, I’ve shown how easy it is to <a href="/2007/09/wicket-feedresource.html">publish RSS/atom feeds within Wicket applications</a>, and now it is just as easy to consume external feeds. It’s actually quite trivial (about 20 lines of code), but it is nice to support this out of the box so new users don’t have to roll their own implementation every time.</p>
<p>The most common usecase thus far has been to display a list of information that comes from an external rss feed.</p>
<p>Here’s an example Wicket HTML template that just displays the RSS entry’s title.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>ul<span class="ni">&gt;</span>
<span class="ni">&lt;</span>li wicket:id="entry"<span class="ni">&gt;&lt;</span>span wicket:id="title"<span class="ni">&gt;</span>My Happy Blog Post<span class="ni">&lt;</span>/span<span class="ni">&gt;&lt;</span>/li<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/ul<span class="ni">&gt;</span>
</code></pre></div></div>
<p>The Java code to look up the RSS feed, and wrap it into a Wicket ListView, is ridiculously simple. The new wicketstuff-rome SyndEntryListModel does all of the heavy lifting. Just point it at the desired RSS feed and extract whatever information out of the ROME SyndEntry that you want!</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">HomePage</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">HomePage</span><span class="o">()</span> <span class="o">{</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">ListView</span><span class="o">(</span><span class="s">"entry"</span><span class="o">,</span> <span class="k">new</span> <span class="nc">SyndEntryListModel</span><span class="o">(</span><span class="s">"http://feeds.feedburner.com/code_poet"</span><span class="o">))</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">populateItem</span><span class="o">(</span><span class="nc">ListItem</span> <span class="n">item</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">SyndEntry</span> <span class="n">entry</span> <span class="o">=</span> <span class="o">(</span><span class="nc">SyndEntry</span><span class="o">)</span> <span class="n">item</span><span class="o">.</span><span class="na">getModelObject</span><span class="o">();</span>
<span class="n">item</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">Label</span><span class="o">(</span><span class="s">"title"</span><span class="o">,</span> <span class="n">entry</span><span class="o">.</span><span class="na">getTitle</span><span class="o">()));</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I’m sure there are improvements that can be made, and I’d love to hear feedback from Wicket users what other options would be useful. Try it today and let me know what can be done to improve it!</p>
Using Maven For Classpath Isolation2008-02-22T00:00:00+00:00https://codecrate.com/2008/02/using-maven-for-classpath-isolation<p>I’m absolutely obsessed with my application’s classpath. I come from a background where projects have ginormous classpaths containing 80+ jars, and classes are imported willy nilly without any thought of the consequences. This is one of the worst things you do to the long term maintainability of your application. Let me give you an example…</p>
<p>Let’s say we have a very simple application with a single source tree that integrates with a third party library. Like so…</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">com.foo.FooService</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FooServiceBridge</span> <span class="kd">implements</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">doStuff</span><span class="o">()</span> <span class="o">{</span>
<span class="k">new</span> <span class="nc">FooService</span><span class="o">.</span><span class="na">performOperation</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, this third party library may provide a set of “utility” classes that other core parts of your application may find useful.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">com.foo.FooUtils</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyBusinessObject</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">isValid</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="nc">FooUtils</span><span class="o">.</span><span class="na">isObjectNull</span><span class="o">(</span><span class="k">this</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Before you know it, you’ll find that you’ll have references to this third party library littered all over your application. This is absolutely horrible. What happens to the when I want to replace my FooService with a competing library? You should be able to rip out an implementation of one service and replace it with another implementation with no impact to the rest of the application. Using a shared classpath for third party libraries essentially prevents you from migrating from one library to another. Your stuck with what you’ve got until the day you die. Okay, maybe the day your application dies… =)</p>
<p>I’ve gone through this process OVER and OVER again. Every time it happens, it makes <a href="http://diveintomark.org/public/2006/07/you-make-bunny-cry.jpg">a little bunny cry</a>.</p>
<p>There is absolutely no way to prevent this coupling from happening unless you can isolate certain libraries at build time into separate classpaths. Maven supports this beautifully by creating a multiproject build where you isolate all code relying on the third party library into it’s own module.</p>
<p>Now, instead of having one monolithic source tree/classpath where all classes have access to all libraries, you have two (or three) projects and each project has their own isolated classpath.</p>
<ul>
<li>
<p>myproject-core (core business logic with no dependencies on the third party library)</p>
</li>
<li>
<p>myproject-foo (depends on the third party library and provides implementation of core interface)</p>
</li>
<li>
<p>myproject-uberjar (optional - depends on both projects to build up the final runtime classpath)</p>
</li>
</ul>
Wicket Users Group Twin Cities2008-02-03T00:00:00+00:00https://codecrate.com/2008/02/wicket-users-group-twin-cities<p>Alright Folks!</p>
<p>Any Wicket users in the Minneapolis/St. Paul area should head over to a newly created google group to start lining up dates/times to get together. Food, presentations, and good times will be had by all.</p>
<p><a href="http://groups.google.com/group/wicket-user-group-twincities">http://groups.google.com/group/wicket-user-group-twincities</a></p>
<p>Feel free to contact me offline with any questions or suggestions!</p>
Choosing a Java Web Framework2008-01-28T00:00:00+00:00https://codecrate.com/2008/01/choosing-java-web-framework<p>Last week I was asked to give a presentation comparing Java web frameworks for an upcoming project. This is very similar to the <a href="http://raibledesigns.com/rd/entry/comparing_jvm_web_frameworks_presentation">a presentation given by Matt Raible</a>, so I started there to see what he had to say. He’s obviously done a lot of work with the appfuse project which supports a pretty impressive number of frameworks out of the box. I’d highly recommend folks checkout the documentation he’s done over the years and even <a href="http://parleys.com/display/PARLEYS/Comparing+Java+Web+Frameworks?showComments=true">watch his presentation from past conferences</a>.</p>
<p>After going through his <a href="http://static.raibledesigns.com/repository/presentations/ComparingJavaWebFrameworks-ApacheConUS2007.pdf">slides</a> and <a href="http://static.raibledesigns.com/repository/presentations/ComparingJVMWebFrameworks-ApacheConUS2007.pdf">presentations</a> there are a few comments I’d like to toss in. For the most part, Matt is a pretty objective reviewer of the frameworks, but his bias is definitely from the point of view of a web developer and not a Java developer. There’s nothing wrong with that, but some of the points he makes aren’t really valid for me as a straight up Java developer. The best point made in is presentation is, <strong>Use whatever tool is right for your project/team</strong>. There is no <strong>one</strong> web framework that will be best for all projects.</p>
<p>Before plunging into the various frameworks, a very important decision must be made. The most often overlooked question when choosing a web framework is what programming paradigm are you looking for? Do you want a component or an action based framework? Choosing between component or action frameworks is as important as choosing what language you’ll use. I would personally make this decision before choosing the actual framework. Since most developers don’t know the difference between the two, here’s a brief intro:</p>
<p>Action frameworks focus mainly on request/response processing. They tend to have a lower barrier to entry and are more simplistic than component oriented frameworks. Action frameworks tend to be very procedural with little reuse of code/components or object oriented design (ever tried to reuse components with JSP?). Even the coveted Ruby on Rails falls into this category (though it is a fantastic action framework).</p>
<p>Component frameworks remove the restriction of basic “request/response” processing and focus on object oriented web design. It takes a considerable mind shift to work with component frameworks, but the benefits include developing object oriented applications where components/widgets can be reused across the application very easily. Developers strong in Java and Object Oriented design will have an easier time picking up Component frameworks while developers more familiar with procedural or scripting frameworks will take some time adjusting.</p>
<p>And now, the abbreviated version of my presentation…</p>
<h3 id="action-frameworks">Action frameworks</h3>
<ul>
<li>
<p>Struts…sucks…that includes Struts2</p>
</li>
<li>
<p>Spring MVC…would you like some Java with your xml?</p>
</li>
</ul>
<h3 id="component-frameworks">Component frameworks</h3>
<ul>
<li>
<p>JSF…you’ve got to be kidding me</p>
</li>
<li>
<p>Wicket…ROXORS!</p>
</li>
</ul>
<p>It’s just that simple! =) This version of the presentation was a big hit, but if you need more explanation, here you go…</p>
<h1 id="action-frameworks-1">Action Frameworks</h1>
<h2 id="spring-mvc"><a href="http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html">Spring MVC</a></h2>
<p>Spring MVC is a Model2/Action web framework built on top of the popular spring framework library. It builds on the standard concepts of Models, Views, and Controllers and adds a well defined lifecycle for binding, validation, etc.</p>
<p>Many parts of the framework are pluggable. You can choose from several different view layers (JSP, Velocity, Freemarker, etc). The framework is sometimes too flexible and causes confusion on how to best accomplish a task.</p>
<p>Lots of configuration in xml is necessary. Even with the new annotation support, you’ll still need to feel comfortable with xml to configure many parts of the system.</p>
<p>Developers will need to understand core Java concepts such as Inversion of Control and Dependency Injection in order to be productive with Spring MVC (or Spring in general).</p>
<p>Spring MVC is a bare bones web framework which is very customizable, but comes with very little out of the box. Everything from security to redirect-after-post to ajax must be built within your webapp.</p>
<p>NOTE: Every web framework offers integration with spring, so it is not necessary to use Spring MVC in order to use spring for your business/service layer.</p>
<h2 id="struts2"><a href="http://struts.apache.org">Struts2</a></h2>
<p>Struts2 is another Model2 web framework that has been around much longer than Spring MVC. It’s an evolution of the legacy struts framework and integrated with the popular WebWork framework. It is more mature than Spring MVC with a larger community of developers and users.</p>
<p>The Struts2 API is fairly complex since they have abstractions in place to mask working with HTTP specific implementations. It takes quite a bit of time to learn the “Struts2 way” (ex: interceptors). Finding documentation and user support is frustrating since there is still such a large community around the legacy Struts1 framework.</p>
<p>Requires lots of configuration using either annotations or xml files.</p>
<p>Quite a few user contributed plugins of varying quality.</p>
<p>Able to work with a variety of view technologies (JSP, Velocity, Freemarker). Provides a number of utility tags to output common constructs (form inputs, etc). The default rendering of the tags can be customized to fit the look/layout you need.</p>
<p>Very powerful library used for rendering view layer (OGNL) can be useful, but has very poor feedback so if anything goes wrong, you’ll have extreme difficulty figuring it out. Wicket used to use OGNL and ditched it in favor of a simpler/easier to understand custom library.</p>
<h1 id="component-frameworks-1">Component Frameworks</h1>
<h2 id="jsf">JSF</h2>
<p>JSF is the “Standard” component framework created by the JCP and distributed as part of Java EE systems. Using JSF requires running a full-blown Java application server, and can not be run on standard servlet containers without extra work.</p>
<p>Although the JSF design is a standard, there is no standard implementation. There are several implementations of the standard, each with strengths/weaknesses. For example, Seam is a particular JSF implementation that has gained a lot of traction recently, but building a “Seam” application is not the same as building a “JSF” application. Building to a Standard API is intended to allow for portability between implementations, but that is far from reality. Since you end up building to a specific implementation, why build with a standard at all?</p>
<p>Considerable ramp up time and tool support is a requirement to be productive. Instead of just working with standard Java and HTML, you end up locking into a particular toolset. The tools get you up and running very quickly, but you pay for the convenience since you can only build what the tool supports and they restrict how much you can do with the internal framework.</p>
<p>Simple things are definitely not simple. JSF relies on tools to do all of the grunt work instead of having simple conventions or sensible defaults. JSP’s become cluttered and unreadable very quickly with all of the custom tags required. Design of JSF is targeted for internal/intranet applications and does not easily support web security or bookmarkable urls because of this.</p>
<p>Releases are far and few between. Since JSF is designed by committees, it takes an extremely long time to agree upon new features. For example, AJAX took the world by storm over the past few years and all of the other major web frameworks were able to evolve to accommodate AJAX, while JSF still lags behind.</p>
<p>User community is very absent. Commercial JSF vendors are the only people actually using (and selling) this stuff. Very few open source plugins/components available.</p>
<h2 id="wicket"><a href="http://wicket.apache.org">Wicket</a></h2>
<p>Wicket is a component based framework with an API more similar to building Swing applications than traditional Model2 web applications. It has a much smaller learning curve than other component based frameworks (ex: JSF, Tapestry).</p>
<p>Wicket is the only framework that provides for a true separation of concerns where the view layer is standard HTML and behavior/logic is captured in Java. This allows for a team of web designers to use standard WYSIWYG HTML editors to build the UI without any knowledge of programming languages or tag library syntax. This is in stark contrast to all other frameworks that require lots of custom tags and logic to litter the view layer causing the page to not be previewable outside a running application.</p>
<p>Wicket is the most performant web framework out of the box when it comes to handling web resources. By default, all javascript, css, and images are compressed, minified, and cached by browsers. Downloading and rendering static resources account for ~80% of the end user experience which makes this feature very important for building high volume, scalable sites. Wicket is also extremely secure by default since it uses server side session management for navigating around the site, but it is still very easy to create stateless pages and bookmarkable urls.</p>
<p>Out of the box Ajax support makes it easy to build Web 2.0 applications.</p>
<p>Wicket has an extremely active community. Questions asked on the mailing lists are answered by core developers within minutes. It is now a top level project at Apache, and has seen a huge increase in popularity with the recent 1.3 release. There are a large number of user contributed projects (wicket-extensions, wicketstuff) that provide extensions and integrations with other libraries (hibernate, spring, scriptaculous, rss/atom generation, etc).</p>
<p>It’s FUN! Seriously, it took me ten minutes to build my first webapp with wicket. Try it and see for yourself.</p>
<p>DISCLAIMER: I’m a contributor to several wicketstuff projects (scriptaculous, hibernate, rss). This may show my bias, but it also shows how easy (and fun) it is to create custom components.</p>
Wicket Client Side Validation2008-01-27T00:00:00+00:00https://codecrate.com/2008/01/wicket-client-side-validation<p>Over the past several weeks, I’ve been been seeing lots of posts for <a href="http://extjs.com/deploy/ext/examples/form/dynamic.html">fancy</a><a href="http://www.jsvalidate.com/">Javascript</a><a href="http://tetlaw.id.au/view/javascript/really-easy-field-validation">validation</a> libraries. I spent a couple weeks playing around with integrating these libraries into Wicket, but something didn’t feel quite right. Giving users instant feedback when filling in data forms is <em>really</em> nice, but what is the best way to support it?</p>
<p>Before we can really dive into the issue of client side validation, we must first be perfectly clear that server side validation is absolutely critical. There is no question that we <em>need</em> validation done on the server side to prevent a user bypassing validation just by turning off javascript.</p>
<p>If server side validation is mandatory, how do you add client side validation with the least amount of work? I mean, how do you get the “most bang for your buck” and not have to re-do all of the server side validation rules with custom code on the client side? The trouble is, server side validation runs in Java, and client side validation runs in Javascript. How can these two languages perform the <em>exact</em> same validation rules without a LOT of extra work? How do you get <em>cohesive</em>, <em>localized</em> messaging for both server side and client side validation errors? I have yet to see a Javascript validation library that handles localized messages as robustly as Java validation frameworks.</p>
<p>My answer? Use Ajax.</p>
<p>Instead of re-implementing all of the server side validation rules in Javascript, just use Ajax to call into the server to perform the REAL validation and give the user feedback. The user gets instant feedback, and we don’t have to “jump through hoops” and write separate Javascript validation libraries to do what is already supported on the server side.</p>
<p>Wicket handles this beautifully with the AjaxFormValidatingBehavior.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyForm</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">MyForm</span><span class="o">()</span> <span class="o">{</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">FeedbackPanel</span><span class="o">(</span><span class="s">"feedback"</span><span class="o">).</span><span class="na">setOutputMarkupId</span><span class="o">(</span><span class="kc">true</span><span class="o">));</span>
<span class="nc">Form</span> <span class="n">form</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Form</span><span class="o">(</span><span class="s">"form"</span><span class="o">,</span> <span class="k">new</span> <span class="nc">CompoundPropertyModel</span><span class="o">(</span><span class="k">new</span> <span class="nc">MyObject</span><span class="o">()))</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onSubmit</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//do something</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="n">add</span><span class="o">(</span><span class="n">form</span><span class="o">);</span>
<span class="nc">TextField</span> <span class="n">name</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">TextField</span><span class="o">(</span><span class="s">"name"</span><span class="o">);</span>
<span class="n">name</span><span class="o">.</span><span class="na">setRequired</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="n">form</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
<span class="nc">AjaxFormValidatingBehavior</span><span class="o">.</span><span class="na">addToAllFormComponents</span><span class="o">(</span><span class="n">form</span><span class="o">,</span> <span class="s">"onblur"</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Boom! Just like that, you have client side validation in Wicket. In this example, the user will get an error message if they try to leave the name field blank. Seriously, can it get any easier than this? Actually it can, if you use hibernate annotations, your Wicket component can <a href="/2007/06/wicketstuff-hibernate-updates.html">automatically configured instead of having to manually set requiredness or add validators</a>. You could also automatically attach this Ajax behavior to all of your forms by using a ComponentInstantiationListener.</p>
<p>Some people may complain that this is no longer “client side” validation since we’re making a call to the server. So WHAT!?! I will gladly pay the cost to have this done on the server where I’m <em>guaranteed</em> to have the correct validation rules fire. There is a definite risk of a possible mismatch between the client side and server side validation rules since they are written in two completely different languages. It’s all too plausible for a javascript validator to have different syntax rules than the server side rules which could ultimately lead to preventing users from entering data that passes the server side validation rules. This may not be a worry for simple “is required” validation, but email address and phone number validation is much more complex and changes between implementations.</p>
<p><a href="http://raibledesigns.com/rd/entry/comparing_jvm_web_frameworks_presentation">Matt Raible gave Wicket low marks in this area</a> because no fancy javascript validation libraries are built into Wicket like in <a href="http://tapestry.apache.org/tapestry4.1/usersguide/clientside-validation.html">Tapestry</a>, but I don’t understand why? In my mind, as long as you’re giving the user instant feedback, there’s no real difference between:</p>
<ol>
<li>
<p>executing Javascript validators</p>
</li>
<li>
<p>using Javascript to call serverside validation</p>
</li>
</ol>
<p>Thoughts?</p>
Personal Productivity2008-01-14T00:00:00+00:00https://codecrate.com/2008/01/personal-productivity<p>I was asked by a co-worker the other day what I would recommend to improve productivity. I’m by no means an expert in this field, but here are a few things I recommend to everyone to increase their effectiveness.</p>
<h2 id="the-mouse-is-evil">The Mouse Is Evil</h2>
<p>Using that little pointing device is the single biggest loss for productivity. Avoid using it at ALL costs.</p>
<ul>
<li>Bye-bye start menu. Quick launch bars and application docks are a waste of time. Use one of the many <a href="/2008/01/requesting-java-launcher.html">application launching tools</a> out there instead. No more searching for buttons or menus to launch the app you need.</li>
</ul>
<h2 id="tools-are-your-friend">Tools are your Friend</h2>
<ul>
<li>
<p>Choose your tools. Make a concious choice for what tools you’re using and why. Don’t just use notepad for coding because it’s the default text editor on your PC. Acknowledge what features you NEED to be productive and either find, buy, or build the tool yourself. I’m still waiting for someone to convince me that a Mac will make me more productive so I can pick up a shiny new toy! =)</p>
</li>
<li>
<p>Know your tools inside and out. Just knowing a few keyboard shortcuts can give you huge lift in the productivity department. (Ctrl+S = Saves Time)</p>
</li>
</ul>
<h2 id="distractions-are-the-devil">Distractions are the Devil</h2>
<p>There are <a href="http://www.google.com/search?q=productivity&sitesearch=37signals.com%2Fsvn">lots of articles that talk about how important it is to get into “the flow”</a>. Here are a few steps I’ve taken to help me focus more on the task at hand.</p>
<ul>
<li>
<p>Turn off all MS Outlook notifications, beeps, and popups. Seriously, they’re just as annoying as Clippy.</p>
</li>
<li>
<p>Launch gmail and google reader as a separate window. This has been absolutely HUGE for me lately. As much as I love firefox tabs, they are my number one source of distractions right now. Instead of focusing on the task/tab at hand, my eyes constantly wander to the other tabs and see “Oh, I have an unread message! I better check it RIGHT NOW!”. <a href="http://labs.mozilla.com/2007/10/prism/">Prism is a godsend</a>that allows me to 1) launch gmail in a lightweight process outside of my main firefox window 2) provide desktop shortcut that can be integrated with my application launcher (see above)</p>
</li>
<li>
<p>Make a CONCIOUS decision to check messages/rss/etc and do it as infrequently as possible. Don’t just flip over to email every time a 10 second code compilation kicks in.</p>
</li>
</ul>
<p>One of my new years resolutions was to increase my organization and productivity, so I’d love to hear tips from others on how they stay focused on “Kicking Ass” in their work.</p>
Revamped Drag and Drop for Scriptaculous2008-01-10T00:00:00+00:00https://codecrate.com/2008/01/revamped-drag-and-drop-for<p>Drag and drop support in wicketstuff-scriptaculous project has undergone some major changes over the past few days.</p>
<p>First off, I upgraded to the latest and greatest 1.8.1 version of scriptaculous. Whoo hoo. Hopefully scriptaculous 2.0 will be making an appearance sometime soon.</p>
<p>Now for the real meat of the changes…</p>
<p>There was a really good conversation on the wicket mailing list about improving the API for drag and drop. The main complaint is that we should be able to infer which wicket component was being dragged instead of just passing around a string id reference. I thought this was absolutely brilliant and would really showcase wicket’s strength for writing Object Oriented web applications (unlike some other scripting frameworks).</p>
<p>Here’s a very simple example of what the new API looks like. It really hasn’t changed that much. The onDrop callback now returns a Component instead of a String.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">DragDropExamplePage</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">DragDropExamplePage</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Label</span> <span class="n">product</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Label</span><span class="o">(</span><span class="s">"product"</span><span class="o">);</span>
<span class="n">product</span><span class="o">.</span><span class="na">addBehavior</span><span class="o">(</span><span class="k">new</span> <span class="nc">DraggableBehavior</span><span class="o">());</span>
<span class="n">add</span><span class="o">(</span><span class="n">product</span><span class="o">);</span>
<span class="nc">DraggableTarget</span> <span class="n">cart</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DraggableTarget</span><span class="o">(</span><span class="s">"cart"</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onDrop</span><span class="o">(</span><span class="nc">Component</span> <span class="n">input</span><span class="o">,</span> <span class="nc">AjaxRequestTarget</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">input</span> <span class="o">+</span> <span class="s">" dropped on the target"</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="n">add</span><span class="o">(</span><span class="n">cart</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This is particularly exciting for complex applications or for manipulating the Model object of the dropped Component. Logic can continue to be encapsulated in custom components and the onDrop callback shouldn’t need any extra logic for looking up the component that was modified.</p>
<p>One other note is that the SortableListView underwent some major plumbing as well, but the API has not changed. I dug through the wicket core API to better understand how ListView’s are intended to work. I was able to remove a bunch of dirty hacks and use the ListView in a much cleaner and better supported way.</p>
<p>Download the latest version and enjoy! Let me know if there are any other API improvements that would be useful!</p>
Requesting Java Launcher2008-01-09T00:00:00+00:00https://codecrate.com/2008/01/requesting-java-launcher<p>For the love of God, will someone please create a Java version of an application launcher ala Quicksilver?!?</p>
<p>I’ve come to absolutely rely on these tools and it annoys me to no end that I have to install different tools and deal with different configurations for every operating system I work on (Windows, Linux KDE, Linux Gnome, and sometimes Mac). Seriously, do we really need thirty implementations of the same idea (<a href="http://launchy.net">Launchy</a>, <a href="http://www.humanized.com/enso/">Enso</a>, Quicksilver, <a href="http://do.davebsd.com/">Gnome Do</a>, <a href="http://katapult.kde.org/">Katapult</a>)?</p>
<p>With so many opensource implementations, a Java port seems inevitable. I’d personally be willing to by someone a beer if they can create a workable opensource Java version! =)</p>
Webstart Report Now Available2008-01-01T00:00:00+00:00https://codecrate.com/2008/01/webstart-report-now-available<p>Happy New Year everyone!</p>
<p>The last day of 2007 brought a few new changes for the codecrate webstart maven plugin. I was extremely bored last night watching the Dick Clark New Years Bash and decided that my first resolution of the new year was to do something productive. What a way to bring in the new year!</p>
<ul>
<li>
<p>The plugin is now packaged under the com.codecrate.webstart group id. This is more consistent with the other projects and plugins I’ve published.</p>
</li>
<li>
<p>No more keystore configuration is necessary! The plugin will automatically generate a new keystore using the organization information from the POM to sign your jar files for you.</p>
</li>
<li>
<p>The plugin can now generate an HTML report for your maven site. You can still link directly to the JNLP file, but the report will auto detect if the user has Java installed and provide info on installing Java before launching the application. This should help new users avoid getting an ugly XML file if they don’t have Java installed.</p>
</li>
</ul>
<p>To add the webstart report to your maven site, just add this block of xml to your POM file.</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>reporting<span class="ni">&gt;</span>
<span class="ni">&lt;</span>plugins<span class="ni">&gt;</span>
<span class="ni">&lt;</span>plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>com.codecrate.webstart<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>webstart-maven-plugin<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugins<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/reporting<span class="ni">&gt;</span>
</code></pre></div></div>
<p>An <a href="http://shard.codecrate.com/shard-cyclops/launch.html">example of the new report can be seen with the shard-cyclops project</a>.</p>
Deploy Maven Webstart Projects2007-12-31T00:00:00+00:00https://codecrate.com/2007/12/deploy-maven-webstart-projects<p>I’ve continued to work on shard-cyclops this last week and just pushed out a new release that has a few updates including:</p>
<ul>
<li>
<p>display the distance of the token path while moving around the grid</p>
</li>
<li>
<p>automate deployment of the project using the new codecrate webstart plugin</p>
</li>
</ul>
<p>That’s right, the codecrate webstart maven plugin can now <em>deploy</em> your distribution as well as create the fancy JNLP file. By adding your maven repository ID and URL to your plugin configuration, you can now upload your JNLP and jar artifacts automatically as part of your maven build!</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>com.codecrate<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>webstart-maven-plugin<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>executions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>execution<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>deploy-webstart<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>phase<span class="ni">&gt;</span>deploy<span class="ni">&lt;</span>/phase<span class="ni">&gt;</span>
<span class="ni">&lt;</span>goals<span class="ni">&gt;</span>
<span class="ni">&lt;</span>goal<span class="ni">&gt;</span>deploy-jnlp<span class="ni">&lt;</span>/goal<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/goals<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/execution<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/executions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>configuration<span class="ni">&gt;</span>
<span class="ni">&lt;</span>mainClass<span class="ni">&gt;</span>com.mysite.MyApp<span class="ni">&lt;</span>/mainClass<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>codecrate-ftp-repo<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>url<span class="ni">&gt;</span>ftp://www.codecrate.com/shard/shard-cyclops<span class="ni">&lt;</span>/url<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/configuration<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugin<span class="ni">&gt;</span>
</code></pre></div></div>
<p>The implementation was a bit <em>too</em> easy if you ask me. The maven-wagon library is intended to be an abstraction around file transfers so your plugin can transfer files across any protocal (ftp, scp, local, webdav, etc). I was right to be skeptical because it seems that the maven-wagon project is yet another red headed stepchild of the maven umbrella. When using an FTP repository, wagon only supports transferring individual files and not an entire directory. WTF? Supposedly, this is done because FTP is slow for transferring files one at a time, but who the hell cares? I’ve got all of my builds automated, so why would I care if it takes 10 seconds or 10 minutes to transfer files?</p>
<p>Oh well, I have a workaround place to transfer files one at a time to get around wagon’s inadequacy. Yet again maven has taken a great idea (abstraction of file deployment for different protocols) and dropped the ball. It’s obvious that maven suffers from NIH Syndrome (Not Invented Here) and is ignoring a lot of work other developers have done. <a href="http://www.jroller.com/phidias/entry/scripting_vfs">Commons VFS</a> has a similar mission as wagon and has been around <em>much</em> longer. Why not leverage what’s already out there?</p>
<p>Enough ranting. I’m psyched to have the new plugin out the door, and now updates to shard-cyclops should become a regular occurance. Next up, I need to create a new maven plugin that will generate a “pretty” html page with the appropriate magic javascript to detect the Java installation on client machines.</p>
New Maven Webstart Plugin2007-12-27T00:00:00+00:00https://codecrate.com/2007/12/new-maven-webstart-plugin<p>After <a href="/2007/12/shard-cyclops-demo-available.html">uncovering the horrible state of affairs for Java Webstart developers</a>, I spent some time trying to figure out where to go next. The current <a href="http://mojo.codehaus.org/webstart-maven-plugin-parent/webstart-maven-plugin/">codehaus plugin for webstart projects</a> just doesn’t cut it.</p>
<p>I was appalled that the default behavior of the plugin forced developers to manually create a JNLP file and all the plugin did was sign jar files and zip up the contents for you. After a few long discussions with the developers of the plugin, <a href="http://jira.codehaus.org/browse/MWEBSTART-86">I commented that</a> “It would greatly improve the adoption of this plugin if it supports very simple out of the box behavior”.</p>
<p>The response I was a bit surprising, “Not sure if that will improve the adoption of the plugin (what are the alternatives?)”</p>
<p>This got me thinking…What are the alternatives? This is exactly what’s going wrong with the maven community. There are no alternatives!</p>
<p>I spent the next two days hacking away at the current crappy maven plugin trying to contribute back improvements before thinking to myself, should it really be this hard? Can’t we provide drop dead simple support for 90% of webstart projects without jumping through all of these hoops? The current plugin is a mis-mash of partially implemented features and no clear usecase for how/when it should be used. The code is nearly unreadable and 100% untestable. Yuk…</p>
<p>So, I took a couple hours and whipped together a new maven webstart plugin that blows the pants off the current plugin. It handles the simple usecase with utmost ease and does so with less code and complexity. Less than 300 lines of code!</p>
<p>If you need complete flexability and control, use the codehaus plugin. If you want your project to “just work”, use mine. =)</p>
<p>The simple usecase is (you guessed it), very simple:</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>build<span class="ni">&gt;</span>
<span class="ni">&lt;</span>plugins<span class="ni">&gt;</span>
<span class="ni">&lt;</span>plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>com.codecrate<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>webstart-maven-plugin<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>executions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>execution<span class="ni">&gt;</span>
<span class="ni">&lt;</span>phase<span class="ni">&gt;</span>package<span class="ni">&lt;</span>/phase<span class="ni">&gt;</span>
<span class="ni">&lt;</span>goals<span class="ni">&gt;</span>
<span class="ni">&lt;</span>goal<span class="ni">&gt;</span>generate-jnlp<span class="ni">&lt;</span>/goal<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/goals<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/execution<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/executions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>configuration<span class="ni">&gt;</span>
<span class="ni">&lt;</span>mainClass<span class="ni">&gt;</span>com.mysite.MyApp<span class="ni">&lt;</span>/mainClass<span class="ni">&gt;</span>
<span class="ni">&lt;</span>allPermissions<span class="ni">&gt;</span>false<span class="ni">&lt;</span>/allPermissions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/configuration<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugins<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/build<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Now, if your application needs allPermissions, you just need to add information about what keystore to use for signing your jars. I’d recommend checking out the <a href="http://mojo.codehaus.org/keytool-maven-plugin/">maven keytools plugin</a> as well for helping setup and maintain your keystore.</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>com.codecrate<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>webstart-maven-plugin<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>executions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>execution<span class="ni">&gt;</span>
<span class="ni">&lt;</span>phase<span class="ni">&gt;</span>package<span class="ni">&lt;</span>/phase<span class="ni">&gt;</span>
<span class="ni">&lt;</span>goals<span class="ni">&gt;</span>
<span class="ni">&lt;</span>goal<span class="ni">&gt;</span>generate-jnlp<span class="ni">&lt;</span>/goal<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/goals<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/execution<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/executions<span class="ni">&gt;</span>
<span class="ni">&lt;</span>configuration<span class="ni">&gt;</span>
<span class="ni">&lt;</span>mainClass<span class="ni">&gt;</span>com.mysite.MyApp<span class="ni">&lt;</span>/mainClass<span class="ni">&gt;</span>
<span class="ni">&lt;</span>keystore<span class="ni">&gt;</span>${project.basedir}/src/main/webstart/keystore<span class="ni">&lt;</span>/keystore<span class="ni">&gt;</span>
<span class="ni">&lt;</span>keypass<span class="ni">&gt;</span>shard-rox<span class="ni">&lt;</span>/keypass<span class="ni">&gt;</span>
<span class="ni">&lt;</span>storepass<span class="ni">&gt;</span>shard-rox<span class="ni">&lt;</span>/storepass<span class="ni">&gt;</span>
<span class="ni">&lt;</span>alias<span class="ni">&gt;</span>shard<span class="ni">&lt;</span>/alias<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/configuration<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugin<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Pretty much every part of the JNLP file is customizable through this plugin, but the key is that there are sensible defaults so you shouldn’t need to tweak anything else. But if you need to, here are some of the available switches:</p>
<table>
<tr>
<th>Parameter</th>
<th>Description</th>
<th>Default Value</th>
</tr>
<tr>
<td>title</td>
<td>Name of application</td>
<td>project.name</td>
</tr>
<tr>
<td>description</td>
<td>Description displayed when launching application</td>
<td>project.description</td>
</tr>
<tr>
<td>homepage</td>
<td>URL for the project homepage</td>
<td>project.url</td>
</tr>
<tr>
<td>vendor</td>
<td>Company publishing the application</td>
<td>project.organization.name</td>
</tr>
<tr>
<td>codebase</td>
<td>Base URL for JNLP resources</td>
<td>project.url</td>
</tr>
<tr>
<td>jnlpFile</td>
<td>Filename of the generated JNLP file</td>
<td>launch.jnlp</td>
</tr>
<tr>
<td>spec</td>
<td>JNLP spec version</td>
<td>1.0+</td>
</tr>
<tr>
<td>offlineAllowed</td>
<td>Configure whether the application can be run offline</td>
<td>false</td>
</tr>
<tr>
<td>j2seVersion</td>
<td>Version of Java required to run the application</td>
<td>1.5+</td>
</tr>
</table>
<p>You’ll also need to add the codecrate repository to have access to the plugin:</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>codecrate-repository<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>name<span class="ni">&gt;</span>Codecrate Repository<span class="ni">&lt;</span>/name<span class="ni">&gt;</span>
<span class="ni">&lt;</span>url<span class="ni">&gt;</span>http://maven.codecrate.com/<span class="ni">&lt;</span>/url<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repositories<span class="ni">&gt;</span>
</code></pre></div></div>
Shard Cyclops Demo Available2007-12-26T00:00:00+00:00https://codecrate.com/2007/12/shard-cyclops-demo-available<p>I thought I’d have a demo out sooner, but working with Java Webstart is quite a pain in the arse.</p>
<p>You’d think that if Sun took Java seriously for the desktop, they’d be pushing this technology a lot harder to get some decent tools out the door. As it stands today, it’s “functional” (for the most part) but it lacks polish to make it easy on developers. This is especially true for the <a href="http://mojo.codehaus.org/webstart-maven-plugin-parent/webstart-maven-plugin/">maven webstart plugin</a>. It has a long way to go before it can be used in the real world.</p>
<p>Without further ranting, I present the <a href="http://shard.codecrate.com/shard-cyclops/launch.jnlp">first available demo of the shard-cyclops application</a>. It’s a basic battle grid application that allows for moving tokens around a set of grid squares. Obstacles can be placed on the grid to prevent movement along certain paths.</p>
<p>Try it out, and drop me a line with any comments or suggestions!</p>
Wicket Wonderland2007-12-21T00:00:00+00:00https://codecrate.com/2007/12/wicket-wonderland<p>A few recent announcements within the Wicket community seem blog worthy.</p>
<p>A <a href="http://javathoughts.capesugarbird.com/2007/11/suckerfish-dropdowns-for-wicket.html">new wicketstuff project is available for creating suckerfish DHTML menus</a> is now available. Suckerfish menus <a href="http://www.htmldog.com/articles/suckerfish/dropdowns/">are cross browser compatible and use very elegant CSS and HTML</a>. I’ve been looking for one of these javascript libraries for a long time, and this is one of the nicest (and simplest) I’ve seen.</p>
<p>A <a href="http://www.codecommit.com/blog/java/a-wicket-api-for-google-charts">new wicketstuff project is available for integrating with Google’s new charting API</a>. It’s amazing how quickly this project came together. Google just <a href="http://feeds.feedburner.com/~r/ajaxian/~3/196196588/use-the-google-chart-api-to-create-charts-for-your-web-applications">announced this service a few days ago</a>, and there have already been two separate working projects submitted for Wicket. It just goes to show how easy it is to custom distributable components with Wicket.</p>
<p>When was the last time someone did anything this cool in JSF? I have yet to see a community like Wicket anywhere else in the Java web framework space. Through my scientific research, I estimate that a new opensource Wicket component is created every 10 minutes, while JSF has to wait for 18 months for commercial vendors to get something out the door. =)</p>
<p>Is there anything out there that you can’t do with Wicket? The number of components that are readily available for building web applications is very compelling. Some of the more interesting components include:</p>
<ul>
<li>
<p>google maps integration</p>
</li>
<li>
<p>Rich text editors</p>
</li>
<li>
<p>flickr integration</p>
</li>
<li>
<p>rss publishing tools</p>
</li>
<li>
<p>any javascript framework you can imagine (YUI, prototype/scriptaculous, mootools, jquery)</p>
</li>
</ul>
<p>Are there any pieces missing for building great web applications with Wicket? One comment I’ve heard in the past is, “Community publishing of components is great, but it creates confusion for users on where to pick and choose components from.” Eclipse users struggle with this today while scavenging across the internet to get random plugins to make them productive. Eclipse is trying to help developers by creating the Calisto distribution, and it would be nice to provide a similar “Uber-Wicket” distribution that included the core Wicket library along with several “recommended” components (wicket-extensions, rss, etc). Since Wicket is Apache licensed and some of these great projects are not, it would have to be distributed outside of the Apache project. Any ideas?</p>
Still Swinging2007-12-15T00:00:00+00:00https://codecrate.com/2007/12/still-swinging<p>It’s been a while since my last blog entry, and I hope you’ll believe me when I say that <a href="http://flickr.com/photos/wireframe/tags/sophia">I’ve been busy for the past month or so</a>…</p>
<p>I may have had a break from blogging, but I’ve still been busy coding. Over the past month, I’ve had plenty of time to dive back into <a href="http://shard.dev.java.net">shard</a>. In particular, I’ve been working on a new swing application to replace the laminated grid sheets and dry erase markers that I’ve been using as a battle grid for the past ten years.</p>
<p>I haven’t seen any decent applications out there like this which is quite a surprise. The new 4th edition DnD tools appear to have something going on in this area, but we have quite a wait before those are available and more than likely, they won’t run on linux. Grrr…</p>
<p>This has been a great opportunity to get back into client side Java development. I’ve been exclusively doing web development for quite a while, so it’s been a nice change of pace. Getting back into using the Swing API’s has taken a bit of time, but I’m going to try and stick with it and avoid the Spring Rich Client library like the plague.</p>
<p>I do miss Wicket quite a bit though. There are a lot of similarities between Wicket and Swing, but I think the Wicket API is much nicer. There’s something very odd about Swing where you’re mixing layout and behavior together that just makes me feel a little dirty. If only “Swing 2.0” could go back to the drawing board and take the lessons learned from all of the great UI frameworks out there and remove the cruft that is there today…</p>
<p>The application is still early, but I’m hoping to get a webstart version posted sometime soon. For now, you’ll have to build it from CVS to experience it’s greatness. So far, it’s fully functional with a few nice features:</p>
<ul>
<li>
<p>drag and drop moving of tokens around the grid</p>
</li>
<li>
<p>creating obstacles on the grid can prevent movement along grid paths</p>
</li>
</ul>
<p>Features in the works include:</p>
<ul>
<li>
<p>display length of path for moving tokens around the grid</p>
</li>
<li>
<p>zooming in and out of the grid to display as much or as little as desired</p>
</li>
</ul>
<p>If anyone has ideas for a project name, let me know. I’m looking for something that goes well with the shard-phoenix and the shard-minotaur project names. Maybe, shard-cyclops with the tagline, “I’ve got my eye on you”?</p>
Scriptaculous 1.8 Release2007-11-09T00:00:00+00:00https://codecrate.com/2007/11/scriptaculous-18-release<p>With the <a href="http://script.aculo.us/">recent release of the scriptaculous 1.8 javascript library</a>, I’ve <a href="http://wicketstuff.org/maven/repository/org/wicketstuff/wicketstuff-scriptaculous/1.3-SNAPSHOT/">released an update to the wicketstuff-scriptaculous project</a> that incorporates these latest changes (including prototype 1.6!).</p>
<p>No Java API changes are in this release, so it should be a transparent upgrade for users. See the <a href="http://dev.rubyonrails.org/browser/spinoffs/scriptaculous/CHANGELOG?rev=8083">scriptaculous release notes</a> for a complete list of changes.</p>
NFJS Conference2007-11-02T00:00:00+00:00https://codecrate.com/2007/11/nfjs-conference<p>It’s been a long time coming, but I’m finally posting about my recent experience at the <a href="http://www.nofluffjuststuff.com/show_view.jsp?showId=106">No Fluff, Just Stuff conference</a>.This was my first time at an NFJS conference, and overall it was well worth the weekend.</p>
<p>A few common themes seemed to permeate the show…</p>
<h2 id="jsf">JSF</h2>
<p>Seriously? People are still using this stuff? Damn, maybe the Java community is in worse shape than I thought. Legions of developers using tools simply because they believe in Ivory Tower standards. I was tempted more than once to join a JSF session just to pitch Wicket. I ran into one other Wicket-eer at NFJS and hopefully next year will have a much larger group if the <a href="http://cwiki.apache.org/WICKET/community-meetups.html">Twin Cities Wicket User Group</a> starts up.</p>
<h2 id="agile">Agile</h2>
<p>Everyone and their mother’s uncle is doing Agile. Finally, there are no more Agile vs. Waterfall debates. Test Driven Development is standard practice. Lots of people asking, “How can we do Agile better and take it to the next level?” That’s one of the most powerful tenets of Agile…iterations. Everything is a work in progress, including your development methodology. Interesting presentations revolved around gathering metrics for Agile projects and how to build <a href="/2006/04/running-code-doesn-lie.html">Self Describing Systems</a> to avoid unnecessary documentation.</p>
<h2 id="performance">Performance</h2>
<p>Java developers are in real trouble here. Let me elaborate…</p>
<p>At least 90% of the developers in the Enterprise Application Performance session are building web apps, but we spent 2 hours basically talking about database tuning. HELLO!?!? Have these people been trapped in some kind of alternate universe for the past year? Yes, tuning your backend system is important, but not a single person in that room had heard of how important <a href="http://www.oreilly.com/catalog/9780596529307/">management of your web resources is</a> to the perceived performance of your application! It’s sad that “Enterprise” Java developers don’t have the slightest idea how to build fast webapps.</p>
<p>Another important part of performance for Java applications is understanding the JVM. Understanding the JVM internals is something that every Java developer should be forced to understand, especially garbage collection. There were a few excellent sessions for understanding Java under the hood.</p>
<p>Overall, the conference was great, and I would highly recommend it to anyone else. Hopefully next time around they’ll have a session or two about Wicket! =)</p>
Maven TestDox Updates2007-10-30T00:00:00+00:00https://codecrate.com/2007/10/maven-testdox-updates<p>Based on some recent <a href="http://jira.codehaus.org/browse/MOJO-681">user suggestions</a>,
I’ve released a <a href="http://maven.codecrate.com/com/codecrate/maven/plugins/testdox-maven-plugin/">new version of the maven testdox plugin</a>.</p>
<p>Notable changes in this release are to try and make the report even more “human readable”:</p>
<ul>
<li>trim off package name for the test class name (ex: com.mysite.FooTest becomes Foo)</li>
<li>add spaces to the test class name (ex: FooBarTest becomes Foo bar)</li>
</ul>
<p>Let me know if there are any other things that can be done to improve this plugin. Actually, if anyone out there would like to help make the HTML report look a bit more “spiffy”, I could use the help!</p>
<p>See my <a href="/2006/04/running-code-doesn-lie.html">previous</a>
<a href="/2007/03/testdox-maven-plugin.html">blog</a>
<a href="/2007/09/official-testdox-maven-plugin-release.html">posts</a> for the history of this plugin.</p>
Static Finders in Java2007-10-02T00:00:00+00:00https://codecrate.com/2007/10/static-finders-in-java<p>For the past couple days, I’ve been unnaturally obsessed with the Ruby syntax for looking up persistent objects. The <a href="http://railsmanual.org/class/ActiveRecord::Base/find/1.1.2">ActiveRecord find API</a> is absolutely a piece of art.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># returns the object for ID = 1</span>
<span class="no">Book</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
</code></pre></div></div>
<p>While Java API’s force developers to think about Services and DAO’s, Ruby/ActiveRecord focuses on the Domain Model which is all that really matters. I’ve <a href="/2006/07/humane-object-iteration.html">said this in the past</a>, it’s all about context. We need to be creating expressive and simple API’s that enable developers to build applications without being constrained by the underlying architecture.</p>
<p>What if we could have the best of both worlds? Why don’t we see this kind of Ruby syntax in Java applications? Is it because of the assumption that <a href="http://beust.com/weblog/archives/000173.html">static methods are evil</a>? Java developers have a lot to learn from Ruby, and here’s how to build a Ruby-like finder method in Java.</p>
<p>I’ll start with my client code. It needs to be simple and not worried about Services or Daos to lookup my persistent objects.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">BookLister</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">printBooks</span><span class="o">()</span> <span class="o">{</span>
<span class="n">foreach</span> <span class="o">(</span><span class="nc">Book</span> <span class="n">book</span> <span class="o">:</span> <span class="nc">Book</span><span class="o">.</span><span class="na">findAll</span><span class="o">())</span> <span class="o">{</span>
<span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">book</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Next, we need expose this finder method on our business object. Don’t worry, I’m not advocating that we perform some magic hack to manually create database connections within these methods. We’ll use standard dependency injection techniques and encapsulate the database access within a standard DAO object and delegate the call from the business object to the DAO.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Book</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="nc">BookDao</span> <span class="n">dao</span><span class="o">;</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">name</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="nc">Collection</span> <span class="nf">findAll</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">dao</span><span class="o">.</span><span class="na">findAll</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">setBookDao</span><span class="o">(</span><span class="nc">BookDao</span> <span class="n">dao</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">dao</span> <span class="o">=</span> <span class="n">dao</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Our final step is to configure the business object to have access to the DAO. This is super simple for a Spring application, and I’d be very interested to see if something like Guice could be used instead of this XML configuration. Or maybe build some custom Annotations?</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>beans<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean id="bookDao" class="com.mysite.BookDao" /<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean id="bookInit" class="com.mysite.Book"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>property name="bookDao"<span class="ni">&gt;&lt;</span>ref bean="bookDao" /<span class="ni">&gt;&lt;</span>/property<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/beans<span class="ni">&gt;</span>
</code></pre></div></div>
Wicket FeedResource2007-09-12T00:00:00+00:00https://codecrate.com/2007/09/wicket-feedresource<p>Just when I think I’m a Wicket guru, I discover a new layer to this pretty amazing framework.</p>
<p>One of <a href="/2007/05/from-components-to-behaviors.html">my previous posts</a>, I mentioned that the three key concepts for working with Wicket were Components, Models, and Behaviors. Well, it looks like I’m going to add Resources to that list as well. I started uncovering the Wicket Resource after finishing up my <a href="/2007/08/wicket-and-rss-feeds.html">Wicket FeedPage contribution</a>. I got some excellent feedback and was advised <a href="/2006/12/wicket-feedpage.html">to use a Resource instead of a WebPage</a>.</p>
<p>What’s the difference between a Resource and a WebPage? They both can serve HTML/XML content, but a Resourcealso allows for serving up of arbitrary content (like download files). Resources are more like lightweight version of WebPages that are not versioned and do not allow Components to be embedded into them. It definitely makes sense to me that a Feed would be considered a Resource for a WebPage instead of a standalone entity.</p>
<p>The API for creating a FeedResource is very similar to creating the FeedPage:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyFeedResource</span> <span class="kd">extends</span> <span class="nc">FeedResource</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="nc">SyndFeed</span> <span class="nf">getFeed</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//construct and return the feed as usual</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Where things start to get interesting is when you want to reference this FeedResource from within your application. You can’t construct a link to a Resource in the same way as to a WebPage, you’ll need to create a ResourceReference to indirectly talk to the Resource instead. ResourceReferences are pretty cryptic, but I’ve had some pointers from the Wicket Developers, so hopefully I’m on the right track.</p>
<p>Constructing a URL to the FeedResource is particularly important if you want browser’s to automatically detect your feed and display their fancy RSS icon. The simplest way to construct this autodiscovery link the FeedResource.autodiscoveryLink() API which will automatically insert the browser autodiscovery link into the HTML head.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyPage</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">MyPage</span><span class="o">()</span> <span class="o">{</span>
<span class="n">add</span><span class="o">(</span><span class="nc">FeedResource</span><span class="o">.</span><span class="na">autodiscoveryLink</span><span class="o">(</span><span class="k">new</span> <span class="nc">ResourceReference</span><span class="o">(</span><span class="s">"myFeed"</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="nc">Resource</span> <span class="nf">newResource</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="nf">MyFeedResource</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}));</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This is a pretty simple example, and there are a number of different ways to use ResourceReferences, so don’t take this as the only way to create the autodiscovery link.</p>
<p>Download the latest version and give it a spin! Let me know if there are any other suggestions to make this the best RSS integration for any Java web framework!</p>
Official Testdox Maven Plugin Release2007-09-08T00:00:00+00:00https://codecrate.com/2007/09/official-testdox-maven-plugin-release<p>It seems as though the <a href="http://mojo.codehaus.org">Codehaus Mojo Project</a> has reached the end of the line. After finishing up my <a href="/2007/03/testdox-maven-plugin.html">testdox maven plugin</a>, I tried to <a href="http://jira.codehaus.org/browse/MOJO-681">contribute my plugin</a> to the Codehaus Project, but it has fallen on deaf ears. I guess it’s time to take things into my own hands, and so I’m happy to announce the <a href="http://maven.codecrate.com/com/codecrate/maven/plugins/testdox-maven-plugin/">first official release of the testdox maven plugin</a>.</p>
<p>Enabling the plugin is a snap. Just add this xml block to your maven2 project and the next time you build your site documentation, the superfancy testdox report will be included in your project reports.</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>codecrate-repository<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>name<span class="ni">&gt;</span>Codecrate Repository<span class="ni">&lt;</span>/name<span class="ni">&gt;</span>
<span class="ni">&lt;</span>url<span class="ni">&gt;</span>http://maven.codecrate.com/<span class="ni">&lt;</span>/url<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>reporting<span class="ni">&gt;</span>
<span class="ni">&lt;</span>plugins<span class="ni">&gt;</span>
<span class="ni">&lt;</span>plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>com.codecrate.maven.plugins<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>testdox-maven-plugin<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugin<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/plugins<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/reporting<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Just incase you’ve missed out on my previous <a href="/2006/04/running-code-doesn-lie.html">blog</a><a href="/2007/03/testdox-maven-plugin.html">entries</a>, the testdox report creates a human readable HTML report of your JUnit test suites. Try it out today, and let me know what you think!</p>
<p>It’s unfortunate that the Codehaus Mojo project is in the state that it is. Since the Maven core codebase is ASF licensed, non-ASF contributions can not be included in the Maven core. That makes this this extension project extremely important to encourage users to develop plugins for the “rest of the non-ASF” world.</p>
<p>This is exactly why the wicket-stuff project is such an important partner to the core wicket project. And wicket-stuff is definitely doing things right. Tons of contributions and an extremely low barrier for new projects to get up and running.</p>
Wicket and RSS Feeds2007-08-23T00:00:00+00:00https://codecrate.com/2007/08/wicket-and-rss-feeds<p>I love Wicket, and I love RSS so it’s only logical that I’d find a way to serve up RSS within Wicket. There’s an <a href="http://cwiki.apache.org/WICKET/rss-page.html">example RssPage posted on the Wicket wiki</a>, and I posted a <a href="/2006/12/wicket-feedpage.html">simple RSS solution</a> a while back, but neither of these are really solid solutions. For the past few weeks I’ve been working heavily with serving RSS feeds, and I’ve finally gotten to a point where I can provide something back to the Wicket community.</p>
<p>Introducing, the new and improved Wicket FeedPage. It’s actually the same API as my previous solution, but the inner workings are much improved. To create an RSS feed, just create a subclass of FeedPage and follow the <a href="https://rome.dev.java.net/">ROME API</a> to create a SyndFeed for your RSS (or Atom) content.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ItemFeedPage</span> <span class="kd">extends</span> <span class="nc">FeedPage</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="nc">SyndFeed</span> <span class="nf">getFeed</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">SyndFeed</span> <span class="n">feed</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndFeedImpl</span><span class="o">();</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setFeedType</span><span class="o">(</span><span class="s">"rss_2.0"</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setTitle</span><span class="o">(</span><span class="s">"Sample Feed"</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setLink</span><span class="o">(</span><span class="s">"http://mysite.com"</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setDescription</span><span class="o">(</span><span class="s">"Sample Feed for how cool Wicket is"</span><span class="o">);</span>
<span class="nc">List</span> <span class="n">entries</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="nc">SyndEntry</span> <span class="n">entry</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndEntryImpl</span><span class="o">();</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setTitle</span><span class="o">(</span><span class="s">"Article One"</span><span class="o">);</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setLink</span><span class="o">(</span><span class="s">"http://mysite.com/article/one"</span><span class="o">);</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setPublishedDate</span><span class="o">(</span><span class="k">new</span> <span class="nc">Date</span><span class="o">());</span>
<span class="nc">SyndContent</span> <span class="n">description</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndContentImpl</span><span class="o">();</span>
<span class="n">description</span><span class="o">.</span><span class="na">setType</span><span class="o">(</span><span class="s">"text/plain"</span><span class="o">);</span>
<span class="n">description</span><span class="o">.</span><span class="na">setValue</span><span class="o">(</span><span class="s">"Article descriping how cool wicket is."</span><span class="o">);</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setDescription</span><span class="o">(</span><span class="n">description</span><span class="o">);</span>
<span class="n">entries</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">entry</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setEntries</span><span class="o">(</span><span class="n">entries</span><span class="o">);</span>
<span class="k">return</span> <span class="n">feed</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The ROME library has really impressed me and does an excellent job of hiding the internals of creating these feeds. Want to change from RSS to Atom? Simple! Just change this line:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">feed</span><span class="o">.</span><span class="na">setFeedType</span><span class="o">(</span><span class="s">"rss_2.0"</span><span class="o">);</span>
</code></pre></div></div>
<p>to this</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">feed</span><span class="o">.</span><span class="na">setFeedType</span><span class="o">(</span><span class="s">"atom_0.3"</span><span class="o">);</span>
</code></pre></div></div>
<p>As Borat would say…“Very Nice!”</p>
<p>I’ve created a <a href="https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicketstuff-rome/">new Wicket Stuff project</a> to host this project which should make it super easy to get up and going. Just add this block to your pom.xml file:</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>wicket-stuff-repository<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>name<span class="ni">&gt;</span>Wicket-Stuff Repository<span class="ni">&lt;</span>/name<span class="ni">&gt;</span>
<span class="ni">&lt;</span>url<span class="ni">&gt;</span>http://www.wicketstuff.org/maven/repository/<span class="ni">&lt;</span>/url<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>dependencies<span class="ni">&gt;</span>
<span class="ni">&lt;</span>dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>org.wicketstuff<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>wicketstuff-rome<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>version<span class="ni">&gt;</span>1.3-SNAPSHOT<span class="ni">&lt;</span>/version<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependencies<span class="ni">&gt;</span>
</code></pre></div></div>
<p>As a side note, if you’re having difficulty creating a dynamic url for use in your feed (guid, return url, etc) vote for <a href="https://issues.apache.org/jira/browse/WICKET-609">this Wicket issue</a> to help create a new API for that info.</p>
Performance Testing using JUnit2007-08-17T00:00:00+00:00https://codecrate.com/2007/08/performance-testing-using-junit<p>I’ve been heavily involved with a major performance initiative for the past several months. One thing I have constantly found frustrating is how few good tools exist for this type of work. Specifically, I have yet to run across a good Java library for programatically measuring performance metrics.</p>
<p>You may be quick to try and point me to <a href="http://clarkware.com/software/JUnitPerf.html">JUnitPerf</a>, but let me stop you right there and tell you that JUnitPerf is utter crap. It is simply a cobbled together set of incoherent API’s that are more effort than their worth. They had the right idea, but their end product is rubbish.</p>
<p>What do I have that’s any better? Let’s start with this as our base class:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">PerformanceTestCase</span> <span class="kd">extends</span> <span class="nc">TestCase</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">assertFasterThan</span><span class="o">(</span><span class="kt">long</span> <span class="n">millis</span><span class="o">,</span> <span class="nc">Runnable</span> <span class="n">runnable</span><span class="o">)</span> <span class="o">{</span>
<span class="kt">long</span> <span class="n">start</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">currentTimeMillis</span><span class="o">();</span>
<span class="n">runnable</span><span class="o">.</span><span class="na">run</span><span class="o">();</span>
<span class="kt">long</span> <span class="n">executionTime</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">currentTimeMillis</span><span class="o">()</span> <span class="o">-</span> <span class="n">start</span><span class="o">;</span>
<span class="n">assertTrue</span><span class="o">(</span><span class="s">"Expected execution time to be less than "</span> <span class="o">+</span> <span class="n">millis</span> <span class="o">+</span> <span class="s">" but was "</span> <span class="o">+</span> <span class="n">executionTime</span><span class="o">,</span> <span class="n">executionTime</span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Using this little base class, I can start to write a real performance test using a standard JUnit API like so:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObjectTestCase</span> <span class="kd">extends</span> <span class="nc">PerformanceTestCase</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">testMyOperationIsFasterThanTheSpeedOfLight</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//perform setup here</span>
<span class="kd">final</span> <span class="nc">MyObject</span> <span class="n">object</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">MyObject</span><span class="o">();</span>
<span class="nc">Runnable</span> <span class="n">work</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Runnable</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//do work that should be measured here</span>
<span class="n">object</span><span class="o">.</span><span class="na">doStuff</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="n">assertFasterThan</span><span class="o">(</span><span class="mi">10</span><span class="o">,</span> <span class="n">work</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Using assertFasterThan is a good start, but anyone who’s done real performance testing knows that there are lots of factors that cause fluctuations in the execution speed of code. This is especially true when your building integration tests that interact with databases or other resources. To get a more reliable metric, we need to execute the same block of code multiple times and grab the average. Here’s an new method to perform just that.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protected</span> <span class="kt">void</span> <span class="nf">assertAverageFasterThan</span><span class="o">(</span><span class="kt">long</span> <span class="n">millis</span><span class="o">,</span> <span class="nc">Runnable</span> <span class="n">runnable</span><span class="o">,</span> <span class="kt">int</span> <span class="n">numberOfExecutions</span><span class="o">)</span> <span class="o">{</span>
<span class="kt">long</span> <span class="n">start</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">currentTimeMillis</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">x</span> <span class="o">&</span><span class="n">lt</span><span class="o">;</span> <span class="n">numberOfExecutions</span><span class="o">;</span> <span class="n">x</span><span class="o">++)</span> <span class="o">{</span>
<span class="n">runnable</span><span class="o">.</span><span class="na">run</span><span class="o">();</span>
<span class="o">}</span>
<span class="kt">long</span> <span class="n">executionTime</span> <span class="o">=</span> <span class="nc">System</span><span class="o">.</span><span class="na">currentTimeMillis</span><span class="o">()</span> <span class="o">-</span> <span class="n">start</span><span class="o">;</span>
<span class="kt">long</span> <span class="n">average</span> <span class="o">=</span> <span class="n">executionTime</span> <span class="o">/</span> <span class="n">numberOfExecutions</span><span class="o">;</span>
<span class="n">assertTrue</span><span class="o">(</span><span class="s">"Expected average execution time to be less than "</span> <span class="o">+</span> <span class="n">millis</span> <span class="o">+</span> <span class="s">" but was "</span> <span class="o">+</span> <span class="n">average</span><span class="o">,</span> <span class="n">average</span> <span class="o"><=</span> <span class="n">millis</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, I can execute my code a number of times to make sure that one slow (or fast) execution doesn’t skew my results.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObjectTestCase</span> <span class="kd">extends</span> <span class="nc">PerformanceTestCase</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">testMyOperationIsFasterThanTheSpeedOfLight</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//perform setup here</span>
<span class="kd">final</span> <span class="nc">MyObject</span> <span class="n">object</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">MyObject</span><span class="o">();</span>
<span class="nc">Runnable</span> <span class="n">work</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Runnable</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//do work that should be measured here</span>
<span class="n">object</span><span class="o">.</span><span class="na">doStuff</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="c1">//execute the block of code 100 times and take the average</span>
<span class="n">assertAverageFasterThan</span><span class="o">(</span><span class="mi">10</span><span class="o">,</span> <span class="n">work</span><span class="o">,</span> <span class="mi">100</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Before I finish, let me remind everyone:</p>
<p><a href="/2006/04/performance-is-overrated.html">Early optimization is the root of much evil.</a></p>
<p>These tools and techniques should be used sparingly and only under the supervision of a licensed therapist. =)</p>
Wicketstuff-Hibernate Updates2007-06-28T00:00:00+00:00https://codecrate.com/2007/06/wicketstuff-hibernate-updates<p>It’s been a week since [the first “release” of my wicket/hibernate integration, and the <a href="http://www.nabble.com/HibernateAnnotationComponentConfigurator-t3969383.html#a11266736">feedback from the wicket community</a> has been pretty amazing.</p>
<p>Short iterations are the key to software success, so I’ve incorporated a number of changes suggested by folks and <a href="http://www.wicketstuff.org/maven/repository/org/wicketstuff/wicketstuff-hibernate/">pushed out a new snapshot release</a>. Changes include:</p>
<ul>
<li>Support OGNL PropertyModel expressions for resolving annotations on models using nested properties. This feature was suggested by Matej, and now allows for the hibernate configurator to inspect _any_PropertyModelthat’s supported by Wicket. ex:</li>
</ul>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">new</span> <span class="nc">PropertyModel</span><span class="o">(</span><span class="k">new</span> <span class="nc">MyObject</span><span class="o">(),</span> <span class="s">"innerObject.name"</span><span class="o">);</span>
</code></pre></div></div>
<ul>
<li>
<p>Prevent re-configuring a component if it has already been rendered. A nice optimization suggested by Igor which is especially useful for ajax heavy applications using the hibernate configurator as an application listener. This will remove any overhead for when a component is rendered multiple times.</p>
</li>
<li>
<p>Support any model that implements IPropertyReflectionAwareModelinterface. This opens up the door for users to use other implementations of Model and not be limited to just using a PropertyModel.</p>
</li>
</ul>
<p>The feedback has been great, and I would love to hear more from users about other areas as well.</p>
<ul>
<li>
<p>What can be done to allow for drop dead simple integration of this hibernate configurator with other projects?</p>
</li>
<li>
<p>Is there anything preventing you from using this hibernate configurator with your project?</p>
</li>
<li>
<p>What other hibernate annotations would be useful to integrate?</p>
</li>
</ul>
HibernateAnnotationComponentConfigurator2007-06-22T00:00:00+00:00https://codecrate.com/2007/06/hibernateannotationcomponentconfigurato<p>It’s been an impressively difficult task to improve upon the <a href="/2007/05/hibernate-annotations-and-wicket.html">initial version of my Wicket/Hibernate integration</a>, but I finally hit a break through. Introducing the new HibernateAnnotationComponentConfigurator. <em>Long enough name for you?</em>=)</p>
<p>This object is used to configure a Wicket Component based on Hibernate annotations. It inspects the Model of a FormComponent and configures the Component according to the declared Hibernate Annotations used on the Model object. This means the Component’s Model_must_be known when configuring a Component.</p>
<p>This object can be used as a Behavior to configure a single Component. NOTE: This object is stateless, and the same instance can be reused to configure multiple Components.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyWebPage</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">MyWebPage</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">TextField</span> <span class="n">name</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">TextField</span><span class="o">(</span><span class="s">"id"</span><span class="o">,</span> <span class="k">new</span> <span class="nc">PropertyModel</span><span class="o">(</span><span class="n">user</span><span class="o">,</span> <span class="s">"name"</span><span class="o">);</span>
<span class="n">name</span><span class="o">.</span><span class="na">addBehavior</span><span class="o">(</span><span class="k">new</span> <span class="nc">HibernateAnnotationComponentConfigurator</span><span class="o">());</span>
<span class="n">add</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This object can also be used as a component listener that will automatically configure _all_FormComponents based on Hibernate annotations. This ensures that an entire application respects annotations without adding custom Validators or Behaviors to each FormComponent.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyApplication</span> <span class="kd">extends</span> <span class="nc">WebApplication</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">init</span><span class="o">()</span> <span class="o">{</span>
<span class="n">addComponentOnBeforeRenderListener</span><span class="o">(</span><span class="k">new</span> <span class="nc">HibernateAnnotationComponentConfigurator</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I’m extremely excited that it is now possible for an <em>entire application_to automatically use Hibernate annotations without any extra work. As far as I know, this is a first for _any</em> Java web framework and just goes to show how much Wicket rocks.</p>
<p>So, what are you waiting for? Start using this today by <a href="http://www.wicketstuff.org/maven/repository/org/wicketstuff/wicketstuff-hibernate/">downloading the latest build</a>. Maven2 users have it even simpler by adding this to your POM.xml file:</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>wicket-stuff-repository<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>name<span class="ni">&gt;</span>Wicket-Stuff Repository<span class="ni">&lt;</span>/name<span class="ni">&gt;</span>
<span class="ni">&lt;</span>url<span class="ni">&gt;</span>http://www.wicketstuff.org/maven/repository/<span class="ni">&lt;</span>/url<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>dependencies<span class="ni">&gt;</span>
<span class="ni">&lt;</span>dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>org.wicketstuff<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>wicketstuff-hibernate<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>version<span class="ni">&gt;</span>1.3-SNAPSHOT<span class="ni">&lt;</span>/version<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependencies<span class="ni">&gt;</span>
</code></pre></div></div>
From Components To Behaviors2007-05-25T00:00:00+00:00https://codecrate.com/2007/05/from-components-to-behaviors<p>In my opinion, there are three very key concepts to Wicket’s architecture. Luckily, these concepts are easy enough to grasp to get up and running quickly, but they also have a lot of depth if you want to dig in to them. The high level concepts are:</p>
<ol>
<li>
<p>Components - Very similar to Swing Components. Could refer to them as Widgets.</p>
</li>
<li>
<p>Models - Encapsulates how Components retrieve and save data.</p>
</li>
<li>
<p>Behaviors - Used to enhancea Component with new functionality.</p>
</li>
</ol>
<p>I’ve been working with Wicket for quite a while now, and I think I finally understand the power of Behaviors. It’s kind of like The Matrix, when Neo finally can see through the code.</p>
<p>You’ll notice that the new version of wicketstuff-scriptaculous has dropped Autocompletion Components in favor of Behaviors. Compare the old solution to the new code. Using the old component looked like this:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">AutocompleteTextField</span> <span class="n">color</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">AutocompleteTextField</span> <span class="o">(</span><span class="s">"color"</span><span class="o">,</span> <span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span><span class="s">"red"</span><span class="o">,</span> <span class="s">"green"</span><span class="o">,</span> <span class="s">"blue"</span><span class="o">});</span>
</code></pre></div></div>
<p>And the new implementation looks like this:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">TextField</span> <span class="n">color</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">TextField</span><span class="o">(</span><span class="s">"color"</span><span class="o">);</span>
<span class="n">color</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">AutocompleteBehavior</span><span class="o">(</span><span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span><span class="s">"red"</span><span class="o">,</span> <span class="s">"green"</span><span class="o">,</span> <span class="s">"blue"</span><span class="o">}));</span>
</code></pre></div></div>
<p>Why is this such a big deal?</p>
<p>For starters, you are no longer coupled to a particularTextField implementation. This is great for when people create their own subclasses of Components to customize behavior. For example, I might create a simple RequiredTextField Component. Using Behaviors allows you to use this functionality on anyTextField Component! Using Components forces users to use class extension to customize behavior while using Behaviors allows for a mix-and-match approach more like interfaces.</p>
<p>Building Components is also tricky because most Wicket Components have several constructors. For example, the Wicket Image Component has 3 unique constructors. So, if you’re going to build a custom Image Component, you need to support all of the various ways to construct the parent Image Component. On the other hand, Behaviors don’t care how the Component was constructed. It’s job is to just add some additional functionality to the Component it’s attached to.</p>
<p>And that, my friends, is why Wicket Behaviors kick serious ass.</p>
Updated Wicketstuff-Scriptaculous Project2007-05-16T00:00:00+00:00https://codecrate.com/2007/05/updated-wicketstuff-scriptaculous<p>Just incase anyone thought that the <a href="/2007/01/wicket-scriptaculous-011-release.html">wicket-contrib-scriptaculous project</a> had dropped off the face of the earth, this is just a reminder that it’s still going strong!</p>
<p>There have been a number of _great_changes made lately (which I will be blogging about later), including a <strong>new project name</strong> (which was _much_needed). I now give you the <strong>wicketstuff-scriptaculous project</strong>.</p>
<p>For those maven users out there, you can start using the <em>bleeding edge</em> development version by pointing to the wicketstuff maven repository and adding the wicketstuff-scriptaculous dependency as follows:</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>id<span class="ni">&gt;</span>wicket-stuff-repository<span class="ni">&lt;</span>/id<span class="ni">&gt;</span>
<span class="ni">&lt;</span>name<span class="ni">&gt;</span>Wicket-Stuff Repository<span class="ni">&lt;</span>/name<span class="ni">&gt;</span>
<span class="ni">&lt;</span>url<span class="ni">&gt;</span>http://www.wicketstuff.org/maven/repository/<span class="ni">&lt;</span>/url<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repository<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/repositories<span class="ni">&gt;</span>
<span class="ni">&lt;</span>dependencies<span class="ni">&gt;</span>
<span class="ni">&lt;</span>dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>org.wicketstuff<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>wicketstuff-scriptaculous<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>version<span class="ni">&gt;</span>1.3-SNAPSHOT<span class="ni">&lt;</span>/version<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependencies<span class="ni">&gt;</span>
</code></pre></div></div>
Hibernate Annotations and Wicket2007-05-08T00:00:00+00:00https://codecrate.com/2007/05/hibernate-annotations-and-wicket<p>Wow. It’s been an insane 24 hours.</p>
<p>It all started by me posting this simple question on the wicket mailing list:</p>
<p>Anyone have some fancy integration of hibernate and wicket?</p>
<p>The response?</p>
<p>Why don’t you write one?</p>
<p>And so it began…</p>
<p>After a flurry of research into this area, I’ve whipped together a hibernate/wicket object that reads <a href="http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/">hibernate annotations</a> and configures the wicket component respectively.</p>
<p>Essentially, right now it will auto configure a component by:</p>
<ul>
<li>
<p>set component to be “required” when using NotNullannotation</p>
</li>
<li>
<p>add “maxlength” attribute when using Lengthannotation</p>
</li>
</ul>
<p>Still lots of work to be done:</p>
<ul>
<li>
<p>attach client side javascript validation</p>
</li>
<li>
<p>maybe integrate into the wicket validation framework?</p>
</li>
</ul>
<p>The code is checked into wicket stuff and I’d appreciate anyone interested to take a look and let me know what they think.</p>
<p><a href="http://wicket-stuff.svn.sourceforge.net/viewvc/wicket-stuff/trunk/wicketstuff-hibernate-behavior/">http://wicket-stuff.svn.sourceforge.net/viewvc/wicket-stuff/trunk/wicketstuff-hibernate-behavior/</a></p>
TestDox Maven Plugin2007-03-06T00:00:00+00:00https://codecrate.com/2007/03/testdox-maven-plugin<p>You may see a new maven2 plugin showing up soon at the <a href="http://mojo.codehaus.org/">Codehaus Mojo project sandbox</a>. I just submitted a new maven2 plugin for generating an HTML report using <a href="http://agiledox.sourceforge.net/">TestDox</a>. This should make a great accessory report to the existing maven junit reports, and should be more usable by non-techie folks.</p>
<p>I’ve <a href="/2006/04/running-code-doesn-lie.html">written about TestDox in the past</a>, and I finally got off my lazy ass because it has tremendous value for me. It actually was pretty painless to create, and there’s definitely opportunities for improvements, but hey, it works.</p>
<p>Here’s an example of what the output will be. The only difference is that the report will be fully integrated with the maven generated site with all the fancy links and menus.</p>
<h3 id="testdoxformatter">TestDoxFormatter</h3>
<ul>
<li>
<p>Pretty class name removes test suffix</p>
</li>
<li>
<p>Pretty method name removes test prefix</p>
</li>
</ul>
<p>Enjoy, and make sure to let me know what would make this plugin more useful.</p>
JRoller Is The Suck2007-02-17T00:00:00+00:00https://codecrate.com/2007/02/jroller-is-suck<p>I haven’t been the biggest fan of JRoller, and now they’ve sunk to a new low, adding spam to my RSS feed. This comes at a time when JRoller might finally be getting some good press for <a href="http://www.javalobby.org/java/forums/t59326.html">breaking 10,000 users</a>.</p>
<p>Who the crap is DZone and why are they scamming my RSS feeds!?</p>
<p>Tired of your job? Need to hire developers? Visit DZone Jobs: great people, great opportunities.</p>
<p>Well, I’m tired of this crappy service! Time to look for a new provider. Luckily those of you subscribing to this feed using my feedburner url will not be affected by any changes. Any suggestions other than blogspot for blog hosting?</p>
<p>I probably wouldn’t have caught this except for the fact that I subscribe to my own RSS feed, and started seeing this junk after each post. Nice try JRoller! You can’t slip something like this past me!</p>
Test Driven Death2007-02-14T00:00:00+00:00https://codecrate.com/2007/02/test-driven-death<p>It’s just another form of TDD…</p>
<p>This may sound weird coming from me, but there are times when unit testing can do more harm than good. Writing test code incorrectly, can lead to code strangulation. I’ve seen this come up time and time again when dealing with a legacy codebase that was written cowboy with no unit tests, and now the team wants to try and insulate the codebase by adding unit tests. Needless to say, this is extremely difficult since code is rarely written to be testable unless tests already exist.</p>
<p>In the end, unit tests become extremely bloated and difficult to understand. What’s the problem with this scenario? Isn’t having the unit test actually a good thing? No. Not necessarily. Now that the codebase has built up a suite of brittle, bloated unit tests, the business code becomes even more difficult to change. Every change to the business layer has the potential to break the unit tests, since the tests were not first class citizens and are usually just hacked together. Each time a test breaks, developers must dig through the test to see if something is really wrong, or if the test just needs to be hacked some more to accommodate the recent changes.</p>
<p>Agile software development uses unit tests to facilitate and enable change. Having these tests allows for developers to work quickly without worrying about breaking functionality. Unit tests written after the fact actually inhibit change and slow down development as a whole.</p>
HSQLDB Datasource2007-02-13T00:00:00+00:00https://codecrate.com/2007/02/hsqldb-datasource<p>I use <a href="http://hsqldb.org">HSQLDB</a> in my development environment, and for the most part it works great. I ran into a recent issue though that caught me off guard.</p>
<p>As you may (or may not) know, HSQLDB only allows for one connection to the database at a time. Most applications will work fine with this limitation, unless you have an embedded application that can be started and restarted within the same JVM.</p>
<p>HSQLDB uses a JVM shutdown hook to release the database lock which can be an issue if your application doesn’t kill the JVM when “shutting down”. Here’s a scenerio when this can be an issue:</p>
<ol>
<li>
<p>Embedded application starts up. A new JVM is initialized.</p>
</li>
<li>
<p>Database Datasourcestarts up and connects to the database. HSQLDB will create the file lock.</p>
</li>
<li>
<p>Embedded application is shutdown. The JVM does not exit.</p>
</li>
<li>
<p>Datasourcecloses, but HSQLDB does not release the file lock since the JVM did not exit.</p>
</li>
<li>
<p>Embedded application is restarted in the same JVM.</p>
</li>
<li>
<p>Database Datasourcestarts up and tries to connect to the database. A big fat stacktrace is thrown because the HSQLDB database is still locked from the previous instance.</p>
</li>
</ol>
<p>So, I did a bit of searching and found that you can manually tell HSQLDB to shutdown and release the database lock. Here’s a nice little extension to the <a href="http://jakarta.apache.org/commons/dbcp/">commons dbcp</a>Datasource that will correctly shutdown HSQLDB when the Datasource is closed.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
* Datasource that shuts down the hsqldb when the data source is closed.
* hsql is normally only shutdown with a JVM hook, so this datasource is
* better suited when you need to shutdown/restart within one JVM.
*
* @see http://hsqldb.org
*/</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">HsqldbDataSource</span> <span class="kd">extends</span> <span class="nc">BasicDataSource</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">close</span><span class="o">()</span> <span class="kd">throws</span> <span class="nc">SQLException</span> <span class="o">{</span>
<span class="nc">Connection</span> <span class="n">conn</span> <span class="o">=</span> <span class="n">getConnection</span><span class="o">();</span>
<span class="nc">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="na">createStatement</span><span class="o">();</span>
<span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">"SHUTDOWN"</span><span class="o">);</span>
<span class="n">statement</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="n">conn</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="kd">super</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
Hibernate LoadAll Feature2007-02-12T00:00:00+00:00https://codecrate.com/2007/02/hibernate-loadall-feature<p>I’ve used <a href="http://hibernate.org">Hibernate</a> off and on over the years, and just recently discovered one of its weirdest features.</p>
<p>I’ll setup a simple test scenerio to best illustrate the behavior. First, I’ll create a persistent object that has a mapped Collection. The classic Department/Employee example seems to fit the bill.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Entity</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Department</span> <span class="o">{</span>
<span class="nd">@OneToMany</span>
<span class="kd">private</span> <span class="nc">Collection</span> <span class="n">employees</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, here’s a simple Spring DAO that is used to load all the Departments.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">DepartmentDao</span> <span class="kd">extends</span> <span class="nc">HibernateDaoSupport</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nc">List</span> <span class="nf">getDepartments</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="nf">getHibernateTemplate</span><span class="o">().</span><span class="na">loadAll</span><span class="o">(</span><span class="nc">Department</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Okay. This all works great. Let’s make one little change to have the Employee’s loaded eagerly instead of lazily.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Entity</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Department</span> <span class="o">{</span>
<span class="nd">@OneToMany</span><span class="o">(</span><span class="n">fetch</span><span class="o">=</span><span class="nc">FetchType</span><span class="o">.</span><span class="na">EAGER</span><span class="o">)</span>
<span class="kd">private</span> <span class="nc">Collection</span> <span class="n">employees</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>
<p>With this one little change, the shit hits the fan. Now, duplicate Departments show up on my listing page. Why the hell are duplicates showing up? Hibernate uses an outer join to eagerly load all of the Employee information with the Department. So, when it queries for all Departments, you’re actually getting back the same Department multiple times (one time for each Employee).</p>
<p>I could swear that this is a bug, but according to the Hibernate folks, it appears to be <a href="http://www.hibernate.org/117.html">Working as Designed</a>. So, I whipped up a little helper method to filter out all the duplicates. It literally took my two hours to figure out that Hibernate was the problem and not my code. Anyone else out there been bit by this behavior before?</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">DepartmentDao</span> <span class="kd">extends</span> <span class="nc">HibernateDaoSupport</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nc">List</span> <span class="nf">getDepartments</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="nf">loadAllUnique</span><span class="o">(</span><span class="nc">Department</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="o">}</span>
<span class="cm">/**
* Loads all the unique instances of a given Class (to work around issue with duplicate
* rows when eagerly fetching collections).
*
* @see http://www.hibernate.org/117.html
*/</span>
<span class="kd">private</span> <span class="nc">List</span> <span class="nf">loadAllUnique</span><span class="o">(</span><span class="nc">Class</span> <span class="n">clazz</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="nf">ArrayList</span><span class="o">(</span><span class="k">new</span> <span class="nc">LinkedHashSet</span><span class="o">(</span><span class="n">getHibernateTemplate</span><span class="o">().</span><span class="na">loadAll</span><span class="o">(</span><span class="n">clazz</span><span class="o">)));</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
Fuel to the Fire2007-01-25T00:00:00+00:00https://codecrate.com/2007/01/fuel-to-fire<p>It’s funny…There are days when I enjoy my current place of work, and there are days that I’m literally a few seconds away from losing it.</p>
<p>Today, I raised some questions regarding processes that go against effective software development. I’m a software developer, and things that keep me from developing should be kept to a minimum, right? The response I received? “We’re not a software development company. Never have been. Never will be.”</p>
<p>Damn. Isn’t that motivating? Sure, I could cave in and give up all of my lofty, idealogical development thoughts. I could wuss out and become a thoughtless drone churning out lines and lines of code. I could accept the fact that the folks in charge have no idea how software development works.</p>
<p>But there’s a problem with that…</p>
<p><a href="http://jroller.com/page/wireframe/?anchor=the_curse_of_passion">I have passion for what I do</a>.</p>
<p>I’d just like to take a moment to thank all those <a href="http://en.wikiquote.org/wiki/Office_Space">no-talent-ass-clowns</a> that have helped shape me into the person I am today. I wouldn’t be always on the lookout for the next big thing if it weren’t for you.</p>
<p>So, thank you Corporate America for belittling your employees. Thank you for encouraging marketplace innovation through disruptive channels by creating a disgruntled workforce who’s only goal is to break free from the monotonous noise churned out by white collar workforces. The successful internet startup companies of the past, present and future couldn’t have done it without you.</p>
Wicket Scriptaculous 0.1.1 Release2007-01-01T00:00:00+00:00https://codecrate.com/2007/01/wicket-scriptaculous-011-release<p>I just published <a href="http://maven.codecrate.com/wicket-stuff/wicket-contrib-scriptaculous/0.1.1/wicket-contrib-scriptaculous-0.1.1.jar">an updated version of the Wicket/Scriptaculous Project</a>. This release is mainly a bugfix release, but there are a few notable changes.</p>
<h3 id="effects-api">Effects API</h3>
<p>This is the first release to offer a Java API to the scriptaculous Effects library. Here’s an example of how it works today:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">new</span> <span class="nc">Effect</span><span class="o">.</span><span class="na">Highlight</span><span class="o">(</span><span class="k">this</span><span class="o">).</span><span class="na">toJavascript</span><span class="o">();</span>
</code></pre></div></div>
<h3 id="ajaxeditinplacelabel-changes">AjaxEditInPlaceLabel Changes</h3>
<p>The AjaxEditInPlaceLabel now has a few more extension points for really customizing it’s functionality. Of particular interest is that you can now override what text is loaded for the user to edit. This allows for displaying different text than what is edited which can be useful if you want to customize formatting.</p>
<p>Man, I’ve really got to come up with some acronym or abbreviation for “The Wicket/Scriptaculous Project”. It’s too dang long to type all those characters. Maybe Wicktaculous? =)</p>
Wicket FeedPage2006-12-30T00:00:00+00:00https://codecrate.com/2006/12/wicket-feedpage<p>Merry Christmas and a Happy New Year to all you folks out there. Here’s a belated Christmas gift for all you Wicket developers out there.</p>
<p>I’ve been adding RSS feeds to my Wicket application based on the example <a href="http://cwiki.apache.org/WICKET/rss-page.html">Wicket RssPage found on the wiki</a>, and thought it was very restrictive in what it could do. There are a ton of Java libraries out there to build rss feeds, and this RssPage was yet another solution.</p>
<p>I wanted to leverage other libraries and avoid duplicating all of that markup in my own component, so I built a new FeedPage that uses the <a href="https://rome.dev.java.net/">Rome Java library</a> to take care of all the details. Now I can handle any format of RSS or Atom, along with several media extensions without changing any markup files.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">FeedPage</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">getMarkupType</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="s">"xml"</span><span class="o">;</span>
<span class="o">}</span>
<span class="nd">@Override</span>
<span class="kd">protected</span> <span class="kd">final</span> <span class="kt">void</span> <span class="nf">onRender</span><span class="o">(</span><span class="nc">MarkupStream</span> <span class="n">markupStream</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">PrintWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PrintWriter</span><span class="o">(</span><span class="n">getResponse</span><span class="o">().</span><span class="na">getOutputStream</span><span class="o">());</span>
<span class="nc">SyndFeedOutput</span> <span class="n">output</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndFeedOutput</span><span class="o">();</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">output</span><span class="o">.</span><span class="na">output</span><span class="o">(</span><span class="n">getFeed</span><span class="o">(),</span> <span class="n">writer</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">RuntimeException</span><span class="o">(</span><span class="s">"Error streaming feed."</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">FeedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">RuntimeException</span><span class="o">(</span><span class="s">"Error streaming feed."</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kd">abstract</span> <span class="nc">SyndFeed</span> <span class="nf">getFeed</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Wicket requires a markup file for each page, so you’ll need to create an empty FeedPage.xml file to go along with this page.</p>
<p>Now you can create your own page and get RSS or Atom feeds in Wicket! This is a quick example of how to do it, and you’ll probably want to take a look at the <a href="http://wiki.java.net/bin/view/Javawsxml/Rome05Tutorials">Rome tutorials for how to get more advanced stuff</a>.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ItemFeedPage</span> <span class="kd">extends</span> <span class="nc">FeedPage</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="nc">SyndFeed</span> <span class="nf">getFeed</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">SyndFeed</span> <span class="n">feed</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndFeedImpl</span><span class="o">();</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setFeedType</span><span class="o">(</span><span class="s">"rss_2.0"</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setTitle</span><span class="o">(</span><span class="s">"Sample Feed"</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setLink</span><span class="o">(</span><span class="s">"http://mysite.com"</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setDescription</span><span class="o">(</span><span class="s">"Sample Feed for how cool Wicket is"</span><span class="o">);</span>
<span class="nc">List</span> <span class="n">entries</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="nc">SyndEntry</span> <span class="n">entry</span><span class="o">;</span>
<span class="nc">SyndContent</span> <span class="n">description</span><span class="o">;</span>
<span class="n">entry</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndEntryImpl</span><span class="o">();</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setTitle</span><span class="o">(</span><span class="s">"Article One"</span><span class="o">);</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setLink</span><span class="o">(</span><span class="s">"http://mysite.com/article/one"</span><span class="o">);</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setPublishedDate</span><span class="o">(</span><span class="k">new</span> <span class="nc">Date</span><span class="o">());</span>
<span class="n">description</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SyndContentImpl</span><span class="o">();</span>
<span class="n">description</span><span class="o">.</span><span class="na">setType</span><span class="o">(</span><span class="s">"text/plain"</span><span class="o">);</span>
<span class="n">description</span><span class="o">.</span><span class="na">setValue</span><span class="o">(</span><span class="s">"Article descriping how cool wicket is."</span><span class="o">);</span>
<span class="n">entry</span><span class="o">.</span><span class="na">setDescription</span><span class="o">(</span><span class="n">description</span><span class="o">);</span>
<span class="n">entries</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">entry</span><span class="o">);</span>
<span class="n">feed</span><span class="o">.</span><span class="na">setEntries</span><span class="o">(</span><span class="n">entries</span><span class="o">);</span>
<span class="k">return</span> <span class="n">feed</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Enjoy your gift everyone! =)</p>
Wicket Sortable Container2006-12-15T00:00:00+00:00https://codecrate.com/2006/12/wicket-sortable-container<p>The Wicket <a href="http://wicket.sourceforge.net/apidocs/wicket/markup/html/list/ListView.html">ListView</a> is an excellent core component when you need to display a list of objects. It’s fairly simple to use and is fairly extensible when you need to customize it’s behavior.</p>
<p>The Java code for using a ListView is fairly simple. Note: This is using the most recent Wicket-2.0 snapshot API, which is slightly different from the Wicket 1.0 API.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">ListView</span><span class="o">(</span><span class="s">"rows"</span><span class="o">,</span> <span class="n">listData</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">populateItem</span><span class="o">(</span><span class="kd">final</span> <span class="nc">ListItem</span> <span class="n">item</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">MyObject</span> <span class="n">bean</span> <span class="o">=</span> <span class="o">(</span><span class="nc">MyObject</span><span class="o">)</span> <span class="n">item</span><span class="o">.</span><span class="na">getModelObject</span><span class="o">();</span>
<span class="k">new</span> <span class="nf">Label</span><span class="o">(</span><span class="n">item</span><span class="o">,</span> <span class="s">"label"</span><span class="o">,</span> <span class="n">bean</span><span class="o">.</span><span class="na">getLabel</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">});</span>
</code></pre></div></div>
<p>The HTML template to use the ListView is pretty straightforward too.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>ul<span class="ni">&gt;</span>
<span class="ni">&lt;</span>li wicket:id="items"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>span wicket:id="label"<span class="ni">&gt;</span>Something unique for this object<span class="ni">&lt;</span>/span<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/li<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/ul<span class="ni">&gt;</span>
</code></pre></div></div>
<p>This is all fine and dandy, but it’s pretty bare bones. Now, if you want to do some fancy Web 2.0ish drag/drop reordering of your items, check out the new SortableContainer Wicket extension that integrates the <a href="http://wiki.script.aculo.us/scriptaculous/show/Sortable.create">very sweet scriptaculous Sortable Javascript component</a> and does all the hard work for you.</p>
<p>The Java code is just slightly different from the ListView. You must pass in a wicketId for the list container (ul, ol, table, etc) as well as the wicketId for the individual list item (li, tr, etc).</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">new</span> <span class="nc">SortableContainer</span><span class="o">(</span><span class="k">this</span><span class="o">,</span> <span class="s">"itemList"</span><span class="o">,</span> <span class="s">"item"</span><span class="o">,</span> <span class="n">listData</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">populateItemInternal</span><span class="o">(</span><span class="kd">final</span> <span class="nc">ListItem</span> <span class="n">item</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">MyObject</span> <span class="n">bean</span> <span class="o">=</span> <span class="o">(</span><span class="nc">MyObject</span><span class="o">)</span> <span class="n">item</span><span class="o">.</span><span class="na">getModelObject</span><span class="o">();</span>
<span class="k">new</span> <span class="nf">Label</span><span class="o">(</span><span class="n">item</span><span class="o">,</span> <span class="s">"label"</span><span class="o">,</span> <span class="n">bean</span><span class="o">.</span><span class="na">getLabel</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">};</span>
</code></pre></div></div>
<p>The HTML template is nearly identical too. You just need to add a wicketId to the parent container.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>ul wicket:id="itemList"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>li wicket:id="item"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>span wicket:id="label"<span class="ni">&gt;</span>Something unique for this object<span class="ni">&lt;</span>/span<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/li<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/ul<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Simple enough for ya? I was extremely excited to see <a href="/2006/12/wicket-scriptaculous-snapshot-release.html">developers having success getting up and running with the latest snapshot release of these components</a>. I’d love to hear other success (or horror) stories from anyone out there that’s using these components!</p>
<p>As a side note, I’ve been reading some posts that the Wicket Repeater API is more robust than the ListView, but without knowing the details, I’ll stick with the ListView for now.</p>
Wicket Scriptaculous Snapshot Release2006-12-10T00:00:00+00:00https://codecrate.com/2006/12/wicket-scriptaculous-snapshot-release<p><a href="http://www.wicketframework.org">Wicket</a> and <a href="http://script.aculo.us/">Scriptaculous</a> are two fantastic libraries and they work extremely well together. Over the past several months, I’ve continued to integrate the scriptaculous Javascript library into Wicket with <strong>lots</strong> of success. Today, marks a significant milestone with the first availble public release! This may be a snapshot release, but it is ready for real world use.</p>
<p>I’ll be detailing a bunch of the recent changes over the next couple posts, but until then, <a href="http://maven.codecrate.com/wicket-stuff/wicket-contrib-scriptaculous/0.1.0-SNAPSHOT/wicket-contrib-scriptaculous-0.1.0-SNAPSHOT.jar">download it</a> and try it for yourself!</p>
Just Push It2006-12-01T00:00:00+00:00https://codecrate.com/2006/12/just-push-it<p>Holiday time has come again, and my time available for blogging has shrunk to almost none. This little post continues my series of simple development tips, and builds on a <a href="/2005/02/document-code-with-units-of-work.html">related post from a while back</a>.</p>
<p>There are times when I run across a procedural block of code and can not for the life of me figure out what’s going on. Most of my time is spent trying to understand what the code is really intended to do. For example, here’s a little chunk of code that has a bit of an identity crisis. What exactly is it trying to do? Why isn’t it more evident what it’s purpose is just by reading the code?</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">sendReminderEmails</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Collection</span> <span class="n">users</span> <span class="o">=</span> <span class="n">userDao</span><span class="o">.</span><span class="na">findUsers</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">iter</span> <span class="o">=</span> <span class="n">users</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">iter</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();</span> <span class="o">;)</span> <span class="o">{</span>
<span class="nc">User</span> <span class="n">user</span> <span class="o">=</span> <span class="o">(</span><span class="nc">User</span><span class="o">)</span> <span class="n">iter</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">user</span><span class="o">.</span><span class="na">isActive</span><span class="o">())</span> <span class="o">{</span>
<span class="n">user</span><span class="o">.</span><span class="na">sendReminderEmail</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This is a mighty simple example, but notice how cluttered the code is with logic unrelated to it’s core purpose? Now, there are a number of ways to improve this code, and **Pushing Logic **is a simple step towards improvement.</p>
<p>Pushing logic is a simple refactoring trick that helps make code more maintainable and understandable. The idea is that if some piece of code isn’t relevant to your current action, it should be pushed Somewhere Else. That magical Somewhere Else can be another class, or a private method of the existing class. The important thing is to get that code out of the way.</p>
<p>From my previous example, a simple change I could make is to try and remove the check for if the user is active. It’s a small thing, but it would be nice to assume all the users are active right? So, I’ll Push that logic into a new method on the UserDao and rely on it to do the correct logic.</p>
<p>Now, my service is a bit cleaner and removes that extra branching logic.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">sendReminderEmails</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Collection</span> <span class="n">users</span> <span class="o">=</span> <span class="n">userDao</span><span class="o">.</span><span class="na">findActiveUsers</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">iter</span> <span class="o">=</span> <span class="n">users</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">iter</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();</span> <span class="o">;)</span> <span class="o">{</span>
<span class="nc">User</span> <span class="n">user</span> <span class="o">=</span> <span class="o">(</span><span class="nc">User</span><span class="o">)</span> <span class="n">iter</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="n">user</span><span class="o">.</span><span class="na">sendReminderEmail</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The beauty of this refactoring tip is that it can be applied to any layer of an application. If your business layer begins pushing logic into the dao layer and that code begins to be bloated, you should push that logic out of the dao layer and into a new abstraction to keep that code concise.</p>
Don't Talk To Your Neighbor's Neighbor2006-10-31T00:00:00+00:00https://codecrate.com/2006/10/don-talk-to-your-neighbor-neighbor<p>I’ll be continuing on the pattern/antipattern postings today, even though it seems that the large majority of people really missed the point of my <a href="/2006/10/mutating-methods.html">previous entry</a>. I’ll try harder to keep things simple, and avoid talking about the much loved static util (anti) pattern.</p>
<p><strong>Don’t Talk to your Neighbor’s Neighbor</strong> is an antipattern that is best demonstrated using an example. I’ll use the example of a PetClinic charging an Owner after working with their Pet.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">PetClinic</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">charge</span><span class="o">(</span><span class="nc">Pet</span> <span class="n">pet</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Owner</span> <span class="n">owner</span> <span class="o">=</span> <span class="n">pet</span><span class="o">.</span><span class="na">getOwner</span><span class="o">();</span>
<span class="n">owner</span><span class="o">.</span><span class="na">sendInvoice</span><span class="o">(</span><span class="s">"100 USD"</span><span class="o">);</span>
<span class="c1">//perform other "clinic" paperwork</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Notice how the charge method takes the Pet as a parameter, except it is only used to navigate it’s object graph to another object? The charge method is using an initial object (aka: next door neighbor) just to talk to another object (aka: neighbor down the street). This example is very simplistic, and although it seems very obvious, this antipattern can be found everywhere.</p>
<p>How do you avoid this antipattern? Simple. If the only reason you’re using a object is to extract data from it, you should depend only on the referenced data and avoid coupling to the initial object. Now, our PetClinic looks like this:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">PetClinic</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">charge</span><span class="o">(</span><span class="nc">Owner</span> <span class="n">owner</span><span class="o">)</span> <span class="o">{</span>
<span class="n">owner</span><span class="o">.</span><span class="na">sendInvoice</span><span class="o">(</span><span class="s">"100 USD"</span><span class="o">);</span>
<span class="c1">//perform other "clinic" paperwork</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Sure, this an ultra simplified example, but notice how the PetClinic is no longer coupled to the Pet class. Less coupling is a good thing!</p>
<p>I’m sure someone will have some comments on the DataObject pattern to refute this one. Since DataObjects are essentially bags of data with no behavior, I’d argue that the DataObject pattern is also an antipattern (although sometimes necessary).</p>
Mutating Methods2006-10-25T00:00:00+00:00https://codecrate.com/2006/10/mutating-methods<p>Today marks the start of a new series of blog entries that identify common patterns (and antipatterns) that can be applied to everyday programming. It’s nothing ground breaking, and is simlar to other sites like <a href="http://www.martinfowler.com/bliki/">Martin Fowler’s blog</a>. First up, Mutating Methods.</p>
<p>A Mutating Method is a method that takes a parameter as input and modifies that object directly instead of returning a value. This is definitely an antipattern, and one of my pet peeves. A perfect example of this is Collections.sort(List). There’s no return value for this method. It just rewrites your list however it sees fit and there’s nothing you can do about it.</p>
<p>Why is this such an issue? Because it completely breaks the assumptions of how methods work. These expectations go all the way back to the assembly days. Procedural logic revolves around the concept of inputs and outputs. By it’s very nature, an input parameter is expected to be just that; an input.</p>
<p>It’s the same as working with a math equation. When I see 2 + 3 = 5, my brain interprets this as a series of inputs and outputs. 2 and 3 are inputs and the output is 5. This just makes sense. Now, if we applied Mutating Methods to mathematics, we’d have something like: <del>2 + 3</del> 5</p>
<p>Nice…</p>
The Poor Man's Apple2006-10-23T00:00:00+00:00https://codecrate.com/2006/10/poor-man-apple<p>I’ve been a hardcore Linux user for the past couple years, and I commonly refer to Linux as The Poor Man’s Apple. I use Linux because I truly believe that I’m more productive using Linux than Windows, and I’m too cheap to buy an Apple. Seriously, I would love to have a spiffy new Apple laptop, but I just can’t justify paying the extra markup cost.</p>
<p><a href="http://opensuse.org">SuSE Linux</a> has been my distribution of choice for quite some time, but this week I decided to try out the highly recommended <a href="http://www.ubuntu.com/">Ubuntu distribution</a>. I can honestly say that this was the easiest installation I’ve ever done. It literally took me 5 minutes to boot up and try out their live CD, and after a couple clicks and about 15 minutes of file copying, I was up and running. The Ubuntu install went far beyond my expectations, and there were a few specific features that really blew me away.</p>
<p>Apple is known for packing a lot of “nifty” features into there operating system for a great out of the box experience, while Linux support for non-free applications is pretty poor. I’ve grown to deal with installing “bare bones” Linux, and then tweaking it to get basic MP3 and DVD support. Not any more! After installing Ubuntu, I installed <a href="http://easyubuntu.freecontrib.org/">Easy Ubuntu</a>, and was able to get all these extensions installed in a snap! It even installed the Java 5 JRE for me!</p>
<p>The other feature that I found especially impressive was how Ubuntu automatically created mapped drives for my commonly used connections. I frequently need to connect to my server to transfer files, or my public ftp server to update webpages. Ubuntu will walk you through this connection process and then create a handy desktop icon to reconnect to your network location. Very nice!</p>
<p>Having a flashy new Apple would be nice, but I don’t feel the need nearly as much now. As Ubuntu keeps getting better, I’m quite happy to keep recieving all of these updates for free!</p>
Oh JSP, How I Hate Thee2006-10-18T00:00:00+00:00https://codecrate.com/2006/10/oh-jsp-how-i-hate-thee<p>The title says it all. It’s poetry, and I’m the <strong>code_poet</strong> right?</p>
<p>I’m currently working on a project to migrate our web application to tomcat. Our current appserver is a pile of dung and this upgrade has been a long time coming. I was not expecting this to be easy given how large our application is, but I wasn’t expecting us to have to change nearly every single JSP in our application. That’s right, tomcat can’t compile over two thirds of our JSP’s, and it’s largely because of one issue. Here’s an very simple example of our current JSP’s that tomcat can’t handle.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>bean:define id="targetUser" value="Ryan"/<span class="ni">&gt;</span>
<span class="ni">&lt;</span>logic:equal name="currentUserName" value="<span class="ni">&lt;</span>%= targetUser %<span class="ni">&gt;</span>"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>!-- do something special --<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/logic:equal<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Looks pretty standard right? Why in the world could our current crappy app server handle this, and the industry standard, servlet specification reference implementation, appserver not? It all comes down to differences in how the JSP is transalted to Java bewteen the two appservers.</p>
<p>The bean:define tag creates an instance of an Object. The logic:equal tag requires a String for the value attribute. Now, our crappy appserver is smart enough to try and cast the object from an Object to a String, but tomcat refuses to try and help a brother out in this simple little way. Tomcat requires you to perform the cast yourself like this:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>logic:equal name="currentUserName" value="<span class="ni">&lt;</span>%= (String)targetUser %<span class="ni">&gt;</span>"<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Oh JSP, How I Hate Thee.</p>
<p>Yes, this is more of a Jasper issue than Tomcat, but I refuse to accept that the industry standard servlet container can’t handle this. At the very least, it should be mandated by the Servlet specification so that each appserver handles this the same way.</p>
Rename JUnit Tests When Refactoring2006-10-17T00:00:00+00:00https://codecrate.com/2006/10/rename-junit-tests-when-refactoring<p>Modern IDE’s have been putting a lot of effort into improving their tools to support code refactoring. Eclipse is still the champ in my opinion, but <a href="http://refactoring.netbeans.org/">NetBeans seems to be making headway as well</a>. One refactoring feature I have yet to see implemented that would make my life a little easier would be automatically rename JUnit test classes when the class being tested is renamed.</p>
<p>Since there is no real metadata available to map a particular JUnit test to the class being tested, this feature would rely mainly on naming conventions, but I’m willing to bet that this would still work 90% of the time. If someone has a class named Dog, the unit test will nearly always be DogTest. You could also infer this by checking all classes that extend from TestCase that reference the renamed class. Again, this may not be perfect, but it’s far from impossible.</p>
<p>I’ve requested <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=136880">this feature for Eclipse</a>, but they’ve refused to add it (which is their right). So, if anyone is interested in this feature, please make your voice heard by voting for this issue. If that doesn’t drum up enough support, it may be necessary to extend and replace the current refactoring plugin with a custom one. Anyone out there an Eclipse plugin expert? :)</p>
Wizard Validation2006-10-09T00:00:00+00:00https://codecrate.com/2006/10/wizard-validation<p>How should validation frameworks integrate with “wizards”? It may take a bit of magic to get these concepts to work together, but I am talking about <a href="http://en.wikipedia.org/wiki/Wizard_(software)">software wizards to help users get through a complex workflow</a>, and not <a href="http://en.wikipedia.org/wiki/Wizard_(fantasy)">magical sorcerers from fantasy land</a>.</p>
<p>Here’s my issue (in a broad sense):</p>
<ol>
<li>
<p>I want to build a wizard to walk me through a complex operation (ex: MyOperation).</p>
</li>
<li>
<p>My wizard has registered a number of validators (ex: NameNotNullValidator).</p>
</li>
<li>
<p>My wizard doesn’t display a validated piece of data until a later step. (ex: can’t enter the nameuntil step 2).</p>
</li>
<li>
<p>How does the wizard support “delayed” validation until the user has access to the validated field?</p>
</li>
</ol>
<p>I’ve done a lot of work over the past several monthes with Spring RCP, and it seems as if <a href="http://opensource.atlassian.com/projects/spring/browse/RCP-406">this usecase has never been addressed</a>. I’ve also searched through every framework I could lay my hands on, and none seem to support this scenerio.</p>
<p>This usecase seems so basic, so am I totally missing something? Have I gone crazy, or has the rest of the world turned it’s back on Wizard Frameworks?</p>
More Javascript Helpers2006-10-06T00:00:00+00:00https://codecrate.com/2006/10/more-javascript-helpers<p>With all of the Javascript needed to work with AJAX, it gets messy pretty quickly when you’re building Javascript programatically within Java. Especially when you need to pass optional parameters as a Javascript hash to a library. If Java had something like <a href="http://nubyonrails.com/articles/2006/02/01/rjs-and-content-type-header">Ruby’s RJS</a>, that would get rid of this mess. Until that comes around, I’ve enhanced my <a href="/2006/10/javascriptbuilder.html">JavascriptBuilder</a> to make my life a little easier with dealing with more complex Javascript API’s.</p>
<p>Need to pass a hash of options to a Javascript method? Now, you can just create a Java map of options (Boolean, String, or JavascriptFunction references), and it’ll automatically be formatted into the correct javascript syntax! Here’s an example…</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Map</span> <span class="n">dropOptions</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">()</span> <span class="o">{</span> <span class="o">{</span>
<span class="n">put</span><span class="o">(</span><span class="s">"accept"</span><span class="o">,</span> <span class="n">draggableClass</span><span class="o">);</span>
<span class="n">put</span><span class="o">(</span><span class="s">"onDrop"</span><span class="o">,</span> <span class="k">new</span> <span class="nc">JavascriptFunction</span><span class="o">(</span><span class="s">"function(element) {new Ajax.Updater('"</span> <span class="o">+</span> <span class="n">getId</span><span class="o">()</span> <span class="o">+</span> <span class="s">"', '"</span><span class="o">+</span> <span class="n">url</span><span class="o">+</span> <span class="s">"')}"</span><span class="o">));</span>
<span class="n">put</span><span class="o">(</span><span class="s">"hoverclass"</span><span class="o">,</span> <span class="n">getId</span><span class="o">()</span> <span class="o">+</span> <span class="s">"-active"</span><span class="o">);</span>
<span class="n">put</span><span class="o">(</span><span class="s">"revert"</span><span class="o">,</span> <span class="nc">Boolean</span><span class="o">.</span><span class="na">TRUE</span><span class="o">);</span>
<span class="o">}</span> <span class="o">};</span>
<span class="nc">JavascriptBuilder</span> <span class="n">builder</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">JavascriptBuilder</span><span class="o">();</span>
<span class="n">builder</span><span class="o">.</span><span class="na">addLine</span><span class="o">(</span><span class="s">"Droppables.add('"</span> <span class="o">+</span> <span class="n">getId</span><span class="o">()</span> <span class="o">+</span> <span class="s">"', "</span><span class="o">);</span>
<span class="n">builder</span><span class="o">.</span><span class="na">addOptions</span><span class="o">(</span><span class="n">dropOptions</span><span class="o">);</span>
<span class="n">builder</span><span class="o">.</span><span class="na">addLine</span><span class="o">(</span><span class="s">");"</span><span class="o">);</span>
<span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">builder</span><span class="o">.</span><span class="na">buildScriptTag</span><span class="o">());</span>
</code></pre></div></div>
<p>Notice the <a href="/2006/06/ruby-syntax-for-java-maps.html">abbreviated syntax for working with simple maps</a>? =)</p>
Wicket AjaxEditInPlaceLabel2006-10-03T00:00:00+00:00https://codecrate.com/2006/10/wicket-ajaxeditinplacelabel<p>I think it’s time to put back on my Wicket hat, and start kicking ass again. It’s been a while since I’ve worked with Wicket, and I’ve picked it back up for a new project I’m working on. It’s an AJAX heavy application, and that’s where Wicket (and scriptaculous) really shine.</p>
<p>My first AJAX Wicket component that I need is an Edit In Place Label. You’ll find examples of this component all over the web. <a href="http://www.flickr.com">Flickr</a> uses this type of component heavily, and you can browse through the <a href="http://script.aculo.us/">scriptaculous</a> examples for others.</p>
<p>I want the client code to be nearly identical to creating a normal textfield. No special interfaces or extra hoops to jump through. The value from the AJAX call should be saved on the object, just the same as for a textfield.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nf">EditPresentationPanel</span><span class="o">(</span><span class="nc">String</span> <span class="n">wicketId</span><span class="o">,</span> <span class="nc">MyObject</span> <span class="n">myObject</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">wicketId</span><span class="o">);</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">AjaxEditInPlaceLabel</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="k">new</span> <span class="nc">PropertyModel</span><span class="o">(</span><span class="n">myObject</span><span class="o">,</span> <span class="s">"name"</span><span class="o">)));</span>
<span class="o">}</span>
</code></pre></div></div>
<p>So, without further delay, here’s the code! I’ll be checking this into the wicket-stuff project as soon as I cleanup a bit of the other code in that project. It’s still using scriptaculous version 1.5!</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">AjaxEditInPlaceLabel</span> <span class="kd">extends</span> <span class="nc">AbstractTextComponent</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">AbstractAjaxBehavior</span> <span class="n">handler</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">AjaxEditInPlaceLabel</span><span class="o">(</span><span class="nc">String</span> <span class="n">wicketId</span><span class="o">,</span> <span class="nc">IModel</span> <span class="n">model</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">wicketId</span><span class="o">);</span>
<span class="n">setModel</span><span class="o">(</span><span class="n">model</span><span class="o">);</span>
<span class="k">this</span><span class="o">.</span><span class="na">handler</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">AbstractAjaxBehavior</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="nc">String</span> <span class="nf">getImplementationId</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="s">"scriptaculous"</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onRenderHeadInitContribution</span><span class="o">(</span><span class="nc">Response</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
<span class="n">writeJsReference</span><span class="o">(</span><span class="n">response</span><span class="o">,</span> <span class="k">new</span> <span class="nc">PackageResourceReference</span><span class="o">(</span><span class="nc">AjaxEditInPlaceLabel</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"prototype.js"</span><span class="o">));</span>
<span class="n">writeJsReference</span><span class="o">(</span><span class="n">response</span><span class="o">,</span> <span class="k">new</span> <span class="nc">PackageResourceReference</span><span class="o">(</span><span class="nc">AjaxEditInPlaceLabel</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"scriptaculous.js"</span><span class="o">));</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onRequest</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">FormComponent</span> <span class="n">formComponent</span> <span class="o">=</span> <span class="o">(</span><span class="nc">FormComponent</span><span class="o">)</span> <span class="n">getComponent</span><span class="o">();</span>
<span class="n">formComponent</span><span class="o">.</span><span class="na">validate</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">formComponent</span><span class="o">.</span><span class="na">isValid</span><span class="o">())</span> <span class="o">{</span>
<span class="n">formComponent</span><span class="o">.</span><span class="na">updateModel</span><span class="o">();</span>
<span class="o">}</span>
<span class="nc">String</span> <span class="n">value</span> <span class="o">=</span> <span class="n">formComponent</span><span class="o">.</span><span class="na">getValue</span><span class="o">();</span>
<span class="nc">RequestCycle</span><span class="o">.</span><span class="na">get</span><span class="o">().</span><span class="na">setRequestTarget</span><span class="o">(</span><span class="k">new</span> <span class="nc">StringRequestTarget</span><span class="o">(</span><span class="n">value</span><span class="o">));</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="n">add</span><span class="o">(</span><span class="n">handler</span><span class="o">);</span>
<span class="n">setOutputMarkupId</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">getInputName</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="s">"value"</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kd">final</span> <span class="kt">void</span> <span class="nf">onComponentTagBody</span><span class="o">(</span><span class="kd">final</span> <span class="nc">MarkupStream</span> <span class="n">markupStream</span><span class="o">,</span> <span class="kd">final</span> <span class="nc">ComponentTag</span> <span class="n">openTag</span><span class="o">)</span> <span class="o">{</span>
<span class="n">replaceComponentTagBody</span><span class="o">(</span><span class="n">markupStream</span><span class="o">,</span> <span class="n">openTag</span><span class="o">,</span> <span class="n">getValue</span><span class="o">());</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onRender</span><span class="o">(</span><span class="nc">MarkupStream</span> <span class="n">markupStream</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">.</span><span class="na">onRender</span><span class="o">(</span><span class="n">markupStream</span><span class="o">);</span>
<span class="nc">JavascriptBuilder</span> <span class="n">builder</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">JavascriptBuilder</span><span class="o">();</span>
<span class="n">builder</span><span class="o">.</span><span class="na">addLine</span><span class="o">(</span><span class="s">"new Ajax.InPlaceEditor('"</span> <span class="o">+</span> <span class="n">getMarkupId</span><span class="o">()</span> <span class="o">+</span> <span class="s">"', "</span><span class="o">);</span>
<span class="n">builder</span><span class="o">.</span><span class="na">addLine</span><span class="o">(</span><span class="s">" '"</span> <span class="o">+</span> <span class="n">handler</span><span class="o">.</span><span class="na">getCallbackUrl</span><span class="o">()</span> <span class="o">+</span> <span class="s">"', "</span><span class="o">);</span>
<span class="n">builder</span><span class="o">.</span><span class="na">addLine</span><span class="o">(</span><span class="s">" {});"</span><span class="o">);</span>
<span class="n">getResponse</span><span class="o">().</span><span class="na">write</span><span class="o">(</span><span class="n">builder</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>There are a couple things I really like about this implementation. This component gets form validation “for free”, which makes it very easy to reuse other Wicket validators for this component.</p>
<p>Creating this component took me longer than I was hoping, but that’s largly because I’m a bit rusty with Wicket. It was a bit difficult to follow other Wicket AJAX examples out there because my app is built for Wicket-1.2 and most of the example code has been written for Wicket-2.0.</p>
JavascriptBuilder2006-10-03T00:00:00+00:00https://codecrate.com/2006/10/javascriptbuilder<p>I’m jumping back into web development after my recent stint building rich client apps. This is a helper object I’ve been using to programmatically build Javascript on the server side. Nothing too special, but it makes the code quite a bit cleaner than using a standard StringBuffer. Very similar to the <a href="/2006/05/simple-css-builder.html">CssBuilder</a> I wrote a while back.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">JavascriptBuilder</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">StringBuffer</span> <span class="n">buffer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringBuffer</span><span class="o">();</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">addLine</span><span class="o">(</span><span class="nc">String</span> <span class="n">line</span><span class="o">)</span> <span class="o">{</span>
<span class="n">buffer</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">line</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="s">"\n"</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">buildScriptTag</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="s">"\n\n"</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
RegEx Helper2006-09-29T00:00:00+00:00https://codecrate.com/2006/09/regex-helper<p>I’ve always had difficulty with regular expressions. It’s one area of programming that has always confused me.</p>
<p>I’ve been working to improve shard’s support for complex dice expressions (ex: 1d8 + 2d6) and regular expressions have been the only way for me to get things to work. I took a stab at adding this feature a while back, but had to roll back the changes because it broke backwards compatability. It was just too hard to test. Sure, I’ve got pretty extensive unit tests, but there was no good way for me to test, in real-time, how my regular expression would perform against a given input.</p>
<p>Yesterday I tried out a pretty sweet eclipse plugin to provide real-time feedback for regular expressions, <a href="http://www.bastian-bergerhoff.com/eclipse/features/web/QuickREx/toc.html">QuickREx</a>. The plugin was great at providing real-time feedback for how my regular expression would perform against any number of test strings.</p>
<p>In less than an hour, I was able to finally put to rest <a href="http://wiki.codecrate.com/display/SHA/2006/09/28/1d6+Plus+2d8+%3D+FUN">the longest outstanding feature request for shard</a>! Thank you QuickREx developers!</p>
Burn the Feed2006-09-29T00:00:00+00:00https://codecrate.com/2006/09/burn-feed<p>With my recent annoyances with the JRoller hosting, I’ve decided that it would be best to try and remove any unnecessary dependency on their lackluster product. So, I’ve turned to <a href="http://www.feedburner.com">feedburner </a>to provide RSS subscriptions of this blog. This will allow me to migrate off of JRoller and to another host without worrying about anyone missing posts.</p>
<p>So, if there’s anyone out there that actually reads this blog, please update your RSS feeds to be this new url: <a href="http://feeds.feedburner.com/code_poet">http://feeds.feedburner.com/code_poet</a></p>
<p>I’ve also updated the RSS autodetection link on the website, so anyone using built in RSS detection in the future should automatically pick up the new feed. I would love to have automatically done the redirection for any existing readers, but since JRoller servers are “locked down”, that won’t be happening anytime soon.</p>
<p>Sorry for the inconvenience, and thanks for your interest in this blog!</p>
Spring Rich Client Browser Launcher2006-09-15T00:00:00+00:00https://codecrate.com/2006/09/spring-rich-client-browser-launcher<p>I’ve been debating the best avenue for client apps to present help information to users. The client applications I’ve written for <a href="http://shard.codecrate.com">shard</a> are built on <a href="http://spring-rich-c.sf.net">Spring Rich Client</a>, which has built in support for <a href="http://java.sun.com/products/javahelp/">JHelp</a> resources. Now, maybe I’m missing something, but working with JHelp has been anything but helpful. That’s why I’ve decided to take a new direction to leverage the <a href="http://wiki.codecrate.com/display/SHA/User+Guide">shard project wiki for user help documentation</a>. This feels like a perfect use of a wiki, and users never have to worry about “out of date” documentation.</p>
<p>I’ve rolled my own browser launcher for previous projects, but this time, I’m using the opensource <a href="http://www.centerkey.com/java/browser/">BareBonesBrowserLauncher</a>. It’s a lightweight version (~50 LOC) of the more robust <a href="http://browserlaunch2.sourceforge.net/">BrowserLauncher2</a> library and it’s worth a shot until my requirements get more complex.</p>
<p>Here’s a snapshot of the code, and the complete source can be found as part of the shard project.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">BrowserLauncherCommand</span> <span class="kd">extends</span> <span class="nc">ApplicationWindowAwareCommand</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="n">url</span><span class="o">;</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">doExecuteCommand</span><span class="o">()</span> <span class="o">{</span>
<span class="k">new</span> <span class="nf">BareBonesBrowserLauncher</span><span class="o">().</span><span class="na">openURL</span><span class="o">(</span><span class="n">url</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">getUrl</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">url</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">setUrl</span><span class="o">(</span><span class="nc">String</span> <span class="n">url</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">url</span> <span class="o">=</span> <span class="n">url</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The Spring configuration is just a drop in replacement for the default HelpContentsCommand</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>bean id="helpContentsCommand"
class="com.codecrate.shard.ui.command.BrowserLauncherCommand"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>property name="url"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>value<span class="ni">&gt;</span>http://wiki.codecrate.com/display/SHA/User+Guide<span class="ni">&lt;</span>/value<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/property<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
</code></pre></div></div>
<p>This is another component could be useful to other spring-rich applications. Anyone interested in integrating this into the core? There are no external dependencies, so there shouldn’t be too much fuss over allowing it in.</p>
Spring SpecificApplicationEventListener2006-08-09T00:00:00+00:00https://codecrate.com/2006/08/spring-specificapplicationeventlistener<p>I often hear complaints from users of the <a href="http://www.springframework.org/docs/reference/beans.html#context-functionality-events">springframework event listener API</a>. It seems that the vast majority of user’s end up littering their code with <strong>instanceof</strong> checks to only perform work for specific events. Something like this:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObject</span> <span class="kd">implements</span> <span class="nc">ApplicationListener</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onApplicationEvent</span><span class="o">(</span><span class="nc">ApplicationEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">event</span> <span class="k">instanceof</span> <span class="nc">MyEvent</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//do stuff</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Well, here’s a simple little solution that should take all that pain away.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">AbstractSpecificApplicationEventListener</span> <span class="kd">implements</span> <span class="nc">ApplicationListener</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Class</span> <span class="n">targetClass</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">AbstractSpecificApplicationEventListener</span><span class="o">(</span><span class="nc">Class</span> <span class="n">targetClass</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">targetClass</span> <span class="o">=</span> <span class="n">targetClass</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kd">abstract</span> <span class="kt">void</span> <span class="nf">onSpecificApplicationEvent</span><span class="o">(</span><span class="nc">ApplicationEvent</span> <span class="n">event</span><span class="o">);</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onApplicationEvent</span><span class="o">(</span><span class="nc">ApplicationEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">event</span><span class="o">.</span><span class="na">getClass</span><span class="o">().</span><span class="na">isAssignableFrom</span><span class="o">(</span><span class="n">targetClass</span><span class="o">))</span> <span class="o">{</span>
<span class="n">onSpecificApplicationEvent</span><span class="o">(</span><span class="n">event</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>All you need to do now is extend this class, and implement the method you want to do the work. Quite a bit cleaner!</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObject</span> <span class="kd">extends</span> <span class="nc">AbstractSpecificApplicationEventListener</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">MyObject</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="nc">MyEvent</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onSpecificApplicationEvent</span><span class="o">(</span><span class="nc">ApplicationEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//do stuff</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
FinderTemplate2006-08-07T00:00:00+00:00https://codecrate.com/2006/08/findertemplate<p>I think I’m becoming addicted to Ruby syntax. The Ruby collection API is super slick, and since I’ve already brought <a href="http://jroller.com/page/wireframe?entry=humane_object_iteration">a Ruby-like iteration syntax to Java</a>, I think it’s logical to try and port <a href="http://www.rubycentral.com/ref/ref_m_enumerable.html#find">the Ruby find syntax</a> to Java as well.</p>
<p>My goal is to create a simple client API for looping through a collection, looking for a certain object. Here’s how I want it to work.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">MyObject</span> <span class="n">foundObject</span> <span class="o">=</span> <span class="o">(</span><span class="nc">MyObject</span><span class="o">)</span> <span class="k">new</span> <span class="nc">FinderTemplate</span><span class="o">(</span><span class="n">entries</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="kt">boolean</span> <span class="nf">isMatch</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">MyObject</span> <span class="n">entry</span> <span class="o">=</span> <span class="o">(</span><span class="nc">MyObject</span><span class="o">)</span> <span class="n">object</span><span class="o">;</span>
<span class="c1">//perform any required matching logic</span>
<span class="k">return</span> <span class="kc">true</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}.</span><span class="na">find</span><span class="o">();</span>
</code></pre></div></div>
<p>The code for the FinderTemplate is very similar to my previous IteratorTemplate. Nothing too fancy, but it’s pretty slick.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">FinderTemplate</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Collection</span> <span class="n">objects</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">FinderTemplate</span><span class="o">(</span><span class="nc">Collection</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">objects</span> <span class="o">=</span> <span class="n">objects</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">Object</span> <span class="nf">find</span><span class="o">()</span> <span class="o">{</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">iter</span> <span class="o">=</span> <span class="n">objects</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">iter</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();)</span> <span class="o">{</span>
<span class="nc">Object</span> <span class="n">element</span> <span class="o">=</span> <span class="o">(</span><span class="nc">Object</span><span class="o">)</span> <span class="n">iter</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">isMatch</span><span class="o">(</span><span class="n">element</span><span class="o">))</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">element</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kd">abstract</span> <span class="kt">boolean</span> <span class="nf">isMatch</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>What I think is very cool is how this FinderTemplate can be extended ever so slightly to add a findAll method. So, instead of just finding <em>one_object, you can find _all</em> objects that meet your criteria.</p>
<p>Here’s the only change needed to the FinderTemplate to add this new behaviour.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nc">Collection</span> <span class="nf">findAll</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Collection</span> <span class="n">results</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">iter</span> <span class="o">=</span> <span class="n">objects</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">iter</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();)</span> <span class="o">{</span>
<span class="nc">Object</span> <span class="n">element</span> <span class="o">=</span> <span class="o">(</span><span class="nc">Object</span><span class="o">)</span> <span class="n">iter</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">isMatch</span><span class="o">(</span><span class="n">element</span><span class="o">))</span> <span class="o">{</span>
<span class="n">results</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">element</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">results</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I think it would be great if this code could find a home somewhere like <a href="http://jakarta.apache.org/commons/collections/">commons-collections</a>. I’m not sure if there’s much interest for this code though, unless you’ve been exposed to Ruby.</p>
How Prototype Can Break Your Site2006-07-28T00:00:00+00:00https://codecrate.com/2006/07/how-prototype-can-break-your-site<p>I have really grown to like <a href="http://prototype.conio.net/">prototype</a> and all of the extensions it brings to Javascript. The more I use it, the harder it is for me to use standard Javascript for certain operations (ajax, looping, etc).</p>
<p>Unfortunately, my day job project does not use prototype, and there’s been quite a bit of resistance to adopting it. The main argument against using prototype in our application is that it will break a small number of legacy Javascript.</p>
<p>What? Prototype can <strong>break</strong> existing scripts? That’s right, and although it’s only one use case in a small number of scripts, now everyone has become gun shy around adopting prototype. I’ll try to describe the problem. First, here is a simple example that will demonstrate the issue.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">a</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Array</span><span class="p">();</span>
<span class="nx">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
<span class="nx">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="k">in</span> <span class="nx">a</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">i</span> <span class="o">+</span> <span class="dl">"</span><span class="s2"> = </span><span class="dl">"</span><span class="o">+</span> <span class="nx">a</span><span class="p">[</span><span class="nx">i</span><span class="p">]);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Now, before prototype is added to the page, this Javascript will have the following output:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0 = 1
1 = 2
</code></pre></div></div>
<p>After prototype is added to the page, the for loop acts differently and also iterates over the methods that Prototype has added to the Array object. Now, the output looks like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0 = 1
1 = 2
each = function() { }
iterate = function() { }
</code></pre></div></div>
<p>There are two sides of the camp when it comes to this problem, and both sides are <strong>very</strong> passionate that they are right and the other is wrong. One side blames prototype for modifying core Javascript objects. I have a feeling that this group would not appreciate Ruby’s ability to dynamically add methods to any object. The other side blames Javascript developers for using a dangerous version of the for loop. From what I’ve read, using <a href="http://www.andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/">this style of for loop for iterating over associative arrays works, but it’s not correct</a>.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//this style of for loop is really intended for iterating over a hash</span>
<span class="c1">//or for working with an object as a hash of properties</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">property</span> <span class="k">in</span> <span class="nx">object</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">print</span><span class="p">(</span><span class="nx">property</span> <span class="o">+</span> <span class="dl">"</span><span class="s2"> = </span><span class="dl">"</span><span class="o">+</span> <span class="nx">object</span><span class="p">[</span><span class="nx">property</span><span class="p">]);</span>
<span class="p">}</span>
<span class="c1">//this is the correct way to iterate over an array.</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="nx">print</span><span class="p">(</span><span class="nx">x</span> <span class="o">+</span> <span class="dl">"</span><span class="s2"> = </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">array</span><span class="p">[</span><span class="nx">x</span><span class="p">]);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>So, there are definitely options for getting around these issues. One is to update existing Javascript to use correct array iteration. Heck, since you’re integrating prototype, might as use their <a href="/2006/07/humane-object-iteration.html">kick ass object iteration syntax</a>! If updating your current scripts isn’t an option, there are <a href="http://ajaxian.com/archives/prototypify-running-prototype-code-with-legacy-code">wrapper scripts that will allow developers to control which Javascript functions get the special prototype syntax</a>. This would allow you to add prototype without breaking existing scripts.</p>
<p>Realistically, this is only an issue if you’re trying to bring prototype into a legacy project. If you’re starting a new project, do <strong>not</strong> hesitate to use prototype. It’s simply a no brainer.</p>
No Save For You!2006-07-20T00:00:00+00:00https://codecrate.com/2006/07/no-save-for-you<p>I love how naive some software developers are. For some reason people just don’t realize that littering your view layer with business logic is a bad idea. Here’s an example. I just stumbled across a web application that has the amazing security feature to prevent user’s from submitting a page if they don’t have permission. Now, how do you suppose they implemented that?</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>!-- only display save button if user has permission --<span class="ni">&gt;</span>
<span class="ni">&lt;</span>c:if test="${userHasPermission}"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>input type="submit" name="submit" value="submit" /<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/c:if<span class="ni">&gt;</span>
</code></pre></div></div>
<p>There’s nothing inherintly wrong with this solution, except for the fact that this is the <strong>only</strong> place security is enforced in the application.</p>
<p>Thank God for tools like <a href="http://greasemonkey.mozdev.org/">greasemonkey</a> and <a href="https://addons.mozilla.org/firefox/1843/">firebug </a>that allow you to execute scripts against the available DOM. Something like this works like a champ to get around that <em>pesky</em> security.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">document</span><span class="p">.</span><span class="nx">forms</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="nx">submit</span><span class="p">();</span>
</code></pre></div></div>
Is It REALLY Empty?2006-07-19T00:00:00+00:00https://codecrate.com/2006/07/is-it-really-empty<p>JSP is so damn ghetto.</p>
<p>Who would have thought that JSP is so incredibly incompetent that it can screw up one of the easiest operations? All I want to do is determine whether or not a collection is empty. Simple right? Well, obviously this is something too complex to be addressed by JSP.</p>
<p>So, here’s my super simple usecase that <strong>actually</strong> works. The JSP is pretty straight forward.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>c:if test="${not empty myObject.entries}"<span class="ni">&gt;</span>
The Collection is Not Empty! The world is coming to an end!
<span class="ni">&lt;</span>/c:if<span class="ni">&gt;</span>
</code></pre></div></div>
<p>And there’s nothing special about my object.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObject</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">Collection</span> <span class="n">entries</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="kd">public</span> <span class="nc">Collection</span> <span class="nf">getEntries</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">entries</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, guess what happens when I want my entries to ensure only one entry is added. You’d expect to change the colleciton from an ArrayList to a HashSet, and you’d be good to go right? Well, you’d be dead wrong.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObject</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">Collection</span> <span class="n">entries</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashSet</span><span class="o">();</span>
<span class="kd">public</span> <span class="nc">Collection</span> <span class="nf">getEntries</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">entries</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>For some unknown reason, JSTL can not work with sets to determine empty collections. Lists are fine, and even Maps are supported, but not Sets. Way to go JSTL. You’ve proven yet again that JSP is worthless.</p>
<p>Luckily, I stumbled across <a href="http://weblogs.java.net/blog/mister__m/archive/2003/11/crazy_jstl_when.html">this blog that verifies my problem</a>, so I didn’t spend all day digging into this.</p>
Humane Object Iteration2006-07-17T00:00:00+00:00https://codecrate.com/2006/07/humane-object-iteration<p>Over the past several months, I’ve been exposed to more language features than ever before. I’ve been working with Javascript, Java, and I’m starting to be exposed to Ruby as well.</p>
<p>One thing that has really started to bother me about Java (compared to these other languages), is all of the <em>cruft</em> that is required when trying to get stuff done. Specifically, in this blog, I’m talking about object iteration. This is a standard feature in any modern programming language, yet Java seems to have the most bulky and convoluted solution for “out of the box” object iteration.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">i</span> <span class="o">=</span> <span class="n">collection</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">i</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();</span> <span class="o">)</span> <span class="o">{</span>
<span class="nc">Object</span> <span class="n">myObject</span> <span class="o">=</span> <span class="n">i</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, I don’t want to hear about the <a href="http://jcp.org/aboutJava/communityprocess/jsr/tiger/enhanced-for.html">Java 1.5 enhanced for loop</a>. It still falls short of an acceptable solution and is more of a bolt on feature than anything else. I’m sorry, but this Java iteration is far less appealing after being exposed to the Ruby or Javascript syntax.</p>
<p>Object Iteration In Javascript (with Prototype)</p>
<p><a href="http://prototype.conio.net/">Prototype</a> has greatly increased the usability of Javascript by providing a much more elegant approach than the standard for loop.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$$</span><span class="p">(</span><span class="dl">'</span><span class="s1">myElements</span><span class="dl">'</span><span class="p">).</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">//do something with the object</span>
<span class="p">});</span>
</code></pre></div></div>
<p>Object Iteration In Ruby</p>
<p>Ruby takes the cake when it comes to easy object iteration.</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user</span><span class="p">.</span><span class="nf">getDepartments</span><span class="p">().</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">object</span><span class="o">|</span>
<span class="c1">#do something with the object.</span>
<span class="k">end</span>
</code></pre></div></div>
<p>After being exposed to the Javascript and Ruby syntax, I became bound and determined to bring something similar to Java. Unfortunately, since Java does not have the same flexability as Ruby or Javascript to inject new methods into core classes, the solution is nowhere near as elegant.</p>
<p>Object Iteration In Java With Ruby-like Syntax (Version One)</p>
<p>My first stab at doing this in Java was to extract a static util class that would do the iteration and provide a callback for custom code.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">CollectionUtil</span><span class="o">.</span><span class="na">each</span><span class="o">(</span><span class="n">user</span><span class="o">.</span><span class="na">getDepartments</span><span class="o">(),</span> <span class="k">new</span> <span class="nc">ObjectVisitor</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">visit</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//do something with the object.</span>
<span class="o">}</span>
<span class="o">});</span>
</code></pre></div></div>
<p>Here’s the simple little utility class that performs the iteration.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">CollectionUtil</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">each</span><span class="o">(</span><span class="nc">Collection</span> <span class="n">collection</span><span class="o">,</span> <span class="nc">ObjectVisitor</span> <span class="n">visitor</span><span class="o">)</span> <span class="o">{</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">i</span> <span class="o">=</span> <span class="n">collection</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">i</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();</span> <span class="o">)</span> <span class="o">{</span>
<span class="nc">Object</span> <span class="n">object</span> <span class="o">=</span> <span class="n">i</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="n">visitor</span><span class="o">.</span><span class="na">visit</span><span class="o">(</span><span class="n">object</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Also need to define this slim little interface to create the anonymous inner class from.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">ObjectVisitor</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">visit</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, this was not a bad solution, but static util classes are not Object Oriented. Yep, that’s right. Anyone who comes up to me and suggests that I throw some “helper” methods in a “utility” class will get a swift kick to the head. Unfortunately, Java is littered with Util classes (<a href="http://www.jedit.org/42docs/api/bsh/StringUtil.html">StringUtil</a>, <a href="http://www.javazoom.net/jlgui/docs/docs2.2/javazoom/Util/FileUtil.html">FileUtil</a>, <a href="http://www.cs.unm.edu/~wzhao/spo/javadocs/api/spo/src/SPDB/Util/DBUtil.html">DBUtil</a>). This is largely because of it’s limitiation to not allow you to extend the core classes. Ruby has taken a very different approach and allows for developers to extend core classes and add any method you see fit.</p>
<p>Java also chose the <a href="http://www.martinfowler.com/bliki/HumaneInterface.html">minimalist route</a> when designing it’s API’s, and created it’s interfaces with the bare minimum number of methods to allow developers to get their work done. This has forced developers to turn to procedural Util classes to do the work that other languages have built in.</p>
<p>Just for fun, I wanted to take another try at doing this “Java iteration with Ruby syntax”. This time, I used Spring as an example for how to approach this solution. <a href="http://www.springframework.org">Spring</a> is the absolute king of Java frameworks right now, and one interesting design philosophy they have is to provide extention points within their “templates” for your custom code. The <a href="http://www.springframework.org/docs/api/org/springframework/orm/hibernate/HibernateTemplate.html">HibernateTemplate</a> is a perfect example where Spring abstracts away all connection and lifecycle handling and provides a single extension point for all custom code.</p>
<p>So, here’s my second attempt of providing a cleaner way to iterate over objects in Java. This time, no static util classes were needed.</p>
<p>Object Iteration In Java With Ruby-like Syntax (Version Two)</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">new</span> <span class="nc">IteratorTemplate</span><span class="o">(</span><span class="nc">Collection</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onEach</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//do something with the object.</span>
<span class="o">}</span>
<span class="o">}.</span><span class="na">iterate</span><span class="o">();</span>
</code></pre></div></div>
<p>This object is doing the same work as the static util class. But, this solution removes the extra interface class, and instead uses a protected method as the extension point.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">IteratorTemplate</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Collection</span> <span class="n">objects</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">IteratorTemplate</span><span class="o">(</span><span class="nc">Collection</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">objects</span> <span class="o">=</span> <span class="n">objects</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">iterate</span><span class="o">()</span> <span class="o">{</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">i</span> <span class="o">=</span> <span class="n">objects</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">i</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();</span> <span class="o">)</span> <span class="o">{</span>
<span class="nc">Object</span> <span class="n">object</span> <span class="o">=</span> <span class="n">i</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="n">onEach</span><span class="o">(</span><span class="n">object</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kd">abstract</span> <span class="kt">void</span> <span class="nf">onEach</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now, I for one, really prefer this new “template” approach. It’s still not as elegant as Ruby, but I think this is definately a step up from the current standard Java solution for (Iterator blah blah blah).</p>
<p>I’ve repeatedly said that Ruby doesn’t do anything that Java can’t do, it just does it differently. I fully believe that the Java solution is comparable to the Ruby solution, it’s just that the Ruby solution is much more elegant and understandable. The Ruby code is clearer and gives the important code much more <strong>context</strong>. Invoking an operation directly on an object has much more meaning that passing an object to another process to perform the work. For example, myString.isEmpty() reads <strong>completely</strong> different than StringUtil.isEmpty(myString).</p>
<p>Context is everything. Our brains work a certain way and some languages are more intuitive than others because they operate more inline with how we think. Ruby and Javascript should get their due credit for designing API’s that are more intuitive that anything I’ve worked with thus far.</p>
Spring Rich Event Processing Bus2006-07-12T00:00:00+00:00https://codecrate.com/2006/07/spring-rich-event-processing-bus<p>For the past few weeks I’ve been working with spring rich to try and build a simple solution for performing units of work within the gui framework, but so far, <a href="/2006/07/crazy-command-composition.html">my solution has been anything but simple</a>.</p>
<p>I started becoming very interested in this area after reading <a href="http://www.ditchnet.org/wp/2005/06/05/remedial-spring-rcp-episode-2-targetableactioncommands-and-the-edt/">a blog on how Spring could be more tightly integrated with Swing for thread management</a>. Container managed threading, essentially. I’ve taken a lot of inspiration from that blog, and have formed it into something that’s actually usable.</p>
<p>The solution I’ve come up with leverages the <a href="http://static.springframework.org/spring/docs/2.0.x/reference/beans.html#context-functionality-events">spring application event framework</a> to fire processing of these GUI specific actions. I call it an <strong>Event Processing Bus</strong>. Here are a few specific use cases that my current solution supports:</p>
<ul>
<li>
<p>Perform long running operation in a background thread.</p>
</li>
<li>
<p>Prevent UI from locking up while operation is being performed.</p>
</li>
<li>
<p>Provide user feedback for progress of operation.</p>
</li>
<li>
<p>Prevent user input until operation is complete.</p>
</li>
</ul>
<p>For starters, I did not want to couple my business layer to Spring. Heck, I didn’t even want to implement the Spring ApplicationListener interface. I just wanted a simple POJO that would perform work on a published event.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">processApplicationEvent</span><span class="o">(</span><span class="nc">MyEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//perform operation with event</span>
<span class="nc">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="mi">1000</span><span class="o">);</span> <span class="c1">//just for fun</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Wiring this object in Spring is now _much_simpler than <a href="/2006/07/crazy-command-composition.html">my previous incarnation</a>. Simply wrap your business object in the EventTriggeredProgressMonitoredBackgroundCommandExecutor and tell it what method to invoke. It’ll take care of the rest!</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>bean id="myService"
class="org.myproject.MyService"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean id="myCommand"
class="com.codecrate.shard.ui.command.EventTriggeredProgressMonitoredBackgroundCommandExecutor"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg<span class="ni">&gt;&lt;</span>value<span class="ni">&gt;</span>org.myproject.MyEvent<span class="ni">&lt;</span>/value<span class="ni">&gt;&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg index="1"<span class="ni">&gt;&lt;</span>ref bean="myService"/<span class="ni">&gt;&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg index="2"<span class="ni">&gt;&lt;</span>value<span class="ni">&gt;</span>processApplicationEvent<span class="ni">&lt;</span>/value<span class="ni">&gt;&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Thus far, I haven’t shown any details on how this helps Spring Rich GUI applications. It has just been using the core spring framework to wrap event processing in background threads. But this solution really shines when you want to change your service to provide user feedback. Simply update your service to take a Spring Rich ProgressMonitor, and without updating any configuration files, your service will be invoked correctly.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyService</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">processApplicationEvent</span><span class="o">(</span><span class="nc">MyEvent</span> <span class="n">event</span><span class="o">,</span> <span class="nc">ProgressMonitor</span> <span class="n">progressMonitor</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//perform operation with event</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Here is where my solution really differentiates from a simple <em>background thread event processer</em>. The EventTriggeredProgressMonitoredBackgroundCommandExecutor doesn’t simply pass the application event to the target object, it allows for more information to be placed in the context so that the target object can have access to that information as well.</p>
<p>I’d like to invest some more time to see if I can invoke operations without always blocking user input. Blocking user input is definately the “safest” solution, but it would be nice to execute operations in the background and allow the user to continue working.</p>
Music Samples Online2006-07-02T00:00:00+00:00https://codecrate.com/2006/07/music-samples-online<p>I finished adding two new pieces to <a href="http://ryan.codecrate.com">my website</a> this weekend.</p>
<p>First, I integrated <a href="http://del.icio.us/wireframe">my delicious bookmarks</a> using the <a href="http://del.icio.us/help/linkrolls">linkroll javascript</a> posted on delicious. It’s a very robust API with lots of options (specific tags, restrict number of results, etc), and has very good CSS options as well.</p>
<p>And I finally uploaded some <a href="http://ryan.codecrate.com/music">sample music</a> from the drifting North CD. I’ve been meaning to do this for a <em>long</em> time, and I figured now was a good time to try out <a href="http://audacity.sourceforge.net/">Audacity</a>. Now, I’ve just got to figure out a distribution channel for selling CD’s. For now, anyone interested can contact me directly, and I’ll get one in the mail ASAP. I was pretty impressed that delicious even offers some custom javascript for <a href="http://del.icio.us/help/playtagger">playing mp3’s on your site</a> as well!</p>
<p>Just a few more signs that you can pull off some cool
<a href="/2006/06/more-dynamic-for-your-static.html">dynamic content for static sites</a>.</p>
Crazy Command Composition2006-07-01T00:00:00+00:00https://codecrate.com/2006/07/crazy-command-composition<p>I’ll send out a bright shiny new nickel to whoever can guess what this spring xml file is actually accomplishing. :)</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="ni">&lt;</span>bean id="importDatasetCommand" class="com.codecrate.shard.ui.command.SpecificApplicationEventActionCommandExecutor"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg<span class="ni">&gt;&lt;</span>value<span class="ni">&gt;</span>com.codecrate.shard.ui.command.ImportDatasetEvent<span class="ni">&lt;</span>/value<span class="ni">&gt;&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean class="com.codecrate.shard.ui.command.EventDispatcherThreadActionCommandExecutor"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean class="com.codecrate.shard.ui.command.ApplicationWindowProgressMonitorActionCommandExecutor"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean class="com.codecrate.shard.ui.command.FoxtrotBackgroundJobActionCommandExecutor"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean class="com.codecrate.shard.ui.command.MethodInvokingActionCommandExecutor"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>property name="targetObject"<span class="ni">&gt;&lt;</span>ref bean="importDatasetService"/<span class="ni">&gt;&lt;</span>/property<span class="ni">&gt;</span>
<span class="ni">&lt;</span>property name="targetMethod"<span class="ni">&gt;&lt;</span>value<span class="ni">&gt;</span>importDataset<span class="ni">&lt;</span>/value<span class="ni">&gt;&lt;</span>/property<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/constructor-arg<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
</code></pre></div></div>
<p>I absolutely love the decorator pattern. It promotes encapsulation of specific behavior into seperate classes. The problem is that when trying to compose an object with multiple layers of functionality, it can get out of control (like above). Usually, this is where a “factory” object is created to encapsulate complex object creation, but unfortunately for me, the above example can’t be pushed into a factory helper. Why?</p>
<p>First, the SpecificApplicationEventActionCommandExecutor implements the ApplicationListener interface. Spring inspects the application context for classes that implement this functionality, which means this layer has to be defined in XML.</p>
<p>Next, the ApplicationWindowProgressMonitorActionCommandExecutor implements ApplicationWindowAware interface, which has the same issues as the ApplicationListener interface.</p>
<p>Hopefully I’ll be able to encapsulate this functionality into some form of spring prototype block so that I can just inject my customized behavior into this whole stack of wrappers.</p>
Maven2 Eclipse Plugin Tips2006-06-30T00:00:00+00:00https://codecrate.com/2006/06/maven2-eclipse-plugin-tips<p>I’ve been using <a href="http://maven.apache.org">Maven2</a> as my primary build tool for <a href="http://shard.codecrate.com">shard</a> for several monthes now. Since I’m also a long time user of maven1, my integration of maven and eclipse has been pretty minimal. Basically, I only used maven as a convenience tool to generate my eclipse .classpath files. It was far from ideal since it still relied on me using the command line maven to download the dependecies into a common location for eclipse to slurp up.</p>
<p>I just recently decided to dig a bit more into the <a href="http://maven.apache.org/eclipse-plugin.html">maven2 eclipse plugin</a>, and surprisingly, I’ve found it quite useful. The M2Eclipse plugin integrates maven into eclipse as an external tool. No need to download and install maven seperately. All commands that need to be executed (like clean, install, etc) can be run as an external tool.</p>
<p>Dealing with multiple sub-projects became a pain pretty quickly because I had to setup individual commands for each project. Since shard has <em>several</em> sub-projects (core, dice, hibernate, minotaur, phoenix, gui-core, transfer, sheets), it really sucked to have to create an install goal for each one. Here’s a quick trick when dealing with multiple sub-projects like shard to get around creating individual goals per project.</p>
<p>Create a new external goal using the eclipse wizard and use some eclipse variables to execute whatever goal you want on the <strong>currently selected project</strong>. This allows you to only create one goal for each unique operation (compile, test, install, etc).</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Base Directory:
${workspace_loc:/${project_name}}
Goals:
install
</code></pre></div></div>
JDirectoryChooser Binding for Spring Richclient2006-06-28T00:00:00+00:00https://codecrate.com/2006/06/jdirectorychooser-binding-for-spring<p>I’ve been continuing work on <a href="http://shard.codecrate.com">shard</a>, and one aspect that’s been bothering me is how we handle importing of datasets. I <strong>really</strong> dislike the current implementation using a Swing JFileChooser. It doesn’t give the user enough context to know that they’ve selected a valid dataset. So, I decided to check out the JDirectoryChooser from the <a href="http://common.l2fprod.com">common l2fprod project</a>.</p>
<p>I have really enjoyed this component for the past couple days, so I decided to do some work to integrate it into <a href="http://spring-rich-c.sf.net">spring richclient</a>. My main goal was to add a custom binding so that data entry forms can automatically use this component if their model object has a java.util.File property. Here’s an example of how to use the new binding control:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">DirectorySelectionForm</span> <span class="kd">extends</span> <span class="nc">AbstractForm</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">String</span> <span class="no">PAGE_NAME</span> <span class="o">=</span> <span class="s">"importPage"</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">DirectorySelectionForm</span><span class="o">(</span><span class="nc">FormModel</span> <span class="n">formModel</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">formModel</span><span class="o">,</span> <span class="no">PAGE_NAME</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="nc">JComponent</span> <span class="nf">createFormControl</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">SwingBindingFactory</span> <span class="n">bindingFactory</span> <span class="o">=</span> <span class="o">(</span><span class="nc">SwingBindingFactory</span><span class="o">)</span> <span class="n">getBindingFactory</span><span class="o">();</span>
<span class="nc">JDirectoryChooser</span> <span class="n">directoryChooser</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">JDirectoryChooser</span><span class="o">();</span>
<span class="n">directoryChooser</span><span class="o">.</span><span class="na">setControlButtonsAreShown</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>
<span class="nc">TableFormBuilder</span> <span class="n">formBuilder</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">TableFormBuilder</span><span class="o">(</span><span class="n">bindingFactory</span><span class="o">);</span>
<span class="n">formBuilder</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">JDirectoryChooserBinding</span><span class="o">(</span><span class="n">getFormModel</span><span class="o">(),</span> <span class="s">"selectedDirectory"</span><span class="o">,</span> <span class="n">directoryChooser</span><span class="o">));</span>
<span class="k">return</span> <span class="n">formBuilder</span><span class="o">.</span><span class="na">getForm</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The code to build this custom binding was pretty straightforward and might be another cantidate for inclusion into the <a href="http://common.l2fprod.com/articles/taskpane-springrcp.php">common l2fprod spring-rcp components</a>.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">JDirectoryChooserBinding</span> <span class="kd">extends</span> <span class="nc">CustomBinding</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">JDirectoryChooser</span> <span class="n">component</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">JDirectoryChooserBinding</span><span class="o">(</span><span class="nc">FormModel</span> <span class="n">model</span><span class="o">,</span> <span class="nc">String</span> <span class="n">property</span><span class="o">,</span> <span class="nc">JDirectoryChooser</span> <span class="n">component</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">model</span><span class="o">,</span> <span class="n">property</span><span class="o">,</span> <span class="nc">File</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="k">this</span><span class="o">.</span><span class="na">component</span> <span class="o">=</span> <span class="n">component</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="nc">JComponent</span> <span class="nf">doBindControl</span><span class="o">()</span> <span class="o">{</span>
<span class="n">component</span><span class="o">.</span><span class="na">setSelectedFile</span><span class="o">((</span><span class="nc">File</span><span class="o">)</span><span class="n">getValue</span><span class="o">());</span>
<span class="n">component</span><span class="o">.</span><span class="na">addPropertyChangeListener</span><span class="o">(</span><span class="k">new</span> <span class="nc">PropertyChangeListener</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">propertyChange</span><span class="o">(</span><span class="nc">PropertyChangeEvent</span> <span class="n">evt</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">String</span> <span class="n">prop</span> <span class="o">=</span> <span class="n">evt</span><span class="o">.</span><span class="na">getPropertyName</span><span class="o">();</span>
<span class="k">if</span><span class="o">(</span><span class="nc">JDirectoryChooser</span><span class="o">.</span><span class="na">SELECTED_FILE_CHANGED_PROPERTY</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">prop</span><span class="o">))</span> <span class="o">{</span>
<span class="nc">File</span> <span class="n">file</span> <span class="o">=</span> <span class="o">(</span><span class="nc">File</span><span class="o">)</span> <span class="n">evt</span><span class="o">.</span><span class="na">getNewValue</span><span class="o">();</span>
<span class="n">controlValueChanged</span><span class="o">(</span><span class="n">file</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="k">return</span> <span class="n">component</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">readOnlyChanged</span><span class="o">()</span> <span class="o">{</span>
<span class="n">component</span><span class="o">.</span><span class="na">setEnabled</span><span class="o">(</span><span class="n">isEnabled</span><span class="o">()</span> <span class="o">&&</span> <span class="o">!</span><span class="n">isReadOnly</span><span class="o">());</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">enabledChanged</span><span class="o">()</span> <span class="o">{</span>
<span class="n">component</span><span class="o">.</span><span class="na">setEnabled</span><span class="o">(</span><span class="n">isEnabled</span><span class="o">()</span> <span class="o">&&</span> <span class="o">!</span><span class="n">isReadOnly</span><span class="o">());</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">valueModelChanged</span><span class="o">(</span><span class="nc">Object</span> <span class="n">newValue</span><span class="o">)</span> <span class="o">{</span>
<span class="n">component</span><span class="o">.</span><span class="na">setSelectedFile</span><span class="o">((</span><span class="nc">File</span><span class="o">)</span><span class="n">newValue</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I also built a simple binder that would allow you to register all java.util.File properties to use this JDirectoryChooserBinding.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">JDirectoryChooserBinder</span> <span class="kd">extends</span> <span class="nc">AbstractBinder</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="nf">JDirectoryChooserBinder</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="nc">File</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="nc">JComponent</span> <span class="nf">createControl</span><span class="o">(</span><span class="nc">Map</span> <span class="n">context</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="nf">JDirectoryChooser</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="nc">Binding</span> <span class="nf">doBind</span><span class="o">(</span><span class="nc">JComponent</span> <span class="n">control</span><span class="o">,</span> <span class="nc">FormModel</span> <span class="n">formModel</span><span class="o">,</span> <span class="nc">String</span> <span class="n">formPropertyPath</span><span class="o">,</span> <span class="nc">Map</span> <span class="n">context</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">final</span> <span class="nc">JDirectoryChooser</span> <span class="n">directoryChooser</span> <span class="o">=</span> <span class="o">(</span><span class="nc">JDirectoryChooser</span><span class="o">)</span> <span class="n">control</span><span class="o">;</span>
<span class="k">return</span> <span class="k">new</span> <span class="nf">JDirectoryChooserBinding</span><span class="o">(</span><span class="n">formModel</span><span class="o">,</span> <span class="n">formPropertyPath</span><span class="o">,</span> <span class="n">directoryChooser</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Simple, but there seem to be a few issues to be worked out yet. I tried adding a custom validator to my model object to make sure that the selected directory contained relevant files, but the validator did not work correctly. It always showed the selected directory as null. I’m assuming this is an issue with my validator, but I haven’t been able to figure this out yet.</p>
<p>That’s all for now.</p>
When Will The Hurting Stop?2006-06-14T00:00:00+00:00https://codecrate.com/2006/06/when-will-hurting-stop<p>It’s been a _long_time since I’ve <a href="/2005/02/jsp-is-joke.html">blogged about</a> <a href="/2004/10/two-faces-of-jsp.html">how much I <strong>HATE</strong> JSP</a>. Today marks yet another day in the unending saga of pain and misery, and yet another reason this beast needs to be put to sleep.</p>
<p>I seriously just spent the past two days troubleshooting why my page shows one chunk of information with correct encoding, and another piece all jumbled. Of course, if I would have _known_it was an “encoding issue”, it wouldn’t have taken me so long, but that’s not exactly the first place I checked since it worked for half the page. The “Standard” JSTL import tag isn’t exactly a red flag for losing the current page encoding.</p>
<p>Just to be perfectly clear why this pisses me off. My webapp renders all pages with UTF-8 encoding (I have actually taken the time to verify that this is true for the entire application). The <strong>problem</strong> is when you use JSTL to import common JSP fragments into your page. JSP <em>conveniently</em> drops the current page encoding when importing the fragment.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code><c:import charEncoding="UTF-8" url="/WEB-INF/views/jsp/myPage.jsp" />
</code></pre></div></div>
<p>I’ve tried a whole lot of things over the past two days to solve this issue, and every one of them proved fruitless.</p>
<ul>
<li>Data setup problem. Maybe it just looks bad for this one object?</li>
<li>Data conversion/truncation issue. If it’s correct in the database, is it getting mangled somewhere else?</li>
<li>Wrong tags (struts, jstl, spring). Does JSTL have different behaviour than Struts tags?</li>
</ul>
<p>Of course! It’s a JSP problem! From this day forward, may this be a new starting point for all of my troubleshooting. Always blame JSP first, until proven otherwise.</p>
<p>Let this blog be a testiment to the suckyness of JSP. If you use JSP, stop using JSP. If you can’t stop using JSP, consider tossing yourself from a balcony to avoid dealing with it’s suckyness. If you wish to live, even though you work with JSP, make sure you set your encoding when using the JSTL import tag.</p>
Preview Release of Shard Minotaur2006-06-13T00:00:00+00:00https://codecrate.com/2006/06/preview-release-of-shard-minotaur<p>Whew…I just wrapped up <a href="http://wiki.codecrate.com/display/SHA/2006/06/13/Preview+Release+of+Shard+Minotaur">releasing a preview of the new shard-minotaur d20 character generator application</a> that I’ve been working on for quite a while. I’ve been chomping at the bit to get this app out there so that I can get feedback as early as possible.</p>
<p>I’m interested to see what people think about the app, even though it’s extremely early. I’m not sure what user’s reactions will be to an application that’s “functional” yet “limited”. I hate calling things an <strong>alpha</strong> or <strong>beta</strong> release, but is it necessary for users to feel comfortable using the app?</p>
<p>I’m still new to this whole release announcement thing and I’m not a big fan of cross posting, so I’ll try to make any release postings on this blog relevant to it’s audience. Anyone interested in more info about the shard RPG project can ping me or check out the <a href="http://shard.codecrate.com">project website</a>.</p>
More Dynamic For Your Static2006-06-13T00:00:00+00:00https://codecrate.com/2006/06/more-dynamic-for-your-static<p>I’ve been undergoing an experiment to build <a href="http://ryan.codecrate.com">my own website</a>, and I’ve come to realize the importance of Javascript for next generation websites. I’m predicting that there will be a significant paradigm shift where websites will move away from using dynamic content hosted on Java application servers and instead use remote services exposed through Javascript API’s (which might in turn be hosted on Java app servers).</p>
<p>This is quite a radical change for me. I’ve been hosting websites for years using application servers even if the website only needed simple header/footer/gutter wrapping. It took a bit of work, but here’s how I took the jump from dynamic sites to static.</p>
<h3 id="solving-headerfootergutter">Solving Header/Footer/Gutter</h3>
<p>Every website I’ve built has required some form of standard navigation decoration. I’ve used <a href="http://www.opensymphony.com/sitemesh/">sitemesh</a> for nearly all of my projects, and it is by far the best solution out there for dynamic page decoration. Obviously, without an application server, something needed to change, and luckily I ran across a tool called <a href="http://www.pols.co.uk/downloads/static-mesh/">staticmesh</a>. Staticmesh is built ontop of sitemesh for offline website generation. So, instead of dynamically decorating pages at request time, I use site mesh to decorate pages at “build time”. I whipped up a quick little Maven2 plugin in about 10 minutes, and just like that, I had a solution for 90% of my application server needs. I can share my Maven2 plugin if anyone is interested…</p>
<h3 id="get-dynamic">Get Dynamic!</h3>
<p>Once I had a working “plain old static site”, I wasn’t expecting much more and this is where Javascript really began to surprise me. There’s a ton of excellent website widgets that can be dropped onto a static site to really liven it up. I was especially interested in integrating a picture gallery and some form of rss aggregator onto my site.</p>
<p>I’ve been an <a href="http://www.flickr.com/photos/wireframe">avid user</a> of <a href="http://www.flickr.com">flickr</a> for quite some time, and their Javascript solution works right out of the box. I’m not a big fan of their table based layout for the pictures, but it get’s the job done, and has decent CSS usage to customize the look.</p>
<p>Next on my list was trying to integrate rss feeds. After several nights searching around, the best I had come up with was <a href="http://www.rss-to-javascript.com/">Javascirpt integration that relied on a PHP server to stream the RSS</a>. This really didn’t interest me since I’m trying to build a site that’s not dependent on an application server, and that’s when I discovered the magic of Google. <a href="http://reader.google.com">Google Reader</a> is an online blog aggregator that exposes it’s feeds to a Javascript API. I’ve been using Google Reader as an “official” replacement for bloglines for a couple monthes now, but I didn’t know about their Javascript API until recently.</p>
<p>That took care of my current needs, but I was definately excited to see a whole slew of other Javascript widgets that could be integrated into purely static sites. [Right Cart looks extremely promising for integrating a complete shopping expreience into a static website, and I may look into this again later if I <a href="http://ryan.codecrate.com/music/">start selling CD’s online</a>. The <a href="http://dojotoolkit.org/">dojo toolkit</a> also has some great examples of Javascript widgets for things like a complete image slideshow too.</p>
<p>Changing from a dynamic hosted site to a purely static site takes some work but so far, it’s been well worth the work. And it’s definitely taught me that, “Not all roads lead to Java”. Maybe all roads lead to Javascript?</p>
Ruby Syntax For Java Maps2006-06-06T00:00:00+00:00https://codecrate.com/2006/06/ruby-syntax-for-java-maps<p>Ruby’s got a lot of momentum going for it right now. One of the syntax sugars that has gotten a lot of attention is for <a href="http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#hash">creation of maps</a>. Compare the typical Java code to create a map with the Ruby equivilent, and you’ll see why it’s getting so much attention.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Java implementation</span>
<span class="nc">Map</span> <span class="n">options</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">();</span>
<span class="n">options</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"foo"</span><span class="o">,</span> <span class="s">"bar"</span><span class="o">);</span>
<span class="n">options</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"option"</span><span class="o">,</span> <span class="s">"value"</span><span class="o">);</span>
<span class="n">options</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"flag"</span><span class="o">,</span> <span class="s">"true"</span><span class="o">);</span>
</code></pre></div></div>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Ruby implementation</span>
<span class="p">{</span><span class="s2">"foo"</span><span class="o">=></span><span class="s2">"bar"</span><span class="p">,</span> <span class="s2">"option"</span><span class="o">=></span><span class="s2">"value"</span><span class="p">,</span> <span class="s2">"flag"</span><span class="o">=></span><span class="s2">"true"</span><span class="p">}</span>
</code></pre></div></div>
<p>This ease of use has led to the creation of several Ruby API’s that take a map as a parameter. Javascript developers have been doing this for quite some time, and <a href="http://script.aculo.us/">scriptaculous</a> is an excellent example of how to use a map parameter effecively to pass optional information.</p>
<p>Ruby and Javascript have essentially taken maps and used them as named parameters, which has led to many Java developers clammering for <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4124331">first class named parameter support in Java</a>. It isn’t necessary to “fix” Java to support this feature, because this can be accomplished already with no JVM changes. To put it bluntly, Java has the ability to make maps more usable, it’s just a bit different than Ruby.</p>
<p>This slick little example is just leveraging a little known Java feature called an initializing block. Basically, it’s creating a subclass of the desired map implementation, and initializing the map upon construction. This code will work for any kind of map.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Map</span> <span class="n">options</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">()</span> <span class="o">{</span> <span class="o">{</span>
<span class="n">put</span><span class="o">(</span><span class="s">"key"</span><span class="o">,</span> <span class="s">"value"</span><span class="o">);</span>
<span class="n">put</span><span class="o">(</span><span class="s">"option"</span><span class="o">,</span> <span class="s">"foo"</span><span class="o">);</span>
<span class="n">put</span><span class="o">(</span><span class="s">"flag"</span><span class="o">,</span> <span class="s">"bar"</span><span class="o">);</span>
<span class="o">}</span> <span class="o">};</span>
</code></pre></div></div>
<p>Another way to accomplish this would be to create a utility implementation that takes a multi-dimensional array as a constructor argument. The downfall of this implementation is that you can’t swap out implementations as easily. This would be an issue if you’re using something like the <a href="http://jakarta.apache.org/commons/collections">commons-collections</a> map implementations.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Map</span> <span class="n">options</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">SimpleHashMap</span><span class="o">(</span><span class="k">new</span> <span class="nc">Object</span><span class="o">[][]</span> <span class="o">{</span>
<span class="o">{</span><span class="s">"key"</span><span class="o">,</span> <span class="s">"value"</span><span class="o">},</span>
<span class="o">{</span><span class="s">"option"</span><span class="o">,</span> <span class="s">"foo"</span><span class="o">},</span>
<span class="o">{</span><span class="s">"flag"</span><span class="o">,</span> <span class="s">"bar"</span><span class="o">}</span>
<span class="o">});</span>
<span class="c1">//simple implementation of the helper class</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">SimpleHashMap</span> <span class="kd">extends</span> <span class="nc">HashMap</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">SimpleHashMap</span><span class="o">(</span><span class="nc">Object</span><span class="o">[][]</span> <span class="n">options</span><span class="o">)</span> <span class="o">{</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">x</span> <span class="o"><</span> <span class="n">options</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">x</span><span class="o">++)</span> <span class="o">{</span>
<span class="nc">Object</span> <span class="n">key</span> <span class="o">=</span> <span class="n">options</span><span class="o">[</span><span class="n">x</span><span class="o">][</span><span class="mi">0</span><span class="o">];</span>
<span class="nc">Object</span> <span class="n">value</span> <span class="o">=</span> <span class="n">options</span><span class="o">[</span><span class="n">x</span><span class="o">][</span><span class="mi">1</span><span class="o">];</span>
<span class="n">put</span><span class="o">(</span><span class="n">key</span><span class="o">,</span> <span class="n">value</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Maybe the Ruby syntax sugar would be nice for Java, but it certainly is not necessary. As a side note, it’s essential that developers take extreme care when developing API’s that use map parameters. An API needs to have <a href="/2006/03/clear-api.html">clear expectations</a> for what it needs to perform it’s work. The concept of passing a map to a method only makes sense when the map contains optional flags. It’s all about sensible defaults, and the successful Javascript and Ruby API’s have got that down. If a method takes a map of options, it better work just fine with an empty map!</p>
JRoller Issues2006-06-05T00:00:00+00:00https://codecrate.com/2006/06/jroller-issues<p>I can’t say that I’m exactly impressed with the folks who run JRoller. After their latest upgrade, my templates have broken permalinks. I originally customized my template to add <a href="http://technorati.com">technorati</a> links, but reverting to the “default” templates doesn’t fix the issue. The permalinks for each blog contains an unrendered velocity macro, $entry.website.user.userName. Now, you’d expect a bug this noticeable to be fixed after an hour or two, but this has been lingering around for the past two months!</p>
<p>Any good opensource project has bug trackers to work with these kinds of issues, but this isn’t a problem with the <a href="http://rollerweblogger.org/page/project">roller blogging engine</a>. JRoller’s implementation is just broken, and how do they track their issues? I’ve tried posting comments for the site owners, but that hasn’t made any progress. It’s pretty much a one-way communication stream…</p>
<p>Just goes to show you that you get what you pay for. Maybe it’s finally time for me to start hosting my own blog.</p>
Simple CSS Builder2006-05-15T00:00:00+00:00https://codecrate.com/2006/05/simple-css-builder<p>I would like to think that most developers can avoid hardcoding web content (html, javascript or CSS) directly in Java code. Realistically though, there are times when it’s just easier to put it in the code. <a href="http://wicketframework.org">Wicket</a> is definately improving this, but I’m sure there will still be times where this web content get’s hardcoded in Java.</p>
<p>In order to try and ease any future pain I have with generating CSS within Java, I finally broke down and wrote a simple CSS utility class. <strong>Disclaimer:</strong> This utility was built using 100% Test Driven Development. =)</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.util.ArrayList</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Collection</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.HashMap</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Iterator</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Map</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">CssBuilder</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">Collection</span> <span class="n">selectors</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="kd">public</span> <span class="nc">CssSelector</span> <span class="nf">startSelector</span><span class="o">(</span><span class="nc">String</span> <span class="n">selector</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">CssSelector</span> <span class="n">newSelector</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">CssSelector</span><span class="o">(</span><span class="n">selector</span><span class="o">);</span>
<span class="n">selectors</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">newSelector</span><span class="o">);</span>
<span class="k">return</span> <span class="n">newSelector</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">toString</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="nf">printStyle</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">printStyle</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">StringBuffer</span> <span class="n">output</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringBuffer</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">iter</span> <span class="o">=</span> <span class="n">selectors</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span> <span class="n">iter</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();)</span> <span class="o">{</span>
<span class="nc">CssSelector</span> <span class="n">selector</span> <span class="o">=</span> <span class="o">(</span><span class="nc">CssSelector</span><span class="o">)</span> <span class="n">iter</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="n">output</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">selector</span><span class="o">.</span><span class="na">printStyle</span><span class="o">());</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">output</span><span class="o">.</span><span class="na">toString</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">CssSelector</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">String</span> <span class="n">selector</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Map</span> <span class="n">properties</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">();</span>
<span class="nc">CssSelector</span><span class="o">(</span><span class="nc">String</span> <span class="n">selector</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">selector</span> <span class="o">=</span> <span class="n">selector</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">toString</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="nf">printStyle</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">CssSelector</span> <span class="nf">addProperty</span><span class="o">(</span><span class="nc">String</span> <span class="n">property</span><span class="o">,</span> <span class="nc">String</span> <span class="n">value</span><span class="o">)</span> <span class="o">{</span>
<span class="n">properties</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">property</span><span class="o">,</span> <span class="n">value</span><span class="o">);</span>
<span class="k">return</span> <span class="k">this</span><span class="o">;</span>
<span class="o">}</span>
<span class="nc">String</span> <span class="nf">printStyle</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">StringBuffer</span> <span class="n">output</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringBuffer</span><span class="o">();</span>
<span class="n">output</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">selector</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="s">" {\n"</span><span class="o">);</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Iterator</span> <span class="n">iter</span> <span class="o">=</span> <span class="n">properties</span><span class="o">.</span><span class="na">keySet</span><span class="o">().</span><span class="na">iterator</span><span class="o">();</span> <span class="n">iter</span><span class="o">.</span><span class="na">hasNext</span><span class="o">();)</span> <span class="o">{</span>
<span class="nc">String</span> <span class="n">property</span> <span class="o">=</span> <span class="o">(</span><span class="nc">String</span><span class="o">)</span> <span class="n">iter</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
<span class="nc">String</span> <span class="n">value</span> <span class="o">=</span> <span class="o">(</span><span class="nc">String</span><span class="o">)</span> <span class="n">properties</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">property</span><span class="o">);</span>
<span class="n">output</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">" "</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="n">property</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="s">": "</span><span class="o">);</span>
<span class="n">output</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">value</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="s">";\n"</span><span class="o">);</span>
<span class="o">}</span>
<span class="n">output</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"}\n"</span><span class="o">);</span>
<span class="k">return</span> <span class="n">output</span><span class="o">.</span><span class="na">toString</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I’ve tried to follow Domain Driven Design principles, even for this simple class. It was important to try and use the correct language when designing this API. Notice the use of properties instead of attributes. Selector is a term that I’m not too familiar with, but <a href="http://www.w3.org/TR/REC-CSS2/selector.html">it is correct term</a>, and is definately more descriptive than my second runner up, Element.</p>
<p>This is my first excursion into using method chaining. I used to loathe method chaining, but I’ve come to realize that it has it’s place. It’s pretty slick to see code this simple:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nc">String</span> <span class="nf">buildCss</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">CssBuilder</span> <span class="n">builder</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">CssBuilder</span><span class="o">();</span>
<span class="n">builder</span><span class="o">.</span><span class="na">startSelector</span><span class="o">(</span><span class="s">".style"</span><span class="o">)</span>
<span class="o">.</span><span class="na">addProperty</span><span class="o">(</span><span class="s">"display"</span><span class="o">,</span> <span class="s">"none"</span><span class="o">)</span>
<span class="o">.</span><span class="na">addProperty</span><span class="o">(</span><span class="s">"padding-left"</span><span class="o">,</span> <span class="s">"0"</span><span class="o">);</span>
<span class="k">return</span> <span class="n">builder</span><span class="o">.</span><span class="na">printStyle</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>
What The $2006-05-12T00:00:00+00:00https://codecrate.com/2006/05/what<p>Here’s a little snippit that could end up on <a href="http://thedailywtf.com/">The Daily WTF</a>.</p>
<p>Is anyone out there familiar with how Java compiles inner classes? Sure, they append a $ to the inner class name. Now, suppose some developer knows the inner workings of the Java compiler and wants to make the compiler’s job easier. What would you do? Of course! You’d name your inner class starting with a $! This should make compilation time much quicker, and it leaves an amazing legacy of source code for future developers.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Foo</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">class</span> <span class="err">$</span><span class="nc">Bar</span> <span class="o">{</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Priceless…</p>
Prevent Caching of Javascript Files2006-05-11T00:00:00+00:00https://codecrate.com/2006/05/prevent-caching-of-javascript-files<p>I spend the majority of my “real” work on a webapp that goes through weekly releases. The majority of javascript for the app was written inline, until recent UI designers started extracting javascript into external .js files. The rational for moving the javascript to separate files is to avoid pushing excess bytes across the wire with every request and allow for browsers to cache files.</p>
<p>Since the browser now caches these javascript files, we’re now running into an interesting issue. When we roll out updates to the webapp, the new webpages may reference updated javascript, and the browser might not refresh it’s reference to the javascript files. This is a thorn in developer’s sides when trying to make local changes as well. Using the <a href="http://chrispederick.com/work/webdeveloper/">Firefox web developer extension</a> to clear the browser’s cached files is about the only thing that prevents me from pulling my hair out some days.</p>
<p>I’ve been searching for better solutions to prevent browser caching, and as far as I can tell, there are two possible solutions for this problem. One is to make the webapp force static file cache expiration by using a custom cache key. <a href="http://www.raibledesigns.com/page/rd/20030714#prevent_caching_of_javascript_and">Matt Raible</a> has a pretty old post on this, and I’ve seen Wicket developers comment on a similar issue with AJAX images being cached by the browser. It seems like anytime a file is referenced by url and not truly static, we should always be adding “?rand=123123” to the url. It’s not exactly elegant, but it’s very explicit. The other option seems to rely on configuring your webserver (like Apache) to know when to refresh the files, but I’m pretty clueless when it comes to webserver configuration.</p>
<p>I’m starting to wonder why people have an issue with inline javascript…</p>
Business Analysts are a Crutch2006-05-10T00:00:00+00:00https://codecrate.com/2006/05/business-analysts-are-crutch<p>I’ve come to the realization that there is no “silver bullet” for software development processes. I personally believe that agile software development practices have great benefit for most teams. That being said, I no longer believe that <a href="http://www.extremeprogramming.org/">eXtreme Programming</a> is the right solution for every development team.</p>
<p>There are certainly developers I know that just couldn’t handle moving to a more agile development environment. They are too comfortable with the “black box” development environment where business analysts tell them what to build, and they just code…no questions asked.</p>
<p>Business analysts are simply a crutch for developers in this waterfall development environment. The idea that all requirements and functionality can be gathered before implementation is a falicy. I have yet to work on a single project that didn’t undergo some form of change once implementation began. And yet, business analysts spend weeks gathering requirements, then “throw it over the wall” for developers to implement.</p>
<p>Business analysts serve their purpose as a developer “safety blanket”. Their job is to make developers all warm and fuzzy inside, and soothe any worries about how the project should work. Developers are not expected to be held accountable for what they build, and this is my biggest issue with this environment.</p>
<p>“The only thing constant is change.” Why not embrace it?</p>
Purpose Of Validation2006-05-09T00:00:00+00:00https://codecrate.com/2006/05/purpose-of-validation<p>There are more than a few validation frameworks out there. Pretty much <a href="http://jakarta.apache.org/commons/validator/">every</a><a href="http://www.onjava.com/pub/a/onjava/2002/12/11/jakartastruts.html">single</a><a href="http://www.springframework.org/docs/reference/validation.html">application</a><a href="http://www.hibernate.org/hib_docs/annotations/reference/en/html/validator.html">framework</a> out there has rolled their own implementation, and there’s no chance of this stopping soon. Sure, each of these frameworks has their own use case, but why does this pattern continue?</p>
<p>The most common misconception developers have about validation frameworks is that it’s the validator’s job is to make sure data is valid. That’s right, I said this is wrong.</p>
<p>What? How can this be? Isn’t this the entire reason for a validator’s measily existance to validate data? No, the <strong>true purpose for validators is to provide feedback</strong>.</p>
<p>Imagine a simple webapp where a client can enter information. The user goes to an edit screen for the object, which fires a validator when the object is saved. What’s wrong with the following scenerio?</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">FooValidator</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">isValid</span><span class="o">(</span><span class="nc">Object</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Foo</span> <span class="n">foo</span> <span class="o">=</span> <span class="o">(</span><span class="nc">Foo</span><span class="o">)</span> <span class="n">object</span><span class="o">;</span>
<span class="k">return</span> <span class="n">foo</span><span class="o">.</span><span class="na">isValid</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The problem with this kind of validation is that the object (Foo) may already be in an invalid state. We’re relying on client code (FooValidator) to make sure the object is in a “good state”, instead of the object being smart enough to prevent invalid state. That means, by simply removing the validator, you’re allowing invalid data into your system. Or, if another developer wrote a second edit page, and forgot to register the validator, you’ve got the same problem.</p>
<p>So, if it’s up to the object to keep itself in a good state, what’s the purpose of the validator? Simple, to give the user a pretty error message instead of a big fat stacktrace. I would encourage developers to invest more time making their objects “safe”, instead of wasting time building more validation frameworks.</p>
Running Code Doesn't Lie2006-04-25T00:00:00+00:00https://codecrate.com/2006/04/running-code-doesn-lie<p>My reading group recently finished <a href="http://www.oreilly.com/catalog/hfdesignpat/">Head First Design Patterns</a> and is now diving into <a href="http://domaindrivendesign.org/book/">Domain-Driven Design</a>. So far, it has really opened my eyes to a new approach to software development. I’m not going to review the book here, but there’s one statement that really caught my eye.</p>
<p>Running code doesn’t lie.</p>
<p>This statement pretty much sums up why agile software development practices like <a href="http://www.extremeprogramming.org/">eXtreme Programming</a> and <a href="https://gettingreal.37signals.com/">Getting Real</a> are so powerful. Instead of business analysts or programmers writing pages of documentation for what they think the system does, the system tells you what it does. I like to call this a Self Describing System.</p>
<p>The cost of maintaining two sources of documentation is just too high. Eventually one or the other will fall out of synch and become irrelevant (even dangerous). The code is the only true source for understanding how a system works. Now, I don’t expect everyone to go to the code to understand how a system works, and I’d be the last person to allow business people to start digging around in my source code. Instead, I am advocating that the codebase be the definitive source for relevant documentation. </p>
<p>There are a number of tools out there than can give insight into code <a href="http://checkstyle.sourceforge.net/">quality</a> or <a href="http://pmd.sourceforge.net/">system metrics</a>, but most of these tools are far too technical and completely meaningless to a business person. But, there are tools out there that can give important contextual information for anyone to understand. <a href="http://agiledox.sourceforge.net/">TestDox </a>is one of these tools, and it has really driven me to look into this area more.</p>
<p>TestDox generates reports describing a system’s features using unit tests as it’s source. This may sound like a simple feature, but I find it incredibly powerful. Take the following unit test:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">DogTest</span> <span class="kd">extends</span> <span class="nc">TestCase</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">testDogWalksWhenYouKickIt</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Dog</span> <span class="n">dog</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Dog</span><span class="o">();</span>
<span class="nc">Person</span> <span class="n">me</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Person</span><span class="o">();</span>
<span class="n">me</span><span class="o">.</span><span class="na">kick</span><span class="o">(</span><span class="n">dog</span><span class="o">);</span>
<span class="n">assertTrue</span><span class="o">(</span><span class="n">dog</span><span class="o">.</span><span class="na">isWalking</span><span class="o">());</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">testDogBarksWhenSitsDown</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Dog</span> <span class="n">dog</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Dog</span><span class="o">();</span>
<span class="n">dog</span><span class="o">.</span><span class="na">sit</span><span class="o">();</span>
<span class="n">assertTrue</span><span class="o">(</span><span class="n">dog</span><span class="o">.</span><span class="na">didBark</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>would generate the following:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Dog
- dog walks when you kick it
- dog barks when sits down
</code></pre></div></div>
<p>There you have it! A Self Describing System for free! No additional documents. No extra frameworks or meta programming. Just straight up unit tests and a simple report generator. </p>
<p>I’d love to see more work done to improve this. First of all, the reports could use a <em>lot</em> of prettying up. A <a href="http://maven.apache.org">maven2 plugin</a> would be great as well. The source for this project is not too complex, so I might have to roll up my sleeves and try to make some improvements myself. </p>
Performance Is Overrated2006-04-13T00:00:00+00:00https://codecrate.com/2006/04/performance-is-overrated<p>Let me get one thing clear: Software performance _is_important, but it’s also _completely_overrated.</p>
<p>Why is it that in nearly every code inspection, the _first_comment I hear is related to performance? Is performance somehow _the_most important software metric? Are educational institutions forcing programmers to believe that fast procedural code is all that matters? Hell, it might be time to throw out Java for good old assembly! I can’t count the number of times I’ve heard something like, “If I loop through this collection twice, it will be slower.” So what!</p>
<p>Sure, your code <em>may_be faster, but will it be more <strong>clear</strong>? More <strong>testable</strong>? More <strong>understandable</strong>? Give me clean _slow_code any day of the week. In the end, your fast code doesn’t matter to me unless you can _prove</em> that it’s faster.</p>
<p>“Early optimization is the root of much evil.”</p>
Two Forms For The Price Of One2006-04-08T00:00:00+00:00https://codecrate.com/2006/04/two-forms-for-price-of-one<p>For the most part, I’m a Javascript hack, but I keep getting pulled into doing more of it. Here’s a little trick I learned recently.</p>
<p>It’s pretty common for websites to offer a _simple view_and an _advanced view_for data entry. Heck, even Google has an <a href="http://www.google.com/advanced_search?hl=en">advanced search page</a>.</p>
<p>The addition of an advanced view usually would entail more server side programming to handle the different data entry, but what if that wasn’t necessary? What if you only needed to build the server side handling of the <em>advanced view_and used CSS and Javascript to display the _simple view</em>?</p>
<p>Just by wrapping your advanced components in a div tag, CSS can be used to hide them. A little Javascript is all you need to change the CSS style so that the advanced view shows up. Here’s an example:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>html<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>style type="text/css"<span class="ni">&gt;</span>
.basicView .advanced {
display: none;
}
<span class="ni">&lt;</span>/style<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type="text/javascript"<span class="ni">&gt;</span>
function displayAdvancedView() {
//change from basicView to advancedView
//this causes the CSS to no longer hide the advanced components
document.getElementById("form").className="advancedView";
}
<span class="ni">&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div id="form" class="basicView"<span class="ni">&gt;</span>
Keywords: <span class="ni">&lt;</span>input type="text" name="keywords" /<span class="ni">&gt;</span>
<span class="ni">&lt;</span>a href="#" onclick="displayAdvancedView();"<span class="ni">&gt;</span>Advanced View<span class="ni">&lt;</span>/a<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div class="advanced"<span class="ni">&gt;</span>
Start Date: <span class="ni">&lt;</span>input type="text" name="startDate" /<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>This example would also require the server side to handle default values for the advanced view since those fields will be posted, even if they are hidden.</p>
<p>This little trick can save quite a bit of development time when applications require a simple and advanced view for data entry. It’s not perfect, but it’s quick and easy to implement. I think it would be really cool to use <a href="http://script.aculo.us/">scriptaculous effects</a> to smoothly display the advanced components instead of just magically showing up.</p>
Clear API2006-03-30T00:00:00+00:00https://codecrate.com/2006/03/clear-api<p>Let me start by saying that I like clear and concise code. I promote best practices and design patterns whenever possible and use tools like <a href="http://pmd.sourceforge.net/">PMD</a> help identify code that maybe too complex for it’s own good. However, I think it’s more importantto have a clear API over a clear implementation.</p>
<p>The API is your contract to clients. It needs to be expressive and understandable. I can’t count the number of bugs caused by developers using an existing API incorrectly and saying “I didn’t know it did that!?”. That’s why it’s so important to have a strong domain model with a clean and expressive API. This is one skill that seperates the <em>programmers_from the _architects</em>.</p>
<p>In the end, all I care about is that your code does what it’s supposed to do. If it’s implementation is ugly, but does what it’s supposed to, that’s okay with me. This is easily verified using unit tests, and is yet another reason I think <a href="/2005/07/actions-speak-louder-than-words.html">reviewing test cases is more important than actually reviewing code</a>. If you have a un-clear API with a muddled implementation <em>and</em> no unit tests, I guess you’re in a <a href="/2005/10/untested-equals-broken.html">bit of trouble</a>.</p>
The Curse Of Passion2006-03-20T00:00:00+00:00https://codecrate.com/2006/03/curse-of-passion<p>For the most part, <em>passion_is a great thing. It’s a word associated with <a href="http://dictionary.reference.com/search?q=passion">fervor, fire and zeal</a>. As a software developer, passion is what keeps me going. It’s what pushes me to innovate, invent and create the best possible solution for the problem at hand. If I were forced to describe myself, I think I would choose, _A Passionate Opensource Software Developer</em>.</p>
<p>The flip side is that passion can drive you to the brink of insanity, if you let it. Many a night have I burnt the midnight oil implementing <em>just one more feature</em>. The same thing happens when I feel like a project is slipping behind or not going as smoothly as I would like. I over-analyze the situation, and look for any way to get back on track. More than once, this has led me into some pretty controversial situations. I haven’t been afraid to tell people blatently when I think they’re wrong, or when a process is broken and needs to be changed.</p>
<p>Some might consider this arrogance, but I expect people to be passionate for their work. You’ve got to be confident if you really believe you’re right.</p>
<p>Last week I started work on a project I would dub <em>The Worst Project I’ve Worked On In The Past Two Years</em>. It’s essentially taking everything I just learned from the amazing <a href="https://gettingreal.37signals.com/">_Getting Real_book by 37signals</a> and throwing it right out the window. Meeting after meeting, with no end in sight. No clear definition or _vision_of what we’re trying to attain. Constant speculation about what the user _wants_instead of just building it and listening to their feedback. I can’t count the number of times I’ve wanted to impale myself with my pen while sitting through hour after hour of meeting.</p>
<p>Yes, passion can be a great thing, but there are definitely times when I wish I could <em>turn it off</em>. It would be great to be like the mindless drones around me once and a while. It’d be nice to not care how bad a project is, and to ignore the terrible code other people are writing. Unfortunately, passion is not just a switch you can turn on or off whenever you want.</p>
Preview Multiple Levels of Components2006-03-13T00:00:00+00:00https://codecrate.com/2006/03/preview-multiple-levels-of-components<p>My <a href="/2006/03/wicket-preview-with-one-javascript.html">previous</a> <a href="/2006/03/auto-previewable-wicket-pages.html">incarnations</a> of the wicket:preview feature have fallen short when trying to preview multiple levels of components. I personally don’t think it’s that big of a deal for the preview to not handle this, but based on the feedback I’ve received, I decided to at least look into it.</p>
<p>Here’s a sample scenario that I’ve been using to test this idea out.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> mysite
|__Home.html -- This is the homepage that includes the login panel
|__login
| \__Login.html -- The login panel includes the cool widget
|__widget
| \__CoolWidget.html
</code></pre></div></div>
<h3 id="mysitehomehtml">mysite/Home.html</h3>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>html<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>title<span class="ni">&gt;</span>Preview Multiple Levels of Components<span class="ni">&lt;</span>/title<span class="ni">&gt;</span>
<span class="ni">&lt;</span>wicket:remove<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;</span> src=<span class="ni">&quot;</span>wicket-preview.js<span class="ni">&quot;&gt;&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/wicket:remove<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
Welcome to my cool site!
<span class="ni">&lt;</span>div wicket:id=<span class="ni">&quot;</span>loginForm<span class="ni">&quot;</span> wicket:preview=<span class="ni">&quot;</span>login/Login.html<span class="ni">&quot;&gt;</span>Text should be replaced<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<h3 id="mysiteloginloginhtml">mysite/login/Login.html</h3>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code>username: <span class="ni">&lt;</span>input wicket:id=<span class="ni">&quot;</span>username<span class="ni">&quot;</span> type=<span class="ni">&quot;</span>text<span class="ni">&quot;</span> name=<span class="ni">&quot;</span>username<span class="ni">&quot;</span> /<span class="ni">&gt;</span>
password: <span class="ni">&lt;</span>input wicket:id=<span class="ni">&quot;</span>password<span class="ni">&quot;</span> type=<span class="ni">&quot;</span>password<span class="ni">&quot;</span> name=<span class="ni">&quot;</span>password<span class="ni">&quot;</span> /<span class="ni">&gt;</span>
<span class="err">&</span>lt!-- Notice the path used to the next component is relative to this component. NOT the home page! --<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id=<span class="ni">&quot;</span>widget<span class="ni">&quot;</span> wicket:preview=<span class="ni">&quot;</span>../widget/CoolWidget.html<span class="ni">&quot;&gt;</span>
widget goes here...
<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
</code></pre></div></div>
<h3 id="mysitewidgetcoolwidgethtml">mysite/widget/CoolWidget.html</h3>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code>WOW!
</code></pre></div></div>
<p>Using this setup, how exactly can multiple levels of components be previewed? The path from the Home template to the Login template is straight forward, but the path from the Login template to the CoolWidget is relative to the Login template, not the Home page!</p>
<p>I’ve reworked the wicket-preview-behaviour.js to support this setup by recursively including the components. Each time an element is included as a preview, It’s path to the included component is saved and tacked onto any included components that need to be previewed. I’m no javascript expert, but the code didn’t turn out too bad!</p>
<h3 id="wicket-preview-behaviourjs">wicket-preview-behaviour.js</h3>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">dojo</span><span class="p">.</span><span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">dojo.io.*</span><span class="dl">""</span><span class="s2">);
function insertPreview(element, url) {
dojo.io.bind({
url: url,
load: function(type, data, evt) {
if (url.indexOf('/') != -1) {
var path = url.substring(0, url.lastIndexOf('/') + 1);
//add path to current component to next preview object
data = data.replace('wicket:preview=</span><span class="se">\"</span><span class="s2">/g, </span><span class="dl">"</span><span class="nx">wicket</span><span class="p">:</span><span class="nx">preview</span><span class="o">=</span><span class="err">\</span><span class="dl">""</span> <span class="o">+</span> <span class="nx">path</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">element</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="nx">data</span><span class="p">;</span>
<span class="c1">//remove attribute to prevent infinite recursion</span>
<span class="nx">element</span><span class="p">.</span><span class="nx">removeAttribute</span><span class="p">(</span><span class="dl">'</span><span class="s1">wicket:preview</span><span class="dl">'</span><span class="p">);</span>
<span class="c1">//apply rules to newly included components</span>
<span class="nx">Behaviour</span><span class="p">.</span><span class="nx">apply</span><span class="p">();</span>
<span class="p">},</span>
<span class="nx">mimetype</span><span class="p">:</span> <span class="dl">"</span><span class="s2">text/plain</span><span class="dl">"</span>
<span class="p">});</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">myrules</span> <span class="o">=</span> <span class="p">{</span>
<span class="dl">'</span><span class="s1">div</span><span class="dl">'</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">url</span> <span class="o">=</span> <span class="nx">element</span><span class="p">.</span><span class="nx">getAttribute</span><span class="p">(</span><span class="dl">'</span><span class="s1">wicket:preview</span><span class="dl">'</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">url</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">insertPreview</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">url</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="nx">Behaviour</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="nx">myrules</span><span class="p">);</span>
</code></pre></div></div>
<p>My favorite part of this feature is that developers don’t need to change any of their HTML templates in order for this to work. All you need to do is drop in the updated javascript file, and it “just works”. I think that would be valuable for the div preview to have some special CSS style, but that can be handled later. Maybe someone with better UI abilities can give feedback on what would be appropriate.</p>
<p>Are there any other outstanding issues that Wicket developers/users can think of?</p>
Wicket Preview With One Javascript2006-03-10T00:00:00+00:00https://codecrate.com/2006/03/wicket-preview-with-one-javascript<p>Third times the charm, right? There’s still a few improvements I would like to make to the wicket:preview feature, but here’s how I got it to work with a single javascript include.</p>
<p>Here’s an example of the new page with only one javascript include.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>html<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>title<span class="ni">&gt;</span>Offline Preview With One Javascript<span class="ni">&lt;</span>/title<span class="ni">&gt;</span>
<span class="ni">&lt;</span>wicket:remove<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;</span> src=<span class="ni">&quot;</span>wicket-preview.js<span class="ni">&quot;&gt;&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/wicket:remove<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id=<span class="ni">&quot;</span>loginForm<span class="ni">&quot;</span> wicket:preview=<span class="ni">&quot;</span>Login.html<span class="ni">&quot;&gt;</span>Text should be replaced<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>The wicket-preview.js file has changed quite a bit. It is now essentially just a “bootstrapping” script, to load all the other javascript files. It is _heavily_influenced by the <a href="http://script.aculo.us/">scriptaculous</a> bootstrapping code, but I had to change a few things here and there to make it more understandable for me. I’m not a big fan of the excessive method chaining that they were using, and I’m not too familiar with some of the prototype syntax either. All of the other work has been pushed to wicket-preview-behaviour.js</p>
<p>One <em>very_important thing to remember, is that the bootstrapping javascript cannot reference any of the included functions. I got stuck on this for a couple hours by trying to bootstrap _and</em> reference the Behaviour objects in the same place. Oh well, I guess you live and learn…</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">WicketPreview</span> <span class="o">=</span> <span class="p">{</span>
<span class="na">require</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">libraryName</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// inserting via DOM fails in Safari 2.0, so brute force approach</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="dl">'</span><span class="s1">&lt;script type="text/javascript" src="</span><span class="dl">'</span> <span class="o">+</span> <span class="nx">libraryName</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">"&gt;&lt;/script&gt;</span><span class="dl">'</span><span class="p">);</span>
<span class="p">},</span>
<span class="na">findJavascriptPath</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">scripts</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByTagName</span><span class="p">(</span><span class="dl">"</span><span class="s2">script</span><span class="dl">"</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">x</span> <span class="o">&</span><span class="nx">lt</span><span class="p">;</span> <span class="nx">scripts</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">x</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">s</span> <span class="o">=</span> <span class="nx">scripts</span><span class="p">[</span><span class="nx">x</span><span class="p">];</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">s</span><span class="p">.</span><span class="nx">src</span> <span class="o">&&</span> <span class="nx">s</span><span class="p">.</span><span class="nx">src</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/wicket-preview</span><span class="se">\.</span><span class="sr">js</span><span class="se">(\?</span><span class="sr">.*</span><span class="se">)?</span><span class="sr">$/</span><span class="p">))</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">s</span><span class="p">.</span><span class="nx">src</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="sr">/wicket-preview</span><span class="se">\.</span><span class="sr">js</span><span class="se">(\?</span><span class="sr">.*</span><span class="se">)?</span><span class="sr">$/</span><span class="p">,</span><span class="dl">''</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">},</span>
<span class="na">load</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">path</span> <span class="o">=</span> <span class="nx">WicketPreview</span><span class="p">.</span><span class="nx">findJavascriptPath</span><span class="p">();</span>
<span class="kd">var</span> <span class="nx">includes</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">behaviour,dojo,wicket-preview-behaviour</span><span class="dl">'</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="dl">'</span><span class="s1">,</span><span class="dl">'</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">x</span> <span class="o">&</span><span class="nx">lt</span><span class="p">;</span> <span class="nx">includes</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">x</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">include</span> <span class="o">=</span> <span class="nx">includes</span><span class="p">[</span><span class="nx">x</span><span class="p">];</span>
<span class="nx">WicketPreview</span><span class="p">.</span><span class="nx">require</span><span class="p">(</span><span class="nx">path</span> <span class="o">+</span> <span class="nx">include</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">.js</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nx">WicketPreview</span><span class="p">.</span><span class="nx">load</span><span class="p">();</span>
</code></pre></div></div>
<p>The wicket-preview-behaviour.js file is the same as <a href="/2006/03/auto-previewable-wicket-pages.html">my previous blog</a>. I just had to move the code into a new file to avoid conflicting with the bootstrapping code.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">myrules</span> <span class="o">=</span> <span class="p">{</span>
<span class="dl">'</span><span class="s1">div</span><span class="dl">'</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">url</span> <span class="o">=</span> <span class="nx">element</span><span class="p">.</span><span class="nx">getAttribute</span><span class="p">(</span><span class="dl">'</span><span class="s1">wicket:preview</span><span class="dl">'</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">url</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">dojo</span><span class="p">.</span><span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">dojo.io.*</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">dojo</span><span class="p">.</span><span class="nx">io</span><span class="p">.</span><span class="nx">bind</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="nx">url</span><span class="p">,</span>
<span class="na">load</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">type</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">evt</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">element</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="nx">data</span><span class="p">;</span>
<span class="p">},</span>
<span class="na">mimetype</span><span class="p">:</span> <span class="dl">"</span><span class="s2">text/plain</span><span class="dl">"</span>
<span class="p">});</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="nx">Behaviour</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="nx">myrules</span><span class="p">);</span>
</code></pre></div></div>
<p>I’m becoming more convinced that this is a killer feature. I have opened a <a href="https://sourceforge.net/tracker/index.php?func=detail&aid=1445715&group_id=119783&atid=684978">request for this feature to be integrated directly into Wicket</a>, but there’s been no movement on it yet. If anyone out there thinks this would be useful, please show your support on the Wicket mailing list or directly in the sourceforge issue I opened.</p>
<p>I think this pretty much sums out the outstanding work in order for this feature to be moved into the Wicket core.</p>
<ol>
<li>
<p>Documentation. Maybe add to the wicket examples or some other visible demo?</p>
</li>
<li>
<p>Add wicket:previewto the official Wicket DTD. The wicket:idattribute is already there, and adding wicket:previewto the DTD will allow designers to create valid XHTML.</p>
</li>
<li>
<p>Optionally remove the wicket:previewattributes at runtime. Wicket has a setting to automatically remove the wicket:idattribute at runtime, and it should be able to support this as well. It might already handle wicket:*, I don’t really know about this one.</p>
</li>
</ol>
<p>My next feat will be to improve this feature to try and handle multiple levels of component inheritance. That should be quite a trick!</p>
Auto Previewable Wicket Pages2006-03-03T00:00:00+00:00https://codecrate.com/2006/03/auto-previewable-wicket-pages<p>Previewable Wicket pages, take two…</p>
<p>My <a href="http://jroller.com/page/wireframe/?anchor=previewable_wicket_pages">previous blog</a> started the ball rolling with previewable Wicket pages, and it’s definately worth spending some more time in this area. I would really like to remove the excessive amount of javascript, and make it easier to use out of the box. After brainstorming and debating with a friend for the cleanest solution, we decided to follow Wicket’s lead and use a custom namespaced html attribute called wicket:preview.</p>
<p>Wicket already uses namespaced attributes for declaring Wicket specific functionality, so this solution feels like a natural fit. Just point the wicket:preview attribute to any url (relative or absolute) and that url’s contents will automatically be inserted into your preview page. The wicket:remove tags are used just to make sure this offline preview magic does not interfere with Wicket during runtime.</p>
<p>Here’s a quick demo of how it looks now!</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>html<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>title<span class="ni">&gt;</span>Slick Offline Wicket Page Preview <span class="ni">&lt;</span>/title<span class="ni">&gt;</span>
<span class="ni">&lt;</span>wicket:remove<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;</span> src=<span class="ni">&quot;</span>behaviour.js<span class="ni">&quot;&gt;&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;</span> src=<span class="ni">&quot;</span>dojo.js<span class="ni">&quot;&gt;&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;</span> src=<span class="ni">&quot;</span>wicket-preview.js<span class="ni">&quot;&gt;&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/wicket:remove<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id=<span class="ni">&quot;</span>loginForm<span class="ni">&quot;</span> wicket:preview=<span class="ni">&quot;</span>Login.html<span class="ni">&quot;&gt;</span>Text should be replaced<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>The wicket-preview.js is pretty simple. It uses <a href="http://dojotoolkit.org/">dojo</a> in the same way as my previous demo, and uses the <a href="bennolan.com/behaviour/">Behaviour javascript library</a> to automatically parse out the wicket:preview attribute and swap in the included file contents. The implementation is maybe a bit basic, but that can be improved later. It seems like the majority of included components use a div tag, but it probably should support the span tag as well.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">myrules</span> <span class="o">=</span> <span class="p">{</span>
<span class="dl">'</span><span class="s1">div</span><span class="dl">'</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">url</span> <span class="o">=</span> <span class="nx">element</span><span class="p">.</span><span class="nx">getAttribute</span><span class="p">(</span><span class="dl">'</span><span class="s1">wicket:preview</span><span class="dl">'</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">url</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">dojo</span><span class="p">.</span><span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">dojo.io.*</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">dojo</span><span class="p">.</span><span class="nx">io</span><span class="p">.</span><span class="nx">bind</span><span class="p">({</span>
<span class="na">url</span><span class="p">:</span> <span class="nx">url</span><span class="p">,</span>
<span class="na">load</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">type</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">evt</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">element</span><span class="p">.</span><span class="nx">innerHTML</span> <span class="o">=</span> <span class="nx">data</span><span class="p">;</span>
<span class="p">},</span>
<span class="na">mimetype</span><span class="p">:</span> <span class="dl">"</span><span class="s2">text/plain</span><span class="dl">"</span>
<span class="p">});</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="nx">Behaviour</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="nx">myrules</span><span class="p">);</span>
</code></pre></div></div>
<p>One outstanding issue is that this solution doesn’t support multiple levels of components (ex: pages including components which include other components). That’s not really a big deal, but I’m open to suggestions if there’s something that can be done to support it.</p>
<p>It would also be a nice improvement to only require user’s to import one javascript file. I think there’s some way to have javascript include other javascript, but I don’t know much about it. I think scriptaculous does something like this, so maybe I’ll dig into that later…</p>
<p>Now, I’d like to present this feature to the core Wicket developers to get feedback. I’d love to contribute this and work with them to integrate this functionality directly into Wicket. This could be yet another notch on Wicket’s belt, and improve it’s status as one of the best web frameworks out there. We’ll see where this goes from here!</p>
Previewable Wicket Pages2006-03-02T00:00:00+00:00https://codecrate.com/2006/03/previewable-wicket-pages<p>One of my favorite features of <a href="http://wicketframework.org">Wicket</a> is the ability to preview a dynamic page without nasty embedded scriptlets or JSP custom tags. I believe <a href="http://jakarta.apache.org/tapestry/">Tapestry</a> also has previewable pages since it works quite similar to Wicket.</p>
<p>Even the “holy grail”, <a href="http://www.rubyonrails.org/">Ruby on Rails</a>, is no better than JSP for previewable web pages, which I find interesting since <a href="http://www.37signals.com">37signals</a> is such an advocate of <a href="http://www.37signals.com/svn/archives/001050.php">working directly with the actual UI and not with mock ups</a>. You would think they’d be frothing at the mouth for completely clickable UI’s from day one.</p>
<p>Wicket is a “component framework”, which means you can extract pieces of your page into reusable pieces. This has huge benefits for building applications quickly, and it truely is the only way to achieve Object Oriented web development. There is a downside to building reusable components though. Once you start extracting common pieces of your page into components, you lose previewability again. The good news is that I think this is a fixable problem.</p>
<p>Here’s an example where my test page has extracted out the login widget into a seperate component. Essentially, my page preview just went in the toilet…</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>!DOCTYPE html PUBLIC <span class="ni">&quot;</span>-//W3C//DTD XHTML 1.0 Strict//EN<span class="ni">&quot;</span>
<span class="ni">&quot;</span>http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd<span class="ni">&quot;&gt;</span>
<span class="ni">&lt;</span>html<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>title<span class="ni">&gt;</span>Lame Non-Previewable Page<span class="ni">&lt;</span>/title<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div id=<span class="ni">&quot;</span>login<span class="ni">&quot;&gt;</span>Text should be replaced<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Now, with just a bit of AJAX magic, I can preview my test page and have the browser dynamically pull in my extracted component. I’ve used <a href="http://script.aculo.us/">scriptaculous</a> for this kind of Javascript before, but this time I decided to give the <a href="http://dojotoolkit.org/">dojo toolkit</a> a try.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>!DOCTYPE html PUBLIC <span class="ni">&quot;</span>-//W3C//DTD XHTML 1.0 Strict//EN<span class="ni">&quot;</span>
<span class="ni">&quot;</span>http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd<span class="ni">&quot;&gt;</span>
<span class="ni">&lt;</span>html<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>title<span class="ni">&gt;</span>Snazzy Dynamic Include<span class="ni">&lt;</span>/title<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;</span> src=<span class="ni">&quot;</span>dojo.js<span class="ni">&quot;&gt;&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>script language=<span class="ni">&quot;</span>JavaScript<span class="ni">&quot;</span> type=<span class="ni">&quot;</span>text/javascript<span class="ni">&quot;&gt;</span>
dojo.require(<span class="ni">&quot;</span>dojo.io.*<span class="ni">&quot;</span>);
dojo.io.bind({
url: <span class="ni">&quot;</span>Login.html<span class="ni">&quot;</span>,
load: function(type, data, evt) {
document.getElementById(<span class="ni">&quot;</span>testInclude<span class="ni">&quot;</span>).innerHTML = data;
},
mimetype: <span class="ni">&quot;</span>text/plain<span class="ni">&quot;</span>
});
<span class="ni">&lt;</span>/script<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div id=<span class="ni">&quot;</span>login<span class="ni">&quot;&gt;</span>Text should be replaced<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>This is a pretty slick little example on how to get previewable pages for Wicket. I’ll try to put together another post soon to bring this concept to the next level.</p>
Spring-RCP/JTaskPane Promoted To L2FProd2006-02-20T00:00:00+00:00https://codecrate.com/2006/02/spring-rcpjtaskpane-promoted-to-l2fprod<p>The common Swing components created by <a href="http://common.l2fprod.com">l2fprod.com</a> just accepted the code I wrote recently to <a href="/2006/01/integrate-jtaskpane-with-spring-rcp.html">integrate Spring-RCP with JTaskPane</a>.</p>
<p>I was <a href="http://forum.springframework.org/showthread.php?t=21867">contacted last week by Frederic</a>, the core developer for the l2fprod project, to try and collaborate on the spring-rcp integration. All of my code was written under the ASL 2.0 license, so he was able to <a href="https://l2fprod-common.dev.java.net/source/browse/l2fprod-common/src/java/springrcp/com/l2fprod/common/springrcp/">migrate my code directly into his project</a> really quickly.</p>
<p>Since Frederic is much more knowledgable about the JTaskPane component, he was able to add a few new features as well. He also published a <a href="http://common.l2fprod.com/articles/taskpane-springrcp.php">new tutorial on how to use the components</a>, which should be a big help to get people up and going.</p>
<p>Last night, I pulled down the <a href="http://common.l2fprod.com/download.php">newest snapshot</a> of the common l2fprod components, and integrated it into <a href="http://shard.codecrate.com">shard</a>. I only had to change the class imports and the spring xml file to use the new components. It was almost too easy…</p>
<p>This is a big win in my book. I removed my custom code, and having it published by the l2fprod project, there’s a much greater chance that others will use this code. It just goes to show how powerful opensource development can really be.</p>
No Need For Flock2006-02-06T00:00:00+00:00https://codecrate.com/2006/02/no-need-for-flock<p>Imagine that. Just weeks after <a href="/2005/11/flock-rocks.html">raving how great Flock was</a>, I’m back to browsing with “good old” Firefox. Of course, I’ve installed a couple of plugins to give me an equivalent suite of features. Here’s how to “pimp your Firefox” to make Flock nearly obsolete:</p>
<ul>
<li>The <a href="http://performancing.com/firefox">performancing firefox plugin</a>is a very impressive plugin and has great integration with blogging platforms.</li>
<li><a href="http://dietrich.ganx4.com/foxylicious/">foxylicious</a>is another must have plugin that actually has better <a href="http://del.icio.us">delicious</a>integration than Flock.</li>
</ul>
<p>I think Flock’s direction is nobel (or is it just novel?). The internet community could use a distribution of firefox that was pre-packaged with useful internet/blogging tools.</p>
Integrate JTaskPane With Spring-RCP2006-01-29T00:00:00+00:00https://codecrate.com/2006/01/integrate-jtaskpane-with-spring-rcp<p>After my <a href="/2006/01/contextual-tasks.html">previous endevour integrating contextual tasks into shard</a>, I wanted to take a step back and see if there was room for improvement.</p>
<p>One glaring issue with my original implementation was that it was very “un-spring like”. I built my context page by hand and I wasn’t able to use the helper objects that Spring-RCP exposes to generate UI specific command objects like button groups, menu objects or popups. For example:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">CommandGroup</span> <span class="n">group</span> <span class="o">=</span> <span class="n">getWindowCommandManager</span><span class="o">().</span><span class="na">getCommandGroup</span><span class="o">(</span><span class="s">"popUp"</span><span class="o">);</span>
<span class="n">group</span><span class="o">.</span><span class="na">createPopupMenu</span><span class="o">();</span>
</code></pre></div></div>
<p>I wanted to build my context pane in the same way so that I could add/remove actions to the context pane without changing my Java code. I also wanted to enhance spring-rcp to add a new “helper” method to build the task pane for me. Something along the lines of:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">CommandGroup</span> <span class="n">group</span> <span class="o">=</span> <span class="n">getWindowCommandManager</span><span class="o">().</span><span class="na">getCommandGroup</span><span class="o">(</span><span class="s">"contextTasks"</span><span class="o">);</span>
<span class="n">group</span><span class="o">.</span><span class="na">createTaskPane</span><span class="o">();</span>
</code></pre></div></div>
<p>Trying to accomplish this enhancement was not nearly as easy as I expected. It was extremely difficult to inject this behavior into spring-rcp, and the implementation is not for the faint of heart. =) It’s unfortunate that the behavior to generate these swing components is so coupled to the implementation. It would be better if the CommandGroup registered different handlers for what Swing components it could generate. That would allow for easier extension of what Swing components spring-rcp supported. A new API could be created that might look something like:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">CommandGroup</span> <span class="n">group</span> <span class="o">=</span> <span class="n">getWindowCommandManager</span><span class="o">().</span><span class="na">getCommandGroup</span><span class="o">(</span><span class="s">"contextTasks"</span><span class="o">);</span>
<span class="n">group</span><span class="o">.</span><span class="na">createSwingComponent</span><span class="o">(</span><span class="nc">JMenuBar</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
</code></pre></div></div>
<p>I won’t go into the hairy details of how I got it all to work right now. If anyone is interested, you can checkout the code from <a href="http://shard.codecrate.com">shard</a>, or drop me a line and I’d be glad to go over it with you. After all of my work was done, here’s all that’s needed now to build a fully configurable task pane that’s wired from spring-rcp!</p>
<p>command-context.xml</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>bean id="contextTasks"
class="com.codecrate.shard.ui.command.task.TaskPaneFactoryBean"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>property name="members"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>list<span class="ni">&gt;</span>
<span class="ni">&lt;</span>ref bean="commonTasks" /<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/list<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/property<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
<span class="ni">&lt;</span>bean id="commonTasks"
class="com.codecrate.shard.ui.command.task.TaskPaneGroupFactoryBean"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>property name="members"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>list<span class="ni">&gt;</span>
<span class="ni">&lt;</span>value<span class="ni">&gt;</span>newCommand<span class="ni">&lt;</span>/value<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/list<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/property<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/bean<span class="ni">&gt;</span>
</code></pre></div></div>
<p>MyObjectView.java</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">TaskPaneCommandGroup</span> <span class="n">tasks</span> <span class="o">=</span> <span class="o">(</span><span class="nc">TaskPaneCommandGroup</span><span class="o">)</span> <span class="n">getWindowCommandManager</span><span class="o">().</span><span class="na">getCommandGroup</span><span class="o">(</span><span class="s">"contextTasks"</span><span class="o">);</span>
<span class="n">tasks</span><span class="o">.</span><span class="na">createTaskPane</span><span class="o">();</span>
</code></pre></div></div>
<p>I wonder if other spring-rcp users have built similar extensions? I don’t think this code could be pushed into spring-rcp since they shy away from including widgets into the core framework, but maybe this code should be hosted somewhere else? Seems kindof similar to the <a href="https://jide-springrcp.dev.java.net/">Spring-RCP/Flexdock integration project</a>.</p>
Seperate Artifacts For Seperate Dependencies2006-01-23T00:00:00+00:00https://codecrate.com/2006/01/seperate-artifacts-for-seperate<p><a href="http://maven.apache.org">Maven2</a> is a definate step up from Maven1, but some of the “must have features” (ie: transitive dependencies), are not as fleshed out as they need to be. If Maven2 hopes to de-throne <a href="http://ant.apache.org">Ant</a> and become the de-facto project management tool, transitive dependencies need to be re-addressed ASAP.</p>
<p>If I were to pick a “home run” example of where transitive dependencies could really be an advantage, it would be when starting a new project using <a href="http://springframework.org">Spring</a>. If I were a new user, I would expect to only have to specify the pieces I need, and the rest should be provided for me. My pom should contain as little as this:</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>dependency<span class="ni">&gt;</span>
<span class="ni">&lt;</span>groupId<span class="ni">&gt;</span>org.springframework<span class="ni">&lt;</span>/groupId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>artifactId<span class="ni">&gt;</span>spring-orm<span class="ni">&lt;</span>/artifactId<span class="ni">&gt;</span>
<span class="ni">&lt;</span>version<span class="ni">&gt;</span>1.2.5<span class="ni">&lt;</span>/version<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/dependency<span class="ni">&gt;</span>
</code></pre></div></div>
<p>Sadly, things are not this way…yet. One of the main problems, is the introduction of the dependency attribute. This lack-luster feature allows for frameworks to publish their artifacts with an ungodly number of dependencies, and force unknowing developers that use their framework to specify what pieces they don’t want.</p>
<p>Spring-ORM is the perfect example of this flaw. Why in the world do I have to specify <a href="https://shard.dev.java.net/source/browse/shard/shard-hibernate/pom.xml?rev=1.21&view=auto&content-type=text/vnd.viewcvs-markup">over 20 dependency excludes</a> just to get started with my project!?! Sure, Spring-ORM is packaged as one massive jar, but I highly doubt there are developers that use <a href="http://www.ibiblio.org/maven2/org/springframework/spring-orm/1.2.6/spring-orm-1.2.6.pom">Hibernate2, AND Hibernate3, AND JDO, AND Toplink, AND EJB’s</a>. What’s so difficult about exposing different POM’s for different sets of dependencies? Maven2 allows for projects to publish POM’s, and this seems to fit perfectly. Ideally, there should be a Spring-ORM-Hibernate dependency that only has the things I need. Then there’s no need for this whole “excludes” feature.</p>
<p>Now that Maven2 is getting some “real world” use, these issues need to be brought to the forefront and addressed so that transitive dependencies will hopefully be useful again.</p>
Fun With Drag and Drop2006-01-20T00:00:00+00:00https://codecrate.com/2006/01/fun-with-drag-and-drop<p>It’s amazing how the little things can really make a difference for an application. I found myself becoming annoyed when I had to import a PCGen dataset because the Java file chooser would forget the directory location after every restart of the application. I usually have a file browser open with the PCGen files anyways, and that’s when the lightbulb came on. Now, instead of having to continually navigate with the crappy Java file chooser, I can just drag and drop the PCGen dataset I’m working with right into shard. The implementation was pretty easy, and it adds an extra bit of polish to the application.</p>
<p>The one problem I had while implementing this new feature was that drag/drop is not supported on all operating systems the same way. So much for Write Once, Run Anywhere. =) There is a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4899516">documented bug that’s been around since JDK 1.4 that Sun has not fixed that prevents Linux applications from handling drag/drop of files the same as other operating systems</a>. The <a href="http://www.javadesktop.org/forums/thread.jspa?messageID=128233">work around</a> is not difficult, and it’s not much of a “hack” either. It’s more of an inconvenience and frustration point. It took me about 2 hours to figure out why the standard drag/drop tutorials from Sun was not working in my application. I don’t know how Sun can let these issues slide through the cracks…</p>
<p>Sometimes Swing programming is more fun than web programming. Sometimes it’s not. <a href="/2005/09/wicket-dragdrop-components.html">Drag and drop with wicket</a> was a blast, while drag and drop for Swing has kindof left a bad taste in my mouth.</p>
Contextual Tasks2006-01-19T00:00:00+00:00https://codecrate.com/2006/01/contextual-tasks<p>Admit it, whether you’re building a web based or a client application, building good GUI’s is hard. I don’t care if you’re using a visual tool, or building them by hand, it’s hard to build a user interface that is “user friendly”. I haven’t delved too much into the area of Application Usability, but I have picked up a few tricks here to help me build usable UI’s.</p>
<p>Using contextual tasks is one way to present users with only “meaningful operations” when they need them. Windows XP popularized this technique with their file explorer by showing particular actions based on what the user had selected (ex: “Burn CD”, “Move Files”, etc). I only wish Microsoft wouldn’t have been the one to popularize these contextual tasks…oh well.</p>
<p>Based on user feedback, I’ve integrated contextual tasks into <a href="http://shard.codecrate.com">shard</a> to help users choose actions relevent to specific operations. The feedback I received was great, and it seemed like user’s were genuinely confused about what they were supposed to do with the application. Hopefully, these contextual tasks will be a step in the right direction to help alleviate user confusion.</p>
<p>The Apache licensed <a href="http://common.l2fprod.com/index.php">common components from l2fprod</a> has an excellent JTaskPane, and seemed like the obvious choise at first. Once I started digging into the l2fprod documentation though, several critical questions came up that have me wondering if it’s really what I should be using.</p>
<p>First, “Where does the definitive JTaskPane live, and who’s working on it?” <a href="http://www.jroller.com/page/l2fprod/?anchor=r_i_p_jtaskpanegroup_hello">Pieces of the common l2fprod library have been integrated into SwingX</a>, and <a href="https://jdnc-incubator.dev.java.net/documentation/l2fprod/">JDNC also has its own copy of the JTaskPane</a>. So, which is the “true” JTaskPane? SwingX and JDNC require JDK 1.5, and I hope the JTaskPane can remain compatible with JDK 1.4! What’s truly baffling though, is that between these three projects, there is no official release of the component.</p>
<p>There’s also the outstanding question of whether or not this code is still under development. There are <a href="https://jdnc-incubator.dev.java.net/documentation/l2fprod/JTaskPaneGroup-plans.html">several missing features</a>; the most obvious of which is that the JTaskPane does not integrate with custom look and feels!</p>
Template Versus Strategy Pattern2006-01-05T00:00:00+00:00https://codecrate.com/2006/01/template-versus-strategy-pattern<p>Are you ready for a design pattern throw down?</p>
<p>I’ve been involved with a development reading group for the <a href="http://www.oreilly.com/catalog/hfdesignpat/">Head First Design Patterns</a> book. Overall, it’s a really good book, and last night there was some interesting debate comparing the Template and Strategy patterns. Both pattern’s intent is to push unique behavior into seperate objects. My argument was that the Template pattern should be banished to the dark side of the moon since it forces use of class inheritance instead of object composition.</p>
<p>The template pattern defines the “hook” template methods for subclasses as protected. That means that in order to unit test the unique behavior, you have to test the main public entry point, which may have a considerable amount of setup/teardown overhead. This makes testing what really matters more difficult than it should be.</p>
<p>Here’s a simple example using Java psuedocode. Notice how in order for me to unit test the importObject(String line) method of my extension class, I have to unit test all of the file IO. It’s a bit basic, but if that behavior was promoted to a strategy, you could unit test it without any file system dependencies. Something like LineObjectImporter.importObject(String line) would do just nicely. +1 for testability!</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">AbstractFileImporter</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nc">Collection</span> <span class="nf">importObjects</span><span class="o">(</span><span class="nc">File</span> <span class="n">file</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Collection</span> <span class="n">results</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="nc">InputReader</span> <span class="n">input</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">FileInputReader</span><span class="o">(</span><span class="n">file</span><span class="o">);</span>
<span class="k">while</span> <span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="na">isActive</span><span class="o">())</span> <span class="o">{</span>
<span class="n">results</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">importObject</span><span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="na">getLine</span><span class="o">()));</span>
<span class="o">}</span>
<span class="n">input</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="k">return</span> <span class="n">results</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kd">abstract</span> <span class="nc">Object</span> <span class="nf">importObject</span><span class="o">(</span><span class="nc">String</span> <span class="n">line</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Although I favor the Strategy pattern, there does seem to be a quicker “up and running” time when using the template pattern. There’s just something inherently easy (pun intended) about extending a parent class and only implementing a few methods.</p>
Website Design Guide2006-01-04T00:00:00+00:00https://codecrate.com/2006/01/website-design-guide<p>I have to deal with graphic designers in my real life job and for my <a href="http://www.codecrate.com">side projects</a>. Unfortunately, people put too much faith in these static mockups, so lately I’ve been cautioning clients to not get too caried away with the images the designer slaps together. Granted, I’m no website developer expert, but I have found these guidelines to be true for the most part.</p>
<h3 id="website-design-guidelines">Website Design Guidelines</h3>
<ol>
<li>The graphic design image will never look the same as the website. Once you’ve decided on the graphic design, just throw it away, and consider the website its own entity. Once the website looks</li>
</ol>
<p>good, stop(Even if it doesn’t look exactly like the original layout).</p>
<ol>
<li>
<p>Try to use as few images as possible. see point 5 for more details.</p>
</li>
<li>
<p>Simple and readable sites are more usable than flashy and creative sites.</p>
</li>
<li>
<p>Certain design principles that make good images do not make good websites. Don’t choose a layout simply based on looks. Check if other websites have used a similar layout, and what you thought of it.</p>
</li>
<li>
<p>Favor dynamic content to static content. Web pages and browsers are made to resize and scale. if all your site is composed of text, it scales great; but if it’s hard coded images and banners, you’re stuck.</p>
</li>
</ol>
<p>Now, all of these guidelines get thrown out the window if the client is actually working with live HTML samples. I think <a href="http://www.37signals.com">37signals</a> hit the nail right on the head <a href="http://www.37signals.com/svn/archives/001050.php">by working directly with the actual user interface from the get go</a>.</p>
More Intuitive Search2005-12-08T00:00:00+00:00https://codecrate.com/2005/12/more-intuitive-search<p>One of the coolest features in <a href="http://shard.codecrate.com">shard-phoenix</a> is the quick search. My first version of the quick search was a “Search when you type” implementation where every keypress fired off a search and updated the GUI. Although impressive, it was not exactly usable. Performing a search for every single keypress is simply too expensive, especially on slower PC’s.</p>
<p>What I really wanted was a “Search when you pause” implementation. I wanted the user to type in their query phrase, and fire off the search when they have a delay (300 milliseconds seems to be the magic number). I was fairly surprised at the lack of examples or tutorials to help me accomplish this and that’s why I’m posting my “slimmed down” implementation here. The complete source code can be found as part of the <a href="https://shard.dev.java.net/source/browse/shard/shard-phoenix/src/main/java/com/codecrate/shard/ui/component/">shard-phoenix project</a>.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SearchComponent</span> <span class="kd">extends</span> <span class="nc">JPanel</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">SEARCH_DELAY_MILLIS</span> <span class="o">=</span> <span class="mi">300</span><span class="o">;</span>
<span class="kd">private</span> <span class="nc">JTextField</span> <span class="n">queryText</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
<span class="kd">private</span> <span class="nc">Timer</span> <span class="n">timer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Timer</span><span class="o">();</span>
<span class="kd">public</span> <span class="nf">SearchComponent</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">();</span>
<span class="n">add</span><span class="o">(</span><span class="n">getQueryText</span><span class="o">(),</span> <span class="kc">null</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="nc">JTextField</span> <span class="nf">getQueryText</span><span class="o">()</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">queryText</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
<span class="n">queryText</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">JTextField</span><span class="o">();</span>
<span class="n">queryText</span><span class="o">.</span><span class="na">setColumns</span><span class="o">(</span><span class="mi">10</span><span class="o">);</span>
<span class="n">queryText</span><span class="o">.</span><span class="na">getDocument</span><span class="o">().</span><span class="na">addDocumentListener</span><span class="o">(</span><span class="k">new</span> <span class="nc">SearchDocumentListener</span><span class="o">());</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">queryText</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kd">class</span> <span class="nc">SearchDocumentListener</span> <span class="kd">implements</span> <span class="nc">DocumentListener</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">changedUpdate</span><span class="o">(</span><span class="nc">DocumentEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="n">processEvent</span><span class="o">(</span><span class="n">event</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">insertUpdate</span><span class="o">(</span><span class="nc">DocumentEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="n">processEvent</span><span class="o">(</span><span class="n">event</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">removeUpdate</span><span class="o">(</span><span class="nc">DocumentEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="n">processEvent</span><span class="o">(</span><span class="n">event</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">processEvent</span><span class="o">(</span><span class="nc">DocumentEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Document</span> <span class="n">document</span> <span class="o">=</span> <span class="n">event</span><span class="o">.</span><span class="na">getDocument</span><span class="o">();</span>
<span class="k">try</span> <span class="o">{</span>
<span class="nc">String</span> <span class="n">value</span> <span class="o">=</span> <span class="n">document</span><span class="o">.</span><span class="na">getText</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="n">document</span><span class="o">.</span><span class="na">getLength</span><span class="o">()).</span><span class="na">trim</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="mi">0</span> <span class="o"><</span> <span class="n">value</span><span class="o">.</span><span class="na">length</span><span class="o">())</span> <span class="o">{</span>
<span class="nc">TimerTask</span> <span class="n">delaySearchTask</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DelaySearchTask</span><span class="o">(</span><span class="n">value</span><span class="o">);</span>
<span class="n">timer</span><span class="o">.</span><span class="na">schedule</span><span class="o">(</span><span class="n">delaySearchTask</span><span class="o">,</span> <span class="no">SEARCH_DELAY_MILLIS</span><span class="o">);</span>
<span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
<span class="c1">//clear search filter</span>
<span class="o">}</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">BadLocationException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//print error</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kd">class</span> <span class="nc">DelaySearchTask</span> <span class="kd">extends</span> <span class="nc">TimerTask</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">String</span> <span class="n">originalInput</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">DelaySearchTask</span><span class="o">(</span><span class="nc">String</span> <span class="n">originalInput</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">originalInput</span> <span class="o">=</span> <span class="n">originalInput</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(!</span><span class="n">hasInputChanged</span><span class="o">())</span> <span class="o">{</span>
<span class="c1">//perform search now!</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">boolean</span> <span class="nf">hasInputChanged</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="o">!</span><span class="n">originalInput</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">getQueryText</span><span class="o">().</span><span class="na">getText</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
Value Beyond Being Better2005-12-06T00:00:00+00:00https://codecrate.com/2005/12/value-beyond-being-better<p>Here’s the scenario: project foo is a widely used program that has been around for quite a while. It’s starting to show it’s age, yet people still use it because it’s the unofficial standard (ex: struts, pcgen). A new application, project new,solves many of the shortcomings of project foo (ex: webwork, shard). Why hasn’t project newachieved the sucess of project foo if it’s better than project foo?</p>
<p>I’ve come to the conclusion that a project can not be successful by solely being better. Sure, it’s good for a project to have newer technologies, better architecture, cleaner code, but that’s not why users change to newer applications. If project new proclaims, “Stop using project foo! Use project new because we’re better!”, users will simply sigh and continue using their current application. The bottom line is that if you want users to start using project new, you need to also support project foo<img src="http://www.openoffice.org" alt="OpenOffice" /> is a good example of this. The majority of people don’t start using OpenOffice simply because it’s “better”. They take the OpenOffice plunge once they feel comfortable that OpenOffice will still support their existing Microsoft Word documents.</p>
<p>This has been particularly relevant to me, as I try to figure out how to make <a href="http://shard.codecrate.com">shard</a> a successful open source project. <a href="http://pcgen.sf.net">PCGen</a> is currently the “top dog” when it comes to d20 applications, and user’s aren’t going to migrate to shard simply because it’s better. Shard has many significant improvements over PCGen (database support, simple user interface, etc), but that alone is not going to convert users. What is really needed is for shard to help users migrate from PCGen quickly and easily. The next version of shard will officially support importing PCGen datasets into shard. An experimental import of <a href="http://www.d20srd.org">SRD skills</a> is already up and running, so it won’t be long before shard supports the rest of PCGen’s LST files.</p>
Flock Rocks2005-11-30T00:00:00+00:00https://codecrate.com/2005/11/flock-rocks<p><a href="http://www.flock.com">Flock</a> has the potential to be one of the coolest applications of 2006. This is assuming, of course, a final release gets out the door next year. I tried out their <a href="http://downloads.flock.com/?product=flock-0.4.10&os=win">first developer preview release</a>, but some major issues left it pretty useless to me.</p>
<p>Yesterday, I tried out <a href="http://tinderbox.flock.com/builds/">the latest snapshot build</a>, and I’m very impressed with how far the application has come. For those of you that haven’t heard of Flock, it’s a new browser built on top of <a href="http://www.mozilla.com/firefox/">firefox</a> and has some features that have really pulled me in:</p>
<ul>
<li>Tight integration with external services (<a href="http://del.icio.us">delicious</a>, <a href="http://www.flickr.com">flickr</a>, most blogging software)</li>
<li>
<p>Search toolbar automatically searches recently viewed pages. Very Google Desktop like, but why in the world is the default search engine Yahoo?!</p>
</li>
<li>Flock makes all of these “geek tools” extremely easy to use. I would <em>almost</em> recommend this browser to my techno-phobic parents!</li>
</ul>
<p>There are still a few areas that I think could use improvements, especially the blogging client. Flock wasn’t able to automatically configure <a href="http://www.jroller.com/page/wireframe">my jroller blog</a>, and it also published my blog with an empty title.</p>
<p>Flock has also replaced the very intuitive firefox “side bar” with the notion of a “top bar”. I think this is a big mistake. This new top bar makes it even more confusing for users to differentiate the browser tools (navigation bar, url, buttons) from web page content. Viewing bookmarks in firefox, using <a href="http://dietrich.ganx4.com/foxylicious/">the sweet foxilicious plug in</a>, is much less intrusive than how Flock only displays bookmarks in a separate tab. I think several of Flock’s flagship tools would be better off utilizing the side bar feature that has worked so well for firefox (shelf, flickr photo uploading, blogging tools).</p>
<p>Flock has taken a fresh approach to many tried and true browser concepts, such as bookmarks. First and foremost, I think it’s time to rethink the concept of a browser download manager. Why hasn’t <a href="http://www.theregister.co.uk/2005/07/07/opera_does_bittorrent/">bittorrent been integrated into any major browser</a>? Flock has been titled the “social browser”, and bittorrent seems to be a perfect fit. </p>
<p>NOTE: This blog was created and published using Flock’s built in blogging client. (very cool!)</p>
Shard: A Call For Support2005-11-14T00:00:00+00:00https://codecrate.com/2005/11/shard-call-for-support<p>I recently received some very critical, yet crucial, feedback on my managing of <a href="http://shard.codecrate.com">the shard project</a>. I’d like to take the time to try and respond to that criticism, and it’s probably a good thing for me to justify my decisions.</p>
<p>Maven doesn’t float everyone’s boat. I admit that it’s usually a Love or Hate relationship, but at the end of the day, its is just another build tool. If ant could be used to build a project like shard with as much ease as maven, I’m all for it. That being said, I have yet to see anything provide the ease of building and publishing multiple artifacts the way maven does. Want to use Ant instead of Maven? Patches are welcome…</p>
<p>The infrequent releases are a direct response to the limited amount of support for the project, and my limited amount of time to devote to the project. I have come to the very important realization that you can not build out a framework without knowing what clients need from the API, and I have yet to hear from users what they need from a d20 API. With the exception of the Shard Toolset (character generator and dataset manager), there are no known consumers of the shard API requiring me to perform releases. I’m a firm believer in “release early, release often”, but right now I “release early and often” for my own use.</p>
<p>It may seem like my focus for shard has shifted over time (hibernate, spring-rcp, lucene, etc), but it has always been focused on what I have needed. My gaming group recently took the time to go through all of our d20 books and log all of the skills/feats. Over 400 feats were saved in excel, and I found it extremely important to be able to import the bulk datasets into shard without manually re-entering all of that data. My original focus was on the core character API, but for the time being it has been pushed to dataset management.</p>
<p>If there’s anything of value in the shard project, it’s the goal of creating a common set of d20 building blocks. I want to highly encourage anyone considering rolling their own d20 tools to try to leverage what’s currently available in shard. If there are pieces lacking for what you are trying to build (which I am sure there are), let’s work together to build that functionality into shard. This way, future d20 applications and tools can be built quickly and easily to benefit the whole gaming community.</p>
Maven2 Delivers2005-11-11T00:00:00+00:00https://codecrate.com/2005/11/maven2-delivers<p>First of all, I need to compliment the <a href="http://maven.apache.org">Maven2</a> developers for delivering an amazing plugin architecture. I have recently been spending a good deal of time migrating our current Ant build to Maven2. We have a good deal of custom work done in our current build, so it’s no trivial task. WSDL2Java and JDO bytecode enhancement are two major pieces that we need to support with Maven2, and it only took a couple hours to get these features working. Building custom Mojos was very straightforward, and I welcome the ability to program a plugin in straight Java. No XML or Jelly scripting required. Not bad!</p>
<p>I’d like to move <a href="http://shard.codecrate.com">Shard</a> to use Maven2 as soon as possible, but there’s no webstart deployment support yet. Since the Maven2 Mojos are so simple to write, I might whip one up and see if it can be contributed back to the Maven community.</p>
Beyond Spring RCP2005-11-11T00:00:00+00:00https://codecrate.com/2005/11/beyond-spring-rcp<p>Good bye Spring RCP. It’s been nice knowing you, and maybe I’ll run into you again sometime later in life…</p>
<p>Last weekend was the first chance I’ve had to work on <a href="http://shard.codecrate.com">shard</a> in quite some time and I thought it might be a good chance to update to <a href="http://maven.codecrate.com/spring-rcp">the most recent snapshot of Spring RCP</a>. After fixing a few compilation errors, the app started up without a problem. Unfortunatly, clicking around the app didn’t fire the action excecutors anymore, and so the app was basically dead in the water.</p>
<p>I think it’s time for me to find an alternative to Spring RCP. I have a limited amount of time to spend working on <a href="http://shard.codecrate.com">my opensource projects</a>, so the time I do have must be spent wisely. Instead of tinkering or troubleshooting issues in an immature framework, I need something dependable. Spring has been a big help for me, and working with Spring RCP was a good learning experience, but I’m just not productive right now.</p>
<p>I’m a bit disapointed with the current state of Spring RCP. The developers have made it very clear that it is still considered alpha, but a 0.1 release was originally planned over a year ago and there are still no public releases or documentation available. I knew what I was getting into by choosing the “bleeding edge”, but I was expecting things to stabalize more quickly than they have. Hell, I used maven a good year before it’s beta release, and it was a much less bumpy ride that this. I guess I’m most frustrated with the fact that Spring RCP is so broad in scope, yet no piece seems to really be rock solid. I would much rather prefer to see a 0.1 release that does a few things really well, than waiting years for every single piece of the framework to shake things out.</p>
<p>Eclipse RCP is one of my top candidates right now, but I have <a href="/2004/07/no-jsr-for-swt.html">my reservations about using SWT</a>. Netbeans also has a RCP framework, but it seems that <a href="http://blogs.sun.com/roller/page/dreamwords/20050328">developing RCP applications with Netbeans has a higher learning curve than Eclipse plugin development</a>.</p>
Javascript AOP2005-10-14T00:00:00+00:00https://codecrate.com/2005/10/javascript-aop<p>Yesterday, I had a truly mind bending experience…</p>
<p>With all of my <a href="http://jroller.com/page/wireframe/?anchor=indicator_while_processing">recent</a><a href="http://jroller.com/page/wireframe/?anchor=new_draggabletarget">work</a><a href="http://jroller.com/page/wireframe/?anchor=wicket_drag_drop_components">using</a><a href="http://jroller.com/page/wireframe/?anchor=choice_is_good">scriptaculous</a>, I never thought there would be a clean way to attach dynamic (AJAX, javascript) functionality to HTML components. I just accepted that the rendered HTML would be “tagsoup” and went on my merry way. Even general concepts like <a href="http://webtips.dan.info/graceful.html">graceful degradation</a> and accesibility didn’t concern me because, “if you don’t want to run a bleeding-edge browser, that’s your problem!” :)</p>
<p>Then, I was introduced to the <a href="http://bennolan.com/behaviour/">behavior</a> javascript library. It’s a javascript library that allows you to dynamically “attach” behavior to HTML elements based on standard CSS selectors. If the user’s browser doesn’t support javascript, the behavior is simply not attached. And all this functionality is supported without writing script blocks within the HTML body. I HIGHLY encourage web 2.0 developers to check this out.</p>
<p>I’ve started updating the wicket scriptaculous package to use behavior. The non-AJAX autocomplete text field is the first component to use behavior, and I’ll try to convert the other components this week. So far, so good!</p>
The Real World2005-10-10T00:00:00+00:00https://codecrate.com/2005/10/real-world<p>I must say that I’m a bit suprised at the number of people who seem genuinely angry because of my previous posts. I could take this opportunity to try to calm people’s fears, or to clarify my opinions. But, what’s the point? How about I just add more wood to the fire?</p>
<p>After I gave my presentation on FIT, I had a number of developers come up and ask me questions about testing (unit, integration, acceptance). Generally, people were very interested and had great suggestions on how to apply testing to their own work. There was one conversation that nearly drove me up a wall, and it went a little something like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>AnotherDeveloper:
Great presentation!
I'm wondering how I can use FIT to test my Spring MVC controllers?
Me:
Ummmm....Spring MVC is a GUI layer, right?
It's extremely difficult to test *any* GUI layer.
But it should be really easy to extract the business logic into
non-GUI specific code and test that.
AnotherDeveloper:
Well ideally, yes we should do that, but this is the "real world".
So, how can I "fix FIT" to create servlet request/response objects?
</code></pre></div></div>
<p>This is just another example of people that just don’t “get it”. I personally <em>guarentee</em> that it would be less work for AnotherDeveloper to extract and test the business logic instead of trying to hack FIT to test their Spring MVC code.</p>
Things I Don't Appreciate2005-10-08T00:00:00+00:00https://codecrate.com/2005/10/things-i-don-appreciate<p>I just made it through one of the worst weeks of my professional career. It’s too bad really. I finished giving a presentation on <a href="http://fit.c2.com/">FIT</a> that went extremely well, but this success was overshadowed by all the other crap going on. I will hopefully post the FIT presentation online sometime soon, once I strip out the company specific material.</p>
<p>I don’t expect anyone reading this to really understand what I mean. I just feel the need to rant for my own sanity.</p>
<p>There are certain facets of my current software development situation that I really don’t appreciate. Here is a short, non complete, list of things I have come to loathe…</p>
<ol>
<li>
<p>I hate that I feel the need to cover my ass and record anyconversation with anyperson regarding anyproject. Project requirements are often ironed out and finalized in informal meetings or conversations, and inevitably, someone along the way will say, “We didn’t sign off on this!” XP software requirements are defined on freaking notecards, and any process that requires more than this is broken!</p>
</li>
<li>
<p>I hate feeling apathetic and not charging forward to make a system better. I’m working on a legacy application with over a million lines of code and thousands of classes that have taken literally hundreds of developers to build. The architecture is extremely procedural and the codebase is littered with bloated utilityclasses. Test coverage is somewhere between 3 to 5 percent. Most functional classes have hundreds of revisions and were built in large part by contractors or developers that are no longer around. With every project I work on, I see the opportunity to refactor procedural logic into small testable units (50 to 85 percent coverage is what I shoot for) without changing the overall business requirements, but what’s the point? Inevitably, <a href="/2005/10/untested-equals-broken.html">someone will be pissed off that you changed their code</a>, and I’m beginning to wonder if refactoring is worth the hassle?</p>
</li>
<li>
<p>I hate militant software development processes. Agile software development requires agile processes. In particular, <a href="/2005/07/actions-speak-louder-than-words.html">I hate code inspections</a>. Having code reviewed by other developers is extremelyimportant, but a formalized meeting has no value and is just a waste of my time.</p>
</li>
</ol>
Untested Equals Broken2005-10-05T00:00:00+00:00https://codecrate.com/2005/10/untested-equals-broken<p>This is an actual email conversation I had today with SomeDeveloper. Am I the only one that finds this ridiculous?</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>SomeDeveloper:
I noticed a lot of the [old functionality] private methods
were removed on one of your previous checkins.
Can we talk about where that functionality went?
Thanks,
SomeDeveloper
Me:
I removed the private methods if they were unused.
The [refactored class] contains any methods
that were only used for [previous functionality].
SomeDeveloper:
I wish you hadn't done that.
I had added them for a reason, and had planned on using them.
</code></pre></div></div>
<p>Unused code is untested code. Untested code is broken code. I’m sorry if there are people out there that have the time to write code that “will be used sometime in the future”. I’m afraid I don’t have the time to waste writing code that’s never used and not needed.</p>
Words of Wisdom2005-09-27T00:00:00+00:00https://codecrate.com/2005/09/words-of-wisdom<p>And now for a short break from my techo blog…</p>
<p>There’s been a lot of talk lately about <a href="http://www.cnn.com/2005/POLITICS/09/27/katrina.brown/index.html">who’s to blame for problems in our world</a>. This constant bickering has pushed me too far, and so I’ve decided to post two simple statements that I constantly run through my head on any given day. If more people would ponder these types of statements, more time would be spent fixing problems instead of bitching about them.</p>
<p>“How are you going to change the world, right here, right now?”</p>
<p>“If you don’t do it, noone else will.”</p>
<p>This second statement is one I find especially relevent. So many American’s have the mentaility that, “If you don’t do it, someone else will.” This ultimately leads to lazyness because if the person next to you has the same belief, it turns into a never ending chain of inaction.</p>
Indicator While Processing2005-09-26T00:00:00+00:00https://codecrate.com/2005/09/indicator-while-processing<p>Most users rely on the broswer’s “spinner” to know when the server is processing and when it has completed, but with AJAX applications, all bets are off. There’s no way for a user to know if clicking a button will take them to a new page, or swap dynamic HTML into the existing page.</p>
<p>The <a href="http://script.aculo.us/demos/shop">scriptaculous demos</a> have solved this problem by showing an inline indicator while the server is processing, and I have now added this feature to wicket as well. The indicator will only display while the server is processing the AJAX request. The DraggableTarget is the first component to interact with this <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-scriptaculous/src/java/wicket/contrib/scriptaculous/dragdrop/">new Indicator component</a>, and I think the AutocompleteTextField may have use for it as well. Here’s a short example of how to use the new Indicator.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">DragDropExamplePage</span> <span class="kd">extends</span> <span class="nc">WebPage</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">DragDropExamplePage</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Label</span> <span class="n">product</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Label</span><span class="o">(</span><span class="s">"product"</span><span class="o">);</span>
<span class="n">product</span><span class="o">.</span><span class="na">addBehavior</span><span class="o">(</span><span class="k">new</span> <span class="nc">DraggableBehavior</span><span class="o">());</span>
<span class="n">add</span><span class="o">(</span><span class="n">product</span><span class="o">);</span>
<span class="nc">DraggableTarget</span> <span class="n">cart</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DraggableTarget</span><span class="o">(</span><span class="s">"cart"</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onDrop</span><span class="o">(</span><span class="nc">Component</span> <span class="n">input</span><span class="o">,</span> <span class="nc">AjaxRequestTarget</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">input</span> <span class="o">+</span> <span class="s">" dropped on the target"</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="n">add</span><span class="o">(</span><span class="n">cart</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The HTML template just needs to include the indicator, and CSS can be used to customize it further.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>html xmlns:wicket="http://wicket.sourceforge.net/"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>style type="text/css"<span class="ni">&gt;</span>
div.cart-active {
background-color: #FFF4D8;
}
<span class="ni">&lt;</span>/style<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/head<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>img wicket:id="product" alt="Drag Me!"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id="indicator" /<span class="ni">&gt;</span>
<span class="ni">&lt;</span>-- The contents of this div are swapped out with the page contribution --<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id="cart"<span class="ni">&gt;</span>Drop images here.<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>I’ve updated the <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-scriptaculous-examples/src/java/wicket/contrib/scriptaculous/examples/dragdrop/">drag/drop examples</a> to use this new indicator, and I also added a short server side delay to actually show that it’s working correctly. Isn’t it odd that a user might not believe an application is working correctly if it’s too fast?</p>
Wicket Drag/Drop Components2005-09-21T00:00:00+00:00https://codecrate.com/2005/09/wicket-dragdrop-components<p>After finishing up work on the <a href="/2005/09/choice-is-good.html">autocomplete text field</a>, I’ve spent the last few weeks trying to figure out what AJAX component to implement in Wicket next. <a href="">Scriptaculous</a> has some great demos of drag/drop and it definately has some cool use cases, so I think I’ll delve into this area next.</p>
<p>I’ve already figured out how to drag images around using scriptaculous, but I have a feeling that handling the drop may be fairly difficult. My <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-scriptaculous/src/java/wicket/contrib/scriptaculous/dragdrop/">first stab at creating a DraggableImage</a> is fairly simplistic, but it works for now. Once I figure out how to drop images onto an area, I’ll come back to improve the DraggableImage. I’ve checked in this basic DraggableImage and <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-scriptaculous-examples/src/java/wicket/contrib/scriptaculous/examples/dragdrop">a new example has been added to wicket-stuff</a> to demonstrate its current functionality.</p>
Choice Is Good2005-09-06T00:00:00+00:00https://codecrate.com/2005/09/choice-is-good<p>I’ve spent the last couple weeks straining my brain to create <a href="/2005/08/wicket-autocomplete-text-field.html">a slick autocomplete text field for Wicket</a>. Over this time, I’ve come up with several different use cases for such a component. Now, instead of trying to create one uber component that can do it all, I have decided that it makes more sense to have different components for different use cases. This should make it much easier for users since each component has a very explicit and simple API.</p>
<h3 id="autocompletetextfield">AutocompleteTextField</h3>
<p>This is the basic autocomplete implementation that is 100% AJAX free. Simply instantiate the text field with all the possible options, and scriptaculous’ built in filtering features will take care of the rest. This is an easy solution for small datasets.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">String</span><span class="o">[]</span> <span class="n">results</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span>
<span class="s">"Red"</span>
<span class="o">,</span> <span class="s">"Blue"</span>
<span class="o">,</span> <span class="s">"Purple"</span>
<span class="o">,</span> <span class="s">"Orange"</span>
<span class="o">};</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">AutocompleteTextField</span><span class="o">(</span><span class="s">"color"</span><span class="o">,</span> <span class="n">results</span><span class="o">));</span>
</code></pre></div></div>
<h3 id="ajaxautocompletetextfield">AjaxAutocompleteTextField</h3>
<p>And now for some AJAX magic. The AjaxAutocompleteTextField provides a simple callback to allow for dynamically populating the list of available auto completions based on the user input.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">AjaxAutocompleteTextField</span><span class="o">(</span><span class="s">"fruit"</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nc">String</span><span class="o">[]</span> <span class="nf">getResults</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//lookup potential results from database or something</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span>
<span class="s">"Apple"</span>
<span class="o">,</span> <span class="s">"Banana"</span>
<span class="o">};</span>
<span class="o">}</span>
<span class="o">});</span>
</code></pre></div></div>
<h3 id="customlayoutajaxautocompletetextfield">CustomLayoutAjaxAutocompleteTextField</h3>
<p>My <a href="/2005/08/autocomplete-more-than-just-text.html">previous blog entry</a> introduced how to autocomplete more than just text. I wanted to improve the API so that the html markup would be done outside the Java code.</p>
<p>After several iterations, I created something called a PageContribution. The concept behind a PageContribution is that it supplies only a portion of the html for a page. This allows for users to completely customize the layout of autcomplete results. The CustomLayoutAjaxAutocompleteTextField delegates the rendering of the autocomplete results to the PageContribution. Under the covers, it works exactly as a normal Wicket page, but it’s intention is to only provide markup for the autocomplete results.</p>
<p>There are a number of benifits to this approach. Not only can you completely customize the layout of the autocomplete results, you can also directly invoke the autocomplete results as a seperate page to preview the results. This is one feature of the scriptaculous examples that really impressed me. Simply view the source of the demo and you can extract the url for the autocomplete component.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">CustomLayoutAjaxAutocompleteTextField</span><span class="o">(</span><span class="s">"emailAddress"</span><span class="o">,</span> <span class="nc">ExampleAjaxAutocompletePageContribution</span><span class="o">.</span><span class="na">class</span><span class="o">));</span>
</code></pre></div></div>
<p>A helper abstract class (CustomLayoutAutocompleteResultsPageContribution) is available to handle extracting the user’s input from the correct input parameter.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ExampleAjaxAutocompletePageContribution</span>
<span class="kd">extends</span> <span class="nc">CustomLayoutAutocompleteResultsPageContribution</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">ExampleAjaxAutocompletePageContribution</span><span class="o">(</span><span class="nc">PageParameters</span> <span class="n">parameters</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">parameters</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="nc">ListView</span> <span class="nf">buildListView</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//lookup results from string input</span>
<span class="nc">List</span> <span class="n">results</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="n">results</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">CustomResultObject</span><span class="o">(</span><span class="s">"ryan.gif"</span><span class="o">,</span> <span class="s">"Ryan Sonnek"</span><span class="o">,</span> <span class="s">"ryan@youremail.com"</span><span class="o">));</span>
<span class="n">results</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">CustomResultObject</span><span class="o">(</span><span class="s">"billy.gif"</span><span class="o">,</span> <span class="s">"Bill Gates"</span><span class="o">,</span> <span class="s">"bill.gates@microsoft.com"</span><span class="o">));</span>
<span class="k">return</span> <span class="k">new</span> <span class="nf">ListView</span><span class="o">(</span><span class="s">"entries"</span><span class="o">,</span> <span class="n">results</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">populateItem</span><span class="o">(</span><span class="nc">ListItem</span> <span class="n">item</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">CustomResultObject</span> <span class="n">result</span> <span class="o">=</span> <span class="o">(</span><span class="nc">CustomResultObject</span><span class="o">)</span> <span class="n">item</span><span class="o">.</span><span class="na">getModelObject</span><span class="o">();</span>
<span class="n">item</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">Label</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="n">result</span><span class="o">.</span><span class="na">getName</span><span class="o">()));</span>
<span class="n">item</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">Label</span><span class="o">(</span><span class="s">"email"</span><span class="o">,</span> <span class="n">result</span><span class="o">.</span><span class="na">getEmail</span><span class="o">()));</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The PageContribution then supplies it’s own html markup for how to render the autocomplete results,</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>ul wicket:id="entries"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>li<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id="name">Ryan Sonnek<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>div wicket:id="email">ryan@somewhere.com<span class="ni">&lt;</span>/div<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/li<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/ul<span class="ni">&gt;</span>
</code></pre></div></div>
<p>I have added examples for each of these use cases to <a href="http://wicket-stuff.sf.net">wicket-stuff</a> along with a Jetty launcher for anyone that wants to give them a test drive.</p>
Autocomplete More Than Just Text2005-08-25T00:00:00+00:00https://codecrate.com/2005/08/autocomplete-more-than-just-text<p>If you run the <a href="http://script.aculo.us/demos/ajax/autocompleter_customized">scriptaculous autocomplete demo</a> you’ll notice that one of the coolest features is that the results are not just plain text. They display a thumbnail image along with two pieces of text in a great looking layout. You might not realize it, but the current Wicket AutocompleteTextField in wicket-stuff already supports this behavior.</p>
<p>Now, you might be thinking, “That’s crazy? How can this be when the API only returns a String?”</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">protected</span> <span class="kd">abstract</span> <span class="nc">String</span><span class="o">[]</span> <span class="nf">getResults</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">);</span>
</code></pre></div></div>
<p>Well, why not just return an HTML formatted string? Here’s some example code:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nf">AdvancedAutocompleteExampleForm</span><span class="o">(</span><span class="nc">String</span> <span class="n">id</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">id</span><span class="o">);</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">AutocompleteTextField</span><span class="o">(</span><span class="s">"emailAddress"</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nc">String</span><span class="o">[]</span> <span class="nf">getResults</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span>
<span class="n">buildAutoCompleteContent</span><span class="o">(</span><span class="s">"bill.gif"</span><span class="o">,</span> <span class="s">"Bill Gates"</span><span class="o">,</span> <span class="s">"bill.gates@microsoft.com"</span><span class="o">)</span>
<span class="o">,</span> <span class="n">buildAutoCompleteContent</span><span class="o">(</span><span class="s">"ryan.gif"</span><span class="o">,</span> <span class="s">"Ryan Sonnek"</span><span class="o">,</span> <span class="s">"ryansonnek@notvalid.com"</span><span class="o">)</span>
<span class="o">};</span>
<span class="o">}</span>
<span class="o">});</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="nf">buildAutoCompleteContent</span><span class="o">(</span><span class="nc">String</span> <span class="n">image</span><span class="o">,</span> <span class="nc">String</span> <span class="n">name</span><span class="o">,</span> <span class="nc">String</span> <span class="n">emailAddress</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">StringBuffer</span> <span class="n">content</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringBuffer</span><span class="o">();</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;div class=\"imageContent\"&gt;"</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;img src=\""</span> <span class="o">+</span> <span class="n">image</span> <span class="o">+</span> <span class="s">"\" alt=\""</span> <span class="o">+</span> <span class="n">name</span> <span class="o">+</span> <span class="s">"\"/&gt;"</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;/div&gt;"</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;div class=\"nameContent\"&gt;"</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;/div&gt;"</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;div class=\"informal\"&gt;"</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">emailAddress</span><span class="o">);</span>
<span class="n">content</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;/div&gt;"</span><span class="o">);</span>
<span class="k">return</span> <span class="n">content</span><span class="o">.</span><span class="na">toString</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Yep, that’s it. Now in order for it to look good, you’ll have to attach some custom style sheet similar to scriptaculous.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">final</span> <span class="kt">void</span> <span class="nf">printHeadInitContribution</span><span class="o">(</span><span class="nc">HtmlHeaderContainer</span> <span class="n">container</span><span class="o">)</span> <span class="o">{</span>
<span class="n">container</span><span class="o">.</span><span class="na">getResponse</span><span class="o">().</span><span class="na">write</span><span class="o">(</span>
<span class="s">"&lt;style type=\"text/css\"&gt;\n"</span> <span class="o">+</span>
<span class="s">" li.contact div.imageContent {\n"</span> <span class="o">+</span>
<span class="s">" float:left;\n"</span> <span class="o">+</span>
<span class="s">" width:32px;\n"</span> <span class="o">+</span>
<span class="s">" height:32px;\n"</span> <span class="o">+</span>
<span class="s">" margin-right:8px;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">" li.contact div.nameContent {\n"</span> <span class="o">+</span>
<span class="s">" font-weight:bold;\n"</span> <span class="o">+</span>
<span class="s">" font-size:12px;\n"</span> <span class="o">+</span>
<span class="s">" line-height:1.2em;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">" li.contact div.informal {\n"</span> <span class="o">+</span>
<span class="s">" font-size:10px;\n"</span> <span class="o">+</span>
<span class="s">" color:#888;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">"&lt;/style&gt;\n"</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Now for a bit more of scriptalicious magic. You might be wondering how the autocomplete text box figures out what text to use when a user selects the text from the drop down. After all, there are two separate text chunks to choose from. This is where the informal class name comes into play. When the user selects an auto complete entry, all informal chunks are ignored. This means that there should only be one piece of text content that is not informal.</p>
<p>I have committed this <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-prototype-examples/">example example into wicket-stuff</a> for anyone to use and to keep up to date with the ever changing AutocompleteTextField API.</p>
Wicket Autocomplete Text Field2005-08-23T00:00:00+00:00https://codecrate.com/2005/08/wicket-autocomplete-text-field<p>Hold onto your seats boys and girls, this one entry you won’t want to miss.</p>
<p>Anyone interested in building the next generation of web applications will hopefully have run across the <a href="http://script.aculo.us/demos/ajax/autocompleter_customized">amazing script.aculo.us demos</a>. Wouldn’t it be great to have these ajax components out of the box with our Java frameworks? I mean, I’ve been impressed with <a href="http://www.rubyonrails.org/">Ruby on Rails</a>, but I can’t see myself using it. One of my gripes with Rails is the loss of previewable HTML. Has anyone seen the <a href="http://script.aculo.us/demos/ajax/autocompleter_customized">source code for the demos</a>? More importantly, can anyone understand them?</p>
<p>Component frameworks like <a href="http://jakarta.apache.org/tapestry/">Tapestry</a> and <a href="http://wicket.sf.net">Wicket</a> allow for HTML designers to take complete control of the look and feel of website design, and dynamic content is plugged in without the need to learn <a href="http://jakarta.apache.org/velocity">new scripting languages</a> or use <a href="http://java.sun.com/products/jsp/jstl/">custom XML-ish tags</a>. Or, does it seem a bit too logical to have HTML designers just use HTML when designing websites? =)</p>
<p>I’ve been so impressed with Wicket and script.aculo.us, that I spent about 4 hours Friday night digging into the <a href="http://jroller.com/page/dashorst?entry=wicket_1_1_beta1_and">experimental ajax support in Wicket</a>. My goal was to create a reusable autocomplete text field that would allow for any Wicket application to add the same functionality with a minimum amount of effort.</p>
<p>This example AutocompleteTextField is just an extention of the normal Wicket text field with some additional javascript and css output added. This component is built using the same <a href="http://prototype.conio.net/">Prototype</a> javascript library that is used with Rails and scrit.aculo.us. I had to really dig into the internals of Wicket in order to get this to work, so it may not be for the light of heart. Hopefully someone smarter than I can figure out a more elegant approach to extending the Wicket render cycle. This code may be a bit long, but I prefer giving the whole source instead of adding extra attachments.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o"><</span><span class="n">pre</span><span class="o">></span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">AutocompleteTextField</span> <span class="kd">extends</span> <span class="nc">TextField</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">AutocompleteEventHandler</span> <span class="n">handler</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">AutocompleteTextField</span><span class="o">(</span><span class="nc">String</span> <span class="n">id</span><span class="o">,</span> <span class="nc">AutocompleteResultGenerator</span> <span class="n">generator</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">id</span><span class="o">);</span>
<span class="n">handler</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">AutocompleteEventHandler</span><span class="o">(</span><span class="n">generator</span><span class="o">);</span>
<span class="n">add</span><span class="o">(</span><span class="n">handler</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onComponentTag</span><span class="o">(</span><span class="nc">ComponentTag</span> <span class="n">tag</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">.</span><span class="na">onComponentTag</span><span class="o">(</span><span class="n">tag</span><span class="o">);</span>
<span class="n">tag</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"id"</span><span class="o">,</span> <span class="n">getId</span><span class="o">());</span>
<span class="c1">//disable browser's autocompletion on this field</span>
<span class="n">tag</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"autocomplete"</span><span class="o">,</span> <span class="s">"off"</span><span class="o">);</span>
<span class="o">}</span>
<span class="cm">/**
* Prototype's Ajax.Autocompleter expects the autocomplete text field to have the following info:
* &lt;input id="foo" /&gt;
* &lt;div id="foo_autocomplete"&gt;&lt;/div&gt;
*/</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onRender</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//render the text area</span>
<span class="kd">super</span><span class="o">.</span><span class="na">onRender</span><span class="o">();</span>
<span class="c1">//print the hidden div area that the autocomplete results are rendered to</span>
<span class="nc">String</span> <span class="n">autocompleteId</span> <span class="o">=</span> <span class="n">getId</span><span class="o">()</span> <span class="o">+</span> <span class="s">"_autocomplete"</span><span class="o">;</span>
<span class="kd">final</span> <span class="nc">String</span> <span class="n">url</span> <span class="o">=</span> <span class="k">this</span><span class="o">.</span><span class="na">urlFor</span><span class="o">(</span><span class="nc">IEventRequestListener</span><span class="o">.</span><span class="na">class</span><span class="o">)</span> <span class="o">+</span> <span class="s">"&amp;id="</span> <span class="o">+</span> <span class="n">handler</span><span class="o">.</span><span class="na">getId</span><span class="o">();</span>
<span class="n">getResponse</span><span class="o">().</span><span class="na">write</span><span class="o">(</span><span class="s">"&lt;div class=\"auto_complete\" id=\""</span> <span class="o">+</span> <span class="n">autocompleteId</span> <span class="o">+</span> <span class="s">"\"&gt;&lt;/div&gt;"</span><span class="o">);</span>
<span class="c1">//render javascript call to Prototype's Ajax.Autocompleter</span>
<span class="n">getResponse</span><span class="o">().</span><span class="na">write</span><span class="o">(</span><span class="s">"&lt;script type=\"text/javascript\"&gt;new Ajax.Autocompleter('"</span> <span class="o">+</span>
<span class="n">getId</span><span class="o">()</span> <span class="o">+</span> <span class="s">"', '"</span> <span class="o">+</span> <span class="n">autocompleteId</span> <span class="o">+</span> <span class="s">"', '"</span> <span class="o">+</span> <span class="n">url</span> <span class="o">+</span> <span class="s">"', {})&lt;/script&gt;"</span><span class="o">);</span>
<span class="c1">//include a BASIC stylesheet for out-of-the box usability</span>
<span class="n">getResponse</span><span class="o">().</span><span class="na">write</span><span class="o">(</span><span class="s">"&lt;style type=\"text/css\"&gt;\n"</span> <span class="o">+</span>
<span class="s">" div.auto_complete {\n"</span> <span class="o">+</span>
<span class="s">" width: 350px;\n"</span> <span class="o">+</span>
<span class="s">" background: #fff;\n"</span> <span class="o">+</span>
<span class="s">" overflow: hidden;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">" div.auto_complete ul {\n"</span> <span class="o">+</span>
<span class="s">" border:1px solid #888;\n"</span> <span class="o">+</span>
<span class="s">" margin:0;\n"</span> <span class="o">+</span>
<span class="s">" padding:0;\n"</span> <span class="o">+</span>
<span class="s">" width:100%;\n"</span> <span class="o">+</span>
<span class="s">" list-style-type:none;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">" div.auto_complete ul li {\n"</span> <span class="o">+</span>
<span class="s">" margin:0;\n"</span> <span class="o">+</span>
<span class="s">" padding:3px;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">" div.auto_complete ul li.selected {\n"</span> <span class="o">+</span>
<span class="s">" background-color: #ffb;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">" div.auto_complete ul strong.highlight {\n"</span> <span class="o">+</span>
<span class="s">" color: #800;\n"</span> <span class="o">+</span>
<span class="s">" margin:0;\n"</span> <span class="o">+</span>
<span class="s">" padding:0;\n"</span> <span class="o">+</span>
<span class="s">" }\n"</span> <span class="o">+</span>
<span class="s">"&lt;/style&gt;\n"</span> <span class="o">+</span>
<span class="s">""</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kd">class</span> <span class="nc">AutocompleteEventHandler</span> <span class="kd">extends</span> <span class="nc">AbstractEventRequestHandler</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">FormComponent</span> <span class="n">formComponent</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">AutocompleteResultGenerator</span> <span class="n">resultGenerator</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">AutocompleteEventHandler</span><span class="o">(</span><span class="nc">AutocompleteResultGenerator</span> <span class="n">resultGenerator</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">resultGenerator</span> <span class="o">=</span> <span class="n">resultGenerator</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kd">final</span> <span class="kt">void</span> <span class="nf">printHeadInitContribution</span><span class="o">(</span><span class="nc">HtmlHeaderContainer</span> <span class="n">container</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">// add our basic javascript needs to the header</span>
<span class="c1">//TODO: might not need to add all of these prototype scripts.</span>
<span class="n">addJsReference</span><span class="o">(</span><span class="n">container</span><span class="o">,</span> <span class="k">new</span> <span class="nc">StaticResourceReference</span><span class="o">(</span><span class="nc">AutocompleteTextField</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"prototype.js"</span><span class="o">));</span>
<span class="n">addJsReference</span><span class="o">(</span><span class="n">container</span><span class="o">,</span> <span class="k">new</span> <span class="nc">StaticResourceReference</span><span class="o">(</span><span class="nc">AutocompleteTextField</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"controls.js"</span><span class="o">));</span>
<span class="n">addJsReference</span><span class="o">(</span><span class="n">container</span><span class="o">,</span> <span class="k">new</span> <span class="nc">StaticResourceReference</span><span class="o">(</span><span class="nc">AutocompleteTextField</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"dragdrop.js"</span><span class="o">));</span>
<span class="n">addJsReference</span><span class="o">(</span><span class="n">container</span><span class="o">,</span> <span class="k">new</span> <span class="nc">StaticResourceReference</span><span class="o">(</span><span class="nc">AutocompleteTextField</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"effects.js"</span><span class="o">));</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">addJsReference</span><span class="o">(</span><span class="nc">HtmlHeaderContainer</span> <span class="n">container</span><span class="o">,</span> <span class="nc">StaticResourceReference</span> <span class="n">ref</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">String</span> <span class="n">url</span> <span class="o">=</span> <span class="n">container</span><span class="o">.</span><span class="na">getPage</span><span class="o">().</span><span class="na">urlFor</span><span class="o">(</span><span class="n">ref</span><span class="o">.</span><span class="na">getPath</span><span class="o">());</span>
<span class="nc">String</span> <span class="n">s</span> <span class="o">=</span>
<span class="s">"\t&lt;script language=\"JavaScript\" type=\"text/javascript\" "</span> <span class="o">+</span>
<span class="s">"src=\""</span> <span class="o">+</span> <span class="n">url</span> <span class="o">+</span> <span class="s">"\"&gt;&lt;/script&gt;\n"</span><span class="o">;</span>
<span class="n">write</span><span class="o">(</span><span class="n">container</span><span class="o">,</span> <span class="n">s</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">write</span><span class="o">(</span><span class="nc">HtmlHeaderContainer</span> <span class="n">container</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
<span class="n">container</span><span class="o">.</span><span class="na">getResponse</span><span class="o">().</span><span class="na">write</span><span class="o">(</span><span class="n">s</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">bind</span><span class="o">(</span><span class="nc">Component</span> <span class="n">component</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(!(</span><span class="n">component</span> <span class="k">instanceof</span> <span class="nc">FormComponent</span><span class="o">))</span> <span class="o">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">IllegalArgumentException</span><span class="o">(</span>
<span class="s">"this handler can only be bound to form components"</span><span class="o">);</span>
<span class="o">}</span>
<span class="k">if</span> <span class="o">(</span><span class="n">formComponent</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">IllegalStateException</span><span class="o">(</span>
<span class="s">"this kind of handler cannot be attached to "</span>
<span class="o">+</span> <span class="s">"multiple components; it is allready attached to component "</span>
<span class="o">+</span> <span class="n">formComponent</span> <span class="o">+</span> <span class="s">", but component "</span>
<span class="o">+</span> <span class="n">component</span> <span class="o">+</span> <span class="s">" wants to be attached too"</span><span class="o">);</span>
<span class="o">}</span>
<span class="k">this</span><span class="o">.</span><span class="na">formComponent</span> <span class="o">=</span> <span class="o">(</span><span class="nc">FormComponent</span><span class="o">)</span> <span class="n">component</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onComponentTag</span><span class="o">(</span><span class="nc">Component</span> <span class="n">component</span><span class="o">,</span> <span class="nc">ComponentTag</span> <span class="n">tag</span><span class="o">)</span> <span class="o">{</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="nc">IResourceStream</span> <span class="nf">getResponse</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">StringBufferResourceStream</span> <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringBufferResourceStream</span><span class="o">();</span>
<span class="n">formComponent</span><span class="o">.</span><span class="na">validate</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="n">formComponent</span><span class="o">.</span><span class="na">isValid</span><span class="o">())</span> <span class="o">{</span>
<span class="n">formComponent</span><span class="o">.</span><span class="na">updateModel</span><span class="o">();</span>
<span class="o">}</span>
<span class="nc">String</span> <span class="n">value</span> <span class="o">=</span> <span class="n">formComponent</span><span class="o">.</span><span class="na">getValue</span><span class="o">();</span>
<span class="c1">//render results in list</span>
<span class="c1">//prototype's Ajax.Autocompleter automatically places results into the hidden div area</span>
<span class="n">s</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;ul&gt;\n"</span><span class="o">);</span>
<span class="nc">String</span><span class="o">[]</span> <span class="n">results</span> <span class="o">=</span> <span class="n">resultGenerator</span><span class="o">.</span><span class="na">getResults</span><span class="o">(</span><span class="n">value</span><span class="o">);</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">x</span> <span class="o">&</span><span class="n">lt</span><span class="o">;</span> <span class="n">results</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">x</span><span class="o">++)</span> <span class="o">{</span>
<span class="nc">String</span> <span class="n">result</span> <span class="o">=</span> <span class="n">results</span><span class="o">[</span><span class="n">x</span><span class="o">];</span>
<span class="n">s</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;li class=\"contact\"&gt;"</span> <span class="o">+</span> <span class="n">result</span> <span class="o">+</span> <span class="s">"&lt;/li&gt;\n"</span><span class="o">);</span>
<span class="o">}</span>
<span class="n">s</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">"&lt;/ul&gt;\n"</span><span class="o">);</span>
<span class="k">return</span> <span class="n">s</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Developers can now get this sweet autocomplete text field in the application. Notice how the HTML template is exactly the same. The template has no idea of the underlying autocomplete/ajax functionality.</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ni">&lt;</span>html xmlns:wicket="http://wicket.sourceforge.net/"<span class="ni">&gt;</span>
<span class="ni">&lt;</span>body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>form wicket:id="searchForm"<span class="ni">&gt;</span>
Search:
<span class="ni">&lt;</span>input wicket:id="query" type="text"/<span class="ni">&gt;</span>
<span class="ni">&lt;</span>input wicket:id="submitButton" type="submit" value="Submit"/<span class="ni">&gt;</span>
<span class="ni">&lt;</span>form<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/body<span class="ni">&gt;</span>
<span class="ni">&lt;</span>/html<span class="ni">&gt;</span>
</code></pre></div></div>
<p>It’s the job of the Java form to add the new AutocompleteTextField and to register the AutocompleteResultGenerator. This example uses a hard coded list of results, but it can easily be customized to perform any custom search or lookup of information.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SearchForm</span> <span class="kd">extends</span> <span class="nc">Form</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nf">SearchForm</span><span class="o">(</span><span class="nc">String</span> <span class="n">id</span><span class="o">,</span> <span class="nc">IFeedback</span> <span class="n">feedback</span><span class="o">)</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="k">new</span> <span class="nc">CompoundPropertyModel</span><span class="o">(</span><span class="k">new</span> <span class="nc">SearchModel</span><span class="o">()),</span> <span class="n">feedback</span><span class="o">);</span>
<span class="nc">AutocompleteResultGenerator</span> <span class="n">searcher</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">AutocompleteResultGenerator</span><span class="o">()</span> <span class="o">{</span>
<span class="kd">public</span> <span class="nc">String</span><span class="o">[]</span> <span class="nf">getResults</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span><span class="s">"Bob"</span><span class="o">,</span> <span class="s">"Jamie"</span><span class="o">,</span> <span class="s">"Eric"</span><span class="o">};</span>
<span class="o">}</span>
<span class="o">};</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">AutocompleteTextField</span><span class="o">(</span><span class="s">"query"</span><span class="o">,</span> <span class="n">searcher</span><span class="o">));</span>
<span class="n">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">Button</span><span class="o">(</span><span class="s">"submitButton"</span><span class="o">));</span>
<span class="o">}</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onSubmit</span><span class="o">()</span> <span class="o">{</span>
<span class="c1">//do something with the search text</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>There’s plenty of room for improvement, but I hope that this will serve as a springboard for others trying out the already impressive Wicket ajax support. It would be great to enhance API to be more Wicket friendly like returning a ListView instead of a String[]. Hopefully with a little support, this component could work it’s way into wicket for other developers to use.</p>
<p>And to all those <a href="/2005/08/web-development-done-right.html">insightful comments on my last blog</a> saying that JSP was “good enough” for a web technology, let’s see JSP do this! And don’t you dare mention JSF…</p>
AJAX Added to Wicket-Stuff2005-08-23T00:00:00+00:00https://codecrate.com/2005/08/ajax-added-to-wicket-stuff<p>There was quite a flurry of activity after my <a href="/2005/08/wicket-autocomplete-text-field.html">blog post yesterday</a>.</p>
<p>It seems that this is not the first attempt to build auto completion components using the new Wicket AJAX support. In order to foster some collaboration and build a true “community component”, the AutocompleteTextField has been accepted into the <a href="http://wicket-stuff.sf.net">wicket-stuff project</a>. This will be an incubator of sorts to smooth out any rough edges for the AutocompleteTextField API before it’s hopefull graduation and inclusion into the core Wicket AJAX components. This should allow for Wicket experts some time to <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-prototype/">tear into the code</a> and give direction for a more elegant solution.</p>
<p>In order to provide some usable examples for people, wicket-stuff has also added <a href="http://cvs.sourceforge.net/viewcvs.py/wicket-stuff/wicket-contrib-prototype-examples/">a new subproject</a> that can be used to test out and excersise the AutocompleteTextField. I’ll be writing up more complex examples soon that show how to really take advantage of the <a href="http://prototype.conio.net/">Prototype</a> auto complete functionality. The <a href="http://script.aculo.us/demos/ajax/autocompleter_customized">scriptaculous demos</a> should give you an idea of the improvements I’ll be adding.</p>
<p>For anyone interested in giving this autocomplete component a test drive, I just published a <a href="http://maven.codecrate.com/wicket-stuff/jars/">snapshot version of the component on my maven repository</a>. The Prototype javascript files are already packaged with the jar, so it should be as simple as dropping the jar into your app and letting it rip! I have only tested the component with wicket-1.1-b2, but I will probably try out wicket-1.1-b3 sometime next week.</p>
<p>If there are changes or improvements that you would like to see, please drop me a line or send an email to the wicket mailing list.</p>
Simple Hibernate Search Engine2005-08-17T00:00:00+00:00https://codecrate.com/2005/08/simple-hibernate-search-engine<p>Wouldn’t it be great to be able to use a powerful search engine on your business objects? Searching is becoming THE preferred way for user’s to find their data. Emerging applications like <a href="http://desktop.google.com">Google Desktop</a> and <a href="http://beaglewiki.org/Main_Page">Beagle</a> have embraced the new mantra of user’s to “Search, Don’t Sort”. User’s don’t want to be forced to organize their data into limiting categories or folders, or to scroll around applications to find the data they are looking for. Even common GUI practices like table sorting are considered an eye sore compared to a snappy search box.</p>
<p>I have experienced the same expectation when working with my D20 datasets. It’s become increasingly difficult to manage lists of skills, feats and items across multiple sources. To try and improve the user experience, I have <a href="http://jira.codecrate.com/browse/SHA-84">integrated a full blown search engine</a> into <a href="http://shard.codecrate.com">shard</a>.</p>
<p>My goal was create a simple search framework to handle simple searching for the majority of my domain objects out of the box. I wanted all of my objects to be placed into the same index, and my search to be smart enough to know what object’s I want returned. Something that made the client API as simple as:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Collection</span> <span class="n">results</span> <span class="o">=</span> <span class="n">searcher</span><span class="o">.</span><span class="na">search</span><span class="o">(</span><span class="nc">DefaultSkill</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"knowledge arc*"</span><span class="o">);</span>
</code></pre></div></div>
<p>In order for the searcher to be smart enough to know what type of objects to search and what type of objects to return from Hibernate, the datatype and the unique Hibernate key need to exist in the index.</p>
<table>
<tr>
<th>Object</th>
<th>Id</th>
<th>Text</th>
</tr><tr>
</tr><tr>
<td>foo.bar.MyObject</td>
<td>123</td>
<td>Happy Dog</td>
</tr>
<tr>
<td>foo.bar.YourObject</td>
<td>456</td>
<td>Yellow Puppy</td>
</tr>
</table>
<p>The first piece of the puzzle was to figure out how to create an index with my persistent objects. I found that the Hibernate Interceptor provided an excellent entry point for indexing my objects. It was actually pretty simple to implement.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">LuceneInterceptor</span> <span class="kd">implements</span> <span class="nc">Interceptor</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">Log</span> <span class="no">LOG</span> <span class="o">=</span> <span class="nc">LogFactory</span><span class="o">.</span><span class="na">getLog</span><span class="o">(</span><span class="nc">LuceneInterceptor</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">boolean</span> <span class="no">DO_NOT_CREATE_INDEX</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Directory</span> <span class="n">directory</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Analyzer</span> <span class="n">analyzer</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">LuceneInterceptor</span><span class="o">(</span><span class="nc">DirectoryManager</span> <span class="n">directoryManager</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">directory</span> <span class="o">=</span> <span class="n">directoryManager</span><span class="o">.</span><span class="na">getDirectory</span><span class="o">();</span>
<span class="k">this</span><span class="o">.</span><span class="na">analyzer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StandardAnalyzer</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">onSave</span><span class="o">(</span><span class="nc">Object</span> <span class="n">entity</span><span class="o">,</span> <span class="nc">Serializable</span> <span class="n">id</span><span class="o">,</span>
<span class="nc">Object</span><span class="o">[]</span> <span class="n">currentState</span><span class="o">,</span> <span class="nc">String</span><span class="o">[]</span> <span class="n">propertyNames</span><span class="o">,</span> <span class="nc">Type</span><span class="o">[]</span> <span class="n">types</span><span class="o">)</span>
<span class="kd">throws</span> <span class="nc">CallbackException</span> <span class="o">{</span>
<span class="c1">//this call cleans out any existing document in the index</span>
<span class="n">removeDocuments</span><span class="o">(</span><span class="n">id</span><span class="o">);</span>
<span class="nc">IndexWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">IndexWriter</span><span class="o">(</span><span class="n">directory</span><span class="o">,</span> <span class="n">analyzer</span><span class="o">,</span> <span class="no">DO_NOT_CREATE_INDEX</span><span class="o">);</span>
<span class="nc">Document</span> <span class="n">document</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Document</span><span class="o">();</span>
<span class="n">document</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="nc">Field</span><span class="o">.</span><span class="na">Keyword</span><span class="o">(</span><span class="nc">LuceneSearcher</span><span class="o">.</span><span class="na">FIELD_CLASS</span><span class="o">,</span> <span class="n">entity</span><span class="o">.</span><span class="na">getClass</span><span class="o">().</span><span class="na">getName</span><span class="o">()));</span>
<span class="n">document</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="nc">Field</span><span class="o">.</span><span class="na">Keyword</span><span class="o">(</span><span class="nc">LuceneSearcher</span><span class="o">.</span><span class="na">FIELD_ID</span><span class="o">,</span> <span class="n">id</span><span class="o">.</span><span class="na">toString</span><span class="o">()));</span>
<span class="c1">//This is a VERY simplistic way to index data about the entity</span>
<span class="c1">//ideally you would have some kind of extension point to allow for more detailed</span>
<span class="c1">//information to be extracted about the entity based on the datatype</span>
<span class="n">document</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="nc">Field</span><span class="o">.</span><span class="na">Text</span><span class="o">(</span><span class="nc">LuceneSearcher</span><span class="o">.</span><span class="na">FIELD_TEXT</span><span class="o">,</span> <span class="n">entity</span><span class="o">.</span><span class="na">toString</span><span class="o">()));</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"saving "</span> <span class="o">+</span> <span class="n">document</span><span class="o">);</span>
<span class="n">writer</span><span class="o">.</span><span class="na">addDocument</span><span class="o">(</span><span class="n">document</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="s">"Error updating index for object "</span> <span class="o">+</span> <span class="n">entity</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
<span class="n">closeWriter</span><span class="o">(</span><span class="n">writer</span><span class="o">);</span>
<span class="o">}</span>
<span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onDelete</span><span class="o">(</span><span class="nc">Object</span> <span class="n">entity</span><span class="o">,</span> <span class="nc">Serializable</span> <span class="n">id</span><span class="o">,</span> <span class="nc">Object</span><span class="o">[]</span> <span class="n">state</span><span class="o">,</span>
<span class="nc">String</span><span class="o">[]</span> <span class="n">propertyNames</span><span class="o">,</span> <span class="nc">Type</span><span class="o">[]</span> <span class="n">types</span><span class="o">)</span> <span class="o">{</span>
<span class="n">removeDocuments</span><span class="o">(</span><span class="n">id</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">removeDocuments</span><span class="o">(</span><span class="nc">Serializable</span> <span class="n">id</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">IndexReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">reader</span> <span class="o">=</span> <span class="nc">IndexReader</span><span class="o">.</span><span class="na">open</span><span class="o">(</span><span class="n">directory</span><span class="o">);</span>
<span class="kt">int</span> <span class="n">numDeleted</span> <span class="o">=</span> <span class="n">reader</span><span class="o">.</span><span class="na">delete</span><span class="o">(</span><span class="k">new</span> <span class="nc">Term</span><span class="o">(</span><span class="s">"id"</span><span class="o">,</span> <span class="n">id</span><span class="o">.</span><span class="na">toString</span><span class="o">()));</span>
<span class="k">if</span> <span class="o">(</span><span class="mi">0</span> <span class="o"><</span> <span class="n">numDeleted</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"Removed "</span> <span class="o">+</span> <span class="n">numDeleted</span> <span class="o">+</span> <span class="s">" documents from index "</span> <span class="o">+</span> <span class="n">directory</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="s">"Error removing documents for "</span> <span class="o">+</span> <span class="n">id</span> <span class="o">+</span> <span class="s">" from index "</span> <span class="o">+</span> <span class="n">directory</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
<span class="n">closeReader</span><span class="o">(</span><span class="n">reader</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">closeWriter</span><span class="o">(</span><span class="nc">IndexWriter</span> <span class="n">writer</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="kc">null</span> <span class="o">!=</span> <span class="n">writer</span><span class="o">)</span> <span class="o">{</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">writer</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"Error while closing index writer"</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">closeReader</span><span class="o">(</span><span class="nc">IndexReader</span> <span class="n">reader</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="kc">null</span> <span class="o">!=</span> <span class="n">reader</span><span class="o">)</span> <span class="o">{</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">reader</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"Error closing index reader for index "</span> <span class="o">+</span> <span class="n">directory</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="c1">// ommitted other interceptor methods</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Next up was creating the simple/smart searcher which is responsible for performing the lucene search and looking up the records in Hibernate.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">LuceneSearcher</span> <span class="kd">extends</span> <span class="nc">HibernateTemplate</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">String</span> <span class="no">FIELD_CLASS</span> <span class="o">=</span> <span class="s">"class"</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">String</span> <span class="no">FIELD_TEXT</span> <span class="o">=</span> <span class="s">"text"</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">String</span> <span class="no">FIELD_ID</span> <span class="o">=</span> <span class="s">"id"</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">Log</span> <span class="no">LOG</span> <span class="o">=</span> <span class="nc">LogFactory</span><span class="o">.</span><span class="na">getLog</span><span class="o">(</span><span class="nc">LuceneSearcher</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">boolean</span> <span class="no">REQUIRED</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">boolean</span> <span class="no">NOT_PROHIBITED</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Directory</span> <span class="n">directory</span><span class="o">;</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">Analyzer</span> <span class="n">analyzer</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">LuceneSearcher</span><span class="o">(</span><span class="nc">DirectoryManager</span> <span class="n">directoryManager</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">directory</span> <span class="o">=</span> <span class="n">directoryManager</span><span class="o">.</span><span class="na">getDirectory</span><span class="o">();</span>
<span class="k">this</span><span class="o">.</span><span class="na">analyzer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StandardAnalyzer</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">Collection</span> <span class="nf">search</span><span class="o">(</span><span class="nc">Class</span> <span class="n">target</span><span class="o">,</span> <span class="nc">String</span> <span class="n">query</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Searcher</span> <span class="n">searcher</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
<span class="nc">Collection</span> <span class="n">results</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">searcher</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">IndexSearcher</span><span class="o">(</span><span class="n">directory</span><span class="o">);</span>
<span class="nc">BooleanQuery</span> <span class="n">masterQuery</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BooleanQuery</span><span class="o">();</span>
<span class="n">masterQuery</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nc">TermQuery</span><span class="o">(</span><span class="k">new</span> <span class="nc">Term</span><span class="o">(</span><span class="no">FIELD_CLASS</span><span class="o">,</span> <span class="n">target</span><span class="o">.</span><span class="na">getName</span><span class="o">())),</span> <span class="no">REQUIRED</span><span class="o">,</span> <span class="no">NOT_PROHIBITED</span><span class="o">);</span>
<span class="n">masterQuery</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="nc">QueryParser</span><span class="o">.</span><span class="na">parse</span><span class="o">(</span><span class="n">makeWildcardQuery</span><span class="o">(</span><span class="n">query</span><span class="o">),</span> <span class="no">FIELD_TEXT</span><span class="o">,</span> <span class="n">analyzer</span><span class="o">),</span> <span class="no">REQUIRED</span><span class="o">,</span> <span class="no">NOT_PROHIBITED</span><span class="o">);</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"Searching for "</span> <span class="o">+</span> <span class="n">masterQuery</span><span class="o">);</span>
<span class="nc">Hits</span> <span class="n">hits</span> <span class="o">=</span> <span class="n">searcher</span><span class="o">.</span><span class="na">search</span><span class="o">(</span><span class="n">masterQuery</span><span class="o">);</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"Found "</span> <span class="o">+</span> <span class="n">hits</span><span class="o">.</span><span class="na">length</span><span class="o">()</span> <span class="o">+</span> <span class="s">" matches"</span><span class="o">);</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">x</span> <span class="o"><</span> <span class="n">hits</span><span class="o">.</span><span class="na">length</span><span class="o">();</span> <span class="n">x</span><span class="o">++)</span> <span class="o">{</span>
<span class="nc">Document</span> <span class="n">document</span> <span class="o">=</span> <span class="n">hits</span><span class="o">.</span><span class="na">doc</span><span class="o">(</span><span class="n">x</span><span class="o">);</span>
<span class="nc">String</span> <span class="n">id</span> <span class="o">=</span> <span class="n">document</span><span class="o">.</span><span class="na">getField</span><span class="o">(</span><span class="no">FIELD_ID</span><span class="o">).</span><span class="na">stringValue</span><span class="o">();</span>
<span class="c1">//lookup the object from hibernate</span>
<span class="nc">Object</span> <span class="n">result</span> <span class="o">=</span> <span class="k">this</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">target</span><span class="o">,</span> <span class="n">id</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="kc">null</span> <span class="o">==</span> <span class="n">result</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"Search index is out of synch with database. Unable to find object "</span> <span class="o">+</span> <span class="n">target</span> <span class="o">+</span> <span class="s">" with id "</span> <span class="o">+</span> <span class="n">id</span><span class="o">);</span>
<span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
<span class="n">results</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">result</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="s">"Error searching directory "</span> <span class="o">+</span> <span class="n">directory</span> <span class="o">+</span> <span class="s">" for type "</span> <span class="o">+</span> <span class="n">target</span> <span class="o">+</span> <span class="s">" using query "</span> <span class="o">+</span> <span class="n">query</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
<span class="n">closeSearcher</span><span class="o">(</span><span class="n">searcher</span><span class="o">);</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">results</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="nc">String</span> <span class="nf">makeWildcardQuery</span><span class="o">(</span><span class="nc">String</span> <span class="n">query</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">String</span> <span class="n">result</span> <span class="o">=</span> <span class="n">query</span><span class="o">.</span><span class="na">trim</span><span class="o">();</span>
<span class="k">if</span> <span class="o">(</span><span class="mi">0</span> <span class="o">!=</span> <span class="n">result</span><span class="o">.</span><span class="na">length</span><span class="o">())</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(!</span><span class="n">result</span><span class="o">.</span><span class="na">endsWith</span><span class="o">(</span><span class="s">"*"</span><span class="o">))</span> <span class="o">{</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">result</span> <span class="o">+</span> <span class="s">"*"</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">result</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">void</span> <span class="nf">closeSearcher</span><span class="o">(</span><span class="nc">Searcher</span> <span class="n">searcher</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="kc">null</span> <span class="o">!=</span> <span class="n">searcher</span><span class="o">)</span> <span class="o">{</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">searcher</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
<span class="no">LOG</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"Error closing searcher"</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This solution works like a charm, and is easily extensible for future improvements. You can check it out in action by <a href="http://www.codecrate.com/display/SHA/Home">launching the shard-phoenix data management application</a>. Complete source code can be found in the <a href="https://shard.dev.java.net/source/browse/shard/shard-hibernate/">shard-hibernate subproject</a>.</p>
Spring-RCP Manifest Application Descriptor2005-08-14T00:00:00+00:00https://codecrate.com/2005/08/spring-rcp-manifest-application<p>One of my <a href="http://opensource.atlassian.com/projects/spring/browse/RCP-113">first patches to spring-rcp</a> was just applied (partially). My goal was to enhance the ApplicationDescriptor object to pull the version information from a manifest instead of being hardcoded in a spring xml file. This makes sense for me since I package my application using maven, and maven automatically puts the version information directly into the manifest. The patch that was applied creates the ApplicationDescriptor interface, but there’s still no concrete implementation to extract the version from the manifest in spring-rcp.</p>
<p>I figured I might as well post my intent here, and if someone else is interested, maybe someone from spring-rcp will add it to the core.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">com.codecrate.springrcp</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.richclient.application.ApplicationDescriptor</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">ManifestApplicationDescriptor</span> <span class="kd">implements</span> <span class="nc">ApplicationDescriptor</span> <span class="o">{</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">String</span> <span class="n">version</span><span class="o">;</span>
<span class="kd">public</span> <span class="nf">ManifestApplicationDescriptor</span><span class="o">(</span><span class="nc">Class</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
<span class="k">this</span><span class="o">.</span><span class="na">version</span> <span class="o">=</span> <span class="n">target</span><span class="o">.</span><span class="na">getPackage</span><span class="o">().</span><span class="na">getImplementationVersion</span><span class="o">();</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">getVersion</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">version</span><span class="o">;</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">getBuildId</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>And here’s how to wire it up using spring.</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><bean</span> <span class="na">id=</span><span class="s">"applicationDescriptor"</span>
<span class="na">class=</span><span class="s">"com.codecrate.springrcp.ManifestApplicationDescriptor"</span><span class="nt">></span>
<span class="nt"><constructor-arg></span>
<span class="nt"><value></span>foo.bar.myVersionedClass<span class="nt"></value></span>
<span class="nt"></constructor-arg></span>
<span class="nt"></bean></span>
</code></pre></div></div>
<p>There may be some question as to why I leave the build id null. Well, I personally don’t believe in a build id. I believe that every release should be tagged in some way in your source code manager to be 100% reproducable. A user/developer should be able to download the 1.0 branch and have it build exactly the same. A product should use 1.0-SNAPSHOT until it is ready to release, and then branch or tag all files as 1.0 when ready.</p>
Web Development Done Right2005-08-09T00:00:00+00:00https://codecrate.com/2005/08/web-development-done-right<p>My <a href="/2005/02/jsp-is-joke.html">deep burning hate for JSP</a> will never change. It is absolutely the<a href="/2005/02/jsp-late-binding.html">most incompetent</a> Java web technology ever created. Yet, with all of my <a href="/2004/10/two-faces-of-jsp.html">bitching and complaining about JSP</a>, I’ve been fairly quiet on what is a better solution. JSP has been the only option at my day-job, and to be honest, I have not deployed a full blown production application using a different web technology. I’ve used plenty of other frameworks internally or for open-source projects, but JSP is where I’ve spent most of my time (not by choice).</p>
<p><a href="http://jakarta.apache.org/velocity">Velocity</a> is quite possibly the most obvious choise for replacing JSP. It’s easy to pick up and is very similar to JSP in most cases. Velocity has created a certain niche as a tool to be used for user customization. <a href="http://atlassian.com/software/confluence/">Confluence</a> and <a href="http://www.rollerweblogger.org/page/project">Roller</a> are examples of how Velocity can be used for user customization of application templates. Velocity is also great for really enforcing MVC architecture (especially when using something like WebWork), but it doesn’t solve all of my problems.</p>
<p><a href="http://jakarta.apache.org/tapestry/">Tapestry</a> has been in my sights for quite a while, but I haven’t been able to take the plunge to <a href="http://en.wikiquote.org/wiki/Yoda">Unlearn what I have Learned</a>. I’ve gone through examples, tutorials and javadocs, but there’s just something about Tapestry that doesn’t quite feel right. Maybe the tedious xml that’s needed; or maybe it’s requirement to have abstract classes so that Tapestry can auto-proxy your classes. It just seems like I have to jump through so many hoops to get up and going.</p>
<p>And now there’s <a href="http://wicket.sf.net">Wicket</a>. Talk about a mind blowing experience, it literally took me ten minutes to have a sample application up and running! The Wicket API is very Swing like, which was a welcome change for me, and allowed for a very familiar development experience. There is even an extension that allows for direct use of a Swing TreeModel. There are so many things that I like about this framework, but here’s a quick list thus far:</p>
<ol>
<li>
<p>Component framework allows for building a library of reusable building blocks.</p>
</li>
<li>
<p>Example applications are able to run out-of-the-box. The embedded Jetty instance makes startup a snap, and allows for you to start tweaking the example apps to really play around with the API.</p>
</li>
<li>
<p>NO XML!</p>
</li>
</ol>
<p>On the downside, Wicket’s integration with Spring is still lacking. Most current examples that perform database operations use static Hibernate queries, and that’s definately something I want to avoid. It shouldn’t be too difficult to create a Spring PageFactory to allow for dependency injection into the Wicket page objects, hopefully.</p>
Matisse Is Miles Behind2005-07-29T00:00:00+00:00https://codecrate.com/2005/07/matisse-is-miles-behind<p>I’m sick and tired of hearing how <a href="http://www.netbeans.org/kb/articles/matisse.html">project Matisse</a> is the best thing since sliced bread. What is really so new and innovative about it? It’s just another GUI designer with a new layout manager, nothing more. I find it increasingly frustrating to see blogs, <a href="http://weblogs.java.net/blog/gsporar/archive/2005/07/project_matisse_1.html">like this one at java.net</a>, attempt to hype a broken development model.</p>
<p>My biggest complaint with most GUI builders is that they <a href="http://jroller.com/page/wireframe/?anchor=swing_development_the_right_way">lock you into their tool</a>. They generate a block of uneditable/unreadable code that forces you to continue using the tool for the life of your software. Vendor lockin is a term that’s often used (and loathed) in the J2EE world, but how is this any different?</p>
<p>I simply find it unresonable to require all developers to use the same IDE and believe we’ve come to an age of Java development where developers can mix and match tools to their heart’s content. In the end, the bytecode should be all that matters, and a project’s build tool is the common denominator that all developers are forced to use.</p>
<p>I’ve had my hand in swing development for a long time, and I’ve gone through my share of Java GUI builders. All of them have their pros and cons, but <a href="/2004/02/eclipse-visual-editor.html">the Eclipse Visual Editor still stands out as the best GUI designer available</a>. JBuilder, Netbeans, and even UIC fall short of the functionality that comes with <a href="http://www.eclipse.org/vep">Eclipse VEP</a>.</p>
IE Must DIE!2005-07-28T00:00:00+00:00https://codecrate.com/2005/07/ie-must-die<p>Why, oh why, are people still using Internet Explorer? Won’t someone please think of the children! I just spent half of my day troubleshooting a problem that ended up only being reproducable on Windows XP using Internet Explorer. What sucks is that I’m still running Windows 2000, so it was not exactly trivial to figure out where the problem was.</p>
<p>In the end, it all comes down to the way Internet Explorer handles forms. I had a form with a submit button like so:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><input</span> <span class="na">class=</span><span class="s">"submit"</span> <span class="na">type=</span><span class="s">"submit"</span> <span class="na">value=</span><span class="s">"save changes"</span> <span class="na">onClick=</span><span class="s">"javascript:submitForm();"</span><span class="nt">/></span>
</code></pre></div></div>
<p>It may not be the best, but it’s definately valid HTML. The problem is that IE see’s this as a button with a type of submit. When the user clicks on the button it submits the form, and THEN runs the javascript method, which submits the form again. The end result is that very bad things were happening on our backend with the multiple requests coming in.</p>
<p>So, now I have updated my form to be more IE friendly like this:</p>
<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><a</span> <span class="na">href=</span><span class="s">"javascript:submitForm();"</span><span class="nt">></span>save changes<span class="nt"></a></span>
</code></pre></div></div>
<p>rage….for….IE….building……</p>
Actions Speak Louder Than Words2005-07-21T00:00:00+00:00https://codecrate.com/2005/07/actions-speak-louder-than-words<p>To be perfectly blunt, I think javadoc is overrated. Yes, I think it’s important for public API’s or interfaces to be documented, but for the most part, it’s unnecessary work. Let me explain why.</p>
<p>Lately, I’ve been involved in some developer code inspections, and I have come to absolutely loathe them. Here’s a brief synopsis of how our code inspections work:</p>
<ol>
<li>
<p>developer hands print out packet of code sometimes the size of a small book.</p>
</li>
<li>
<p>reviewers read code as if it were meaningful.</p>
</li>
<li>
<p>reviewers can’t comment much since all they’re looking for are simple syntax errors that were already caught by the developer’s IDE.</p>
</li>
<li>
<p>reviewers understanding of code is limited to the documentation provided in said code.</p>
</li>
<li>
<p>reviewers read javadocs as basis for what work is performed in code without really understanding the implementation.</p>
</li>
<li>
<p>reviewers happily sign off on code as if they made a difference.</p>
</li>
</ol>
<p>What I’ve come to realize is how pointless it is to review someone else’s code in this way. Personally, I don’t care “how” they implement it, as long as it works. And within that last statement lies the key to better code reviews. Instead of reviewing someone’s code, I would much rather review their unit tests. Reading through a unit test shows you how the code works instead of the javadocs telling you how they work. This is very closely related to my previous post about <a href="/2005/02/document-code-with-units-of-work.html">using code to document units of work</a>.</p>
<p>Which chunk of code do you trust more?</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
* method to do stuff.
* @param target non-null object to work with.
* @throws IllegalArgumentException when target is null.
*/</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">doSomething</span><span class="o">(</span><span class="nc">Object</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//do some work here</span>
<span class="c1">//check for null</span>
<span class="k">if</span> <span class="o">(</span><span class="kc">null</span> <span class="o">==</span> <span class="n">target</span><span class="o">)</span> <span class="o">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">IllegalArgumentException</span><span class="o">(</span><span class="s">"YOU IDIOT!"</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>OR</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kt">void</span> <span class="nf">testErrorGeneratedWhenPassedNull</span><span class="o">()</span> <span class="o">{</span>
<span class="k">try</span> <span class="o">{</span>
<span class="n">myObject</span><span class="o">.</span><span class="na">doSomething</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span>
<span class="n">fail</span><span class="o">(</span><span class="s">"Error should have occurred"</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span><span class="o">(</span><span class="nc">IllegalArgumentException</span> <span class="n">expected</span><span class="o">)</span> <span class="o">{</span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>As a side note, I think the <a href="http://collab.netbeans.org">developer collaboration tools being integrated into NetBeans</a> does allow for more meaningful code review since the reviewer can use an IDE to dig into the code. I’ve tried them out, and would love to see these tools ported to Eclipse.</p>
Deploying Webstart Apps with Maven2005-07-11T00:00:00+00:00https://codecrate.com/2005/07/deploying-webstart-apps-with-maven<p>First, let me describe my goal. I would like to be able to deploy my current <a href="http://shard.codecrate.com">webstart applications</a> using maven. In the past, I’ve deployed internal corporate applications using webstart, but deploying a public customer application is quite different. With an internal application, you can dicate or force all users to be running the most current (SNAPSHOT) version. This is not the case when you are dealing with a public app. For example, I would like to allow users running version 0.3 of my application to continue using that version until they decide to run version 0.4. This would also allow for early adopters to run the next SNAPSHOT version while maintaining their current stable installation.</p>
<p>The current Maven support for deploying webstart applications is pretty weak. I’m currently using a postGoal to build and package the webstart files with my <a href="http://shard.codecrate.com">main project site documentation</a>. Then, when I deploy my site, the webstart files are included and hosted by the same webserver that hosts the project docs.</p>
<p>This definately isn’t desirable, since I want to concurrently serve up multiple versions of the same artifact. The only way around this would be to have completely different sites for each version of the artifact.</p>
<p>The repository layout for maven2 seems to almost solve my problems. It provides a versioned layout for artifacts, which has been my largest problem thus far. This type of layout would be usuable for most of my use cases:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>myProject/
/jnlps/
/1.0/myProject-1.0.jnlp
/myProject-1.0.jar
/projectDependency-2.0.jar
</code></pre></div></div>
<p>Deploying the dependencies along with the artifacts is not currently supported, and I would be very interested to hear if maven2 will offer better support for deployment of webstart (or just plain desktop) applications.</p>
<p>All Webstart applications still have the basic problem that the .jnlp file has to be hardcoded with the servername and path. This restricts the deployment of the application to one location and can’t be rsync’d to other servers that act as mirrors. For example, if my application is to be deployed on <a href="http://www.ibiblio.org/maven">ibiblio</a>, I have to hardcode that in the .jnlp file which means, it won’t run if it’s hosted just on my <a href="http://maven.codecrate.com">codecrate maven repository</a>.</p>
D20 Computer Gaming2005-07-05T00:00:00+00:00https://codecrate.com/2005/07/d20-computer-gaming<p><a href="http://nwn.bioware.com">Neverwinter Nights</a> is still one of my favorite games. It was one of the most <a href="http://nwvault.ign.com/">community focused games</a> I have ever seen. Not only were people able to build <a href="http://nwvault.ign.com/View.php?view=Modules.DMFM">cool little mods</a> for the game, some developers have <a href="http://nwn.bioware.com/premium/">built adventures that rival the original game’s content</a>.</p>
<p>There are two new D&D games coming out soon that I have taken interest to. The first is a MMORPG called <a href="http://www.ddo.com/index.php">Dungeons & Dragons Online</a>. The other is a real time strategy game called <a href="http://www.atari.com/dragonshard/home">Dragonshard</a>. I don’t know too much about these projects, but I have found out some gameplay information that I think is pretty sweet. One of my gripes with the original Neverwinter Nights was how they implemented spell memorization. It was very cumbersome at higher levels, and the fact that you had to rest in order to regain spells was a major slowdown for gameplay. That is why I was so glad to hear that <a href="http://www.ddo.com/index.php?page_id=84">Dungeons & Dragons Online has decided to use spellpoints instead of spells per day</a>. I strongly believe that the spellpoints magic system is much more usable for computer gaming than the traditional spells per day.</p>
<p>I fully plan to implement both traditional and spellpoint magic systems into shard. There are several other optional rules, like the Star Wars Wound System, that make sense to add to shard as well. Increasing the flexability and options for shard will increase the number of places that it can be used. It is completely feasible that a game like Dungeons & Dragons Online could use shard for it’s underlying gaming engine.</p>
<p>And in case anyone is wondering if I copied the Dragonshard name for my shard project, I can assure you I did not. Shard started out as a custom RPG engine I wrote, but never released, way back before d20 was released. Once d20 emerged, and I saw how well done the system was, I changed the focus of my old project to be what it is today and kept the same name.</p>
SuSE Wireless Woes2005-06-28T00:00:00+00:00https://codecrate.com/2005/06/suse-wireless-woes<p>I have now spent three days trying to upgrade my wife’s computer from SuSE 9.1 to SuSE 9.3. I was hoping that the setup of my wireless USB adapter would go smoother than <a href="/2005/06/suse-91-usb-wireless-configuration.html">last time</a> but, I’m sad to say that 9.3 is actually much worse.</p>
<p>My hopes were high when I first plugged in my USB adapter. Yast instantly recognized and installed drivers, and for about 5-10 minutes all was right in the world. I should have known that it was too easy, and wouldn’t last. After about 10 minutes, my system locked up and was completely unresponsive. A hard shutdown was the only solution, and after the system rebooted, it would run for about 5 minutes more before locking up again. <a href="http://www.linuxquestions.org/questions/archive/41/2005/05/2/315331">Seems like all atmel usb cards lock up in SuSE 9.3</a>. All sources point to <a href="http://lists.suse.com/archive/suse-amd64/2005-Apr/0152.html">these problems being with 9.3</a>, since the same adapters worked with 9.1 and 9.2.</p>
<p>A bit of googling suggested trying to configure the USB adapter to use the original Windows drivers and emulate them under Linux using <a href="http://ndiswrapper.sf.net">ndiswrapper</a>. Several hours later, I was no closer to a solution.</p>
<p>After jumping through hoops to try and get my Belkin adapter to work, I decided my time would be better spent elsewhere. Since I run Linksys networking equipment for my house, I bought a Linksys WUSB11v4 Adapter in hopes that it would be better supported. My assumption that Linksys would be easier, was sorely mistaken.</p>
<p>For starters, the Linksys was not even recognized by Yast. Several forums recommended installing <a href="http://at76c503a.berlios.de/">the berilios driver</a>, but <a href="http://at76c503a.berlios.de/devices.html">the driver only supports version 2.1, 2.6 and 2.8</a>, which does me a lot of good. I don’t exactly find it comforting when the driver everyone is told to install, is almost 2 versions behind released hardware. In fact, <a href="http://forum.netgem.com/viewtopic.php?t=2650&start=10&sid=95d387067551ab63a832045f11482451">some people have recommended buying the older adapters off eBay</a> to get around this problem. I forged ahead and tried the driver anyways to no avail.</p>
<p>Needless to say, I will be reinstalling, for the seventh time, with SuSE 9.2 tonight. It looks like <a href="http://nixdoc.net/files/forum/about41079.html">one person appears to have gotten around this issue</a>, but with no documentation posted, I’m not messing around with it.</p>
SuSE 9.1 USB Wireless Configuration2005-06-28T00:00:00+00:00https://codecrate.com/2005/06/suse-91-usb-wireless-configuration<p>My love for SuSE was almost lost while trying to setup a Belkin wireless USB adapter (F5D6050 version 2000) for my PC. My problems were rooted in the fact that I have a standard ethernet card and the USB adapter. They did not play well together, and for the record (and hopefully for others who need the info), here were the steps to get it up and going:</p>
<ul>
<li>
<p>Use YAST to install atmel driver.</p>
</li>
<li>
<p>Plug USB adapter into PC (if already plugged in, need to unplug then plug back in).</p>
</li>
<li>
<p>run ifconfigto see that adapter obtained IP address.</p>
</li>
<li>
<p>run ifdown eth0to disable the ethernet card.</p>
</li>
<li>
<p>run ifdown wlan0to disable the USB adapter.</p>
</li>
<li>
<p>run ifup wlan0to re-enable the USB adapter.</p>
</li>
</ul>
<p>I’ll be trying this again when I reinstall with SuSE 9.3, so we’ll se if things go any smoother.</p>
Code Investment2005-06-23T00:00:00+00:00https://codecrate.com/2005/06/code-investment<p>I always knew that working on open source projects was an investment of time, but now I can see how much it would cost! <a href="http://www.koders.com">Koders.com</a> has <a href="http://koders.com/info.aspx?c=ProjectInfo&pid=GYFTMVZ9VHGEKM6VN8P6BZ4MXF">estimated development costs for shard</a>, based on some basic formulas like: LINES_OF_CODE x COST_PER_1000_LINES. To be honest, it’s a little lower than what I expected. They don’t have all of the source code available yet (shard-minotaur is not there), so those numbers might increase once they have the complete project.</p>
<p>I’ll have to be careful who I show this to. I don’t think my wife was too impressed when she thought of how much I’ve invested in this project that could have been spent doing more freelance consulting.</p>
SwingFX for Spring-RCP2005-06-21T00:00:00+00:00https://codecrate.com/2005/06/swingfx-for-spring-rcp<p>I’ve been continually impressed by the Swing tricks that <a href="http://www.jroller.com/page/gfx">Romain Guy has published on his blog</a>. I’m convinced that Swing applications don’t need to look as crappy as they commonly do. Since I’ve been digging into <a href="http://www.springframework.org/spring-rcp">Spring-RCP</a> lately, I decided to try and bring some of Romain’s innovations over to Spring. This would allow for simple applications to get going quickly and look great without having to re-implement all the nice to have features.</p>
<p>My first feature is an attempt to add support for <a href="http://www.jroller.com/page/gfx/?anchor=better_shadow">nice looking drop shadows on startup splash screens</a>. Romain’s code was very easy to follow, and it was fairly trivial to port it to Spring-RCP. I’ve opened <a href="http://opensource.atlassian.com/projects/spring/browse/RCP-126">a new issue on the Spring-RCP JIRA with a complete patch for this feature</a>, and if anyone is interested in seeing this feature in Spring-RCP, please vote for it! My current implementaion could be improved to allow for applications to choose which splash screen to display (original or drop shadowed), so maybe I’ll put some more time into this feature soon.</p>
<p>My next challange will be to add a new splash screen that tracks the progress of the Spring initialization. I find it quite annoying that there’s currently no feedback to show the user how long startup will take. I opened this as a <a href="http://opensource.atlassian.com/projects/spring/browse/RCP-112">seperate issue in JIRA</a>, and will hopefully have something up and running soon.</p>
New Eclipse 3.1 Features2005-06-16T00:00:00+00:00https://codecrate.com/2005/06/new-eclipse-31-features<p>Wow, I just installed eclipse 3.1 RC2 and there are a few new features that I think are pretty impressive. Performance is definately better than 3.0.x, but that is really just an improvement and not a new feature.</p>
<p>New Execute/Debug Shortcuts</p>
<p>In Eclipse 3.0.x, there was no shortcut defined for Run -> Debug As and Run -> Run As actions. I used to do Alt + R -> A to bring up the list of debug actions. For example, to launch my current class as a Junit Test, I would use do Alt + R -> A -> 4. This definately had it’s issues since the list of options would change if additional eclipse plugins were installed.</p>
<p>Eclipse 3.1 has added two new shortcuts for launching and debugging code. Alt + Shift + X is the new shortcut to eXecute code without breakpoints. Alt + Shift + D can be used to Debug code with breakpoints enabled. Both of these commands trigger a small popup with options to launch the current code as. The new options are keyed by letter so that typing J will launch/debug Java applications, and T will launch/debug JUnit Tests. The popup is a bit difficult to see, but it does the job okay. These new shortcuts are much more convenient than the old navigation, and I’m very glad to see them included in Eclipse 3.1.</p>
<p>CVS Commit Sets</p>
<p>This is a major innovation in my opinion. It’s absolutely essential for me, since I’m usually working on multiple unrelated features at the same time. It’s great to be able to group my changes as I code instead of scratching my head days later trying to figure out what file is for what change. I’ve used several IDE’s over the years and I have never seen any IDE with such complete CVS integration. Eclipse’s CVS integration is one of the main reasons I haven’t dug into NetBeans. I’m sure NetBean’s CVS integration has gotten better, but it was nothing special when I used it last. And don’t even get me started on JDeveloper’s pathetic CVS integration. I hope that Eclipse will give integration with <a href="http://subversion.tigris.org">subversion</a> as much time as their CVS support.</p>
Spring-RCP Snapshots Available2005-06-15T00:00:00+00:00https://codecrate.com/2005/06/spring-rcp-snapshots-available<p>I’ve been putting in a fair amount of work lately on two spring-rcp applications for <a href="http://shard.codecrate.com">shard</a>. One is for managing all customizable d20 data, and the other is a character generator. Shard is built using maven, and since spring-rcp does not have any published artifacts (or snapshots), it’s been a bit of a pain to integrate the applications into my build process.</p>
<p>To solve this problem, I decided to publish <a href="http://maven.codecrate.com/spring-rcp/jars/">CVS snapshots of spring-rcp</a> on <a href="http://maven.codecrate.com">my public maven repository</a>. Anyone interested in developing a spring-rcp application with maven can simply update their list of repositories to include my server.</p>
<p>project.properties</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#repository settings
maven.repo.remote=http://maven.codecrate.com,http://www.ibiblio.org/maven
</code></pre></div></div>
<p>I’ve also included <a href="http://maven.codecrate.com/javahelp/jars/">other dependencies</a> that spring-rcp required to get my applications up and running. These dependencies weren’t available at <a href="http://www.ibiblio.org/maven">ibiblio</a>. If there is not a release sometime soon of spring-rcp, I may continue to publish updated CVS snapshots from time to time.</p>
Swingwork to Springwork?2005-06-10T00:00:00+00:00https://codecrate.com/2005/06/swingwork-to-springwork<p>It seems that my early adoption of <a href="http://www.nanocontainer.org">nanocontainer</a> may not have been the best move for <a href="http://swingwork.codecrate.com">swingwork</a>. There’s very little development being done on nanocontainer and extremely poor community support. It’s basically vaporware. I was orignally impressed with their <a href="http://www.nanocontainer.org/NanoWar+WebWork">webwork2 integration</a> and thought it would be fairly trivial to port the functionality to xwork/swingwork. This was obviously a mistake…</p>
<p>I’ve been digging into the new <a href="http://www.springframework.org/spring-rcp">spring-rcp project</a> recently and can only describe it as, <a href="http://en.wikiquote.org/wiki/Darth_Vader">“Impressive…most impressive”</a>. It’s most powerful feature, in my opinion, is that Swing components can now benefit from dependency injection, and that was my original reason for integrating swingwork with nanocontainer. The project is still very early, and documentation is severely lacking, but they have a very good petclinic demo to dig through as an example. It takes a bit of work to get up and going, but there is a very active community and there are <a href="https://jide-springrcp.dev.java.net/">extension projects</a> being developed to extend the core spring-rcp functionality.</p>
<p><a href="http://wiki.opensymphony.com/display/WW/WebWork+2+Spring+Integration">XWork can use Spring internally for true IoC</a>, so I wonder if there would be any benefit to porting swingwork to use spring internally? Would swingwork really be any different than spring-rcp?</p>
<p>Right now, I’m totally sold on spring. The <a href="http://www.picocontainer.org/Container+Comparison">core functionality provided by spring and picocontainer</a> are very similar, but the spring community is what really makes it worthwhile. An active community should definately be considered when adopting a new library/framework.</p>
IDE Competition is Good2005-06-10T00:00:00+00:00https://codecrate.com/2005/06/ide-competition-is-good<p>I’ve gone through my share of development IDE’s. First it was JBuilder, then NetBeans, now Eclipse. There have been many reasons over the years for me to switch IDE’s (price, features, speed), and I have stuck with Eclipse for the past two years because it “just works”. At least it did work until I <a href="http://www.jroller.com/page/wireframe/20050113#legal_beagle">migrated my development environment from Windows to Linux</a>, and noticed that the performance of Eclipse went down the toilet. Seriously, I’m working with 1GB of RAM, SATA hard drive and a 2.4 Ghz P4. I just can’t excuse the kind of performance I’m seeing.</p>
<p>This has caused me to rethink why I moved to Eclipse. I originally switched from NetBeans to Eclipse because NetBeans was sooo slooow, but now it seems like NetBeans may have finally stepped up to the plate to address their slowness. This <a href="http://cld.blog-city.com/read/1126337.htm">blog from a NetBean’s developer</a> provides some EXCELLENT insight into what NetBeans has done to improve their IDE. His view is biased (since he is a NetBeans developer), yet I found it very fair and informational. I think the ONLY reason that the NetBeans team has invested so much time into the area of performance is because of the threat of Eclipse. And in the end, competition is good for us developers. Each IDE pushes the envelope a bit further and forces the other IDE’s to play catchup. The area of refactoring is one particular “hot topic” where Eclipse has offered a plethora of features that NetBeans is just beginning to roll out.</p>
<p>I can now faithfully say that my previous blog claiming that
<a href="/2004/07/no-jsr-for-swt.html">SWT was the wrong choice for Eclipse was correct</a>.
Eclipse developers are now stuck improving their SWT client libraries across multiple hardware configurations, instead of improving their IDE and rich client support. Swing is NOT slow, and it has been proven time and time again to be the right direction for client side Java development. Sun has thrown a TON of resources at Swing, starting with JDK 1.4, and the work that is being done in this area is very encouraging. Has anyone out there seen the <a href="http://today.java.net/pub/a/today/2004/11/12/graphics2d.html">OpenGL integration</a> for the <a href="http://weblogs.java.net/blog/campbell/archive/2005/03/strcrazy_improv_1.html">Java2D pipeline</a>!?!? This is the kind of stuff that makes me excited to be working on Swing applications. If Swing or AWT is broken, as some people claim, PROVE IT! And now, with the next release of Java, we can actually <a href="https://mustang.dev.java.net/collaborate.html">fix the problem</a>, instead of investing resources into a seperate solution.</p>
Mocking java.lang.Object methods2005-05-11T00:00:00+00:00https://codecrate.com/2005/05/mocking-javalangobject-methods<p>I’ve run into an issue with mock frameworks not being able to mock out methods from java.lang.Object (hashCode, equals, toString). Here’s a simple usecase:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SimpleUseCase</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">doSomething</span><span class="o">(</span><span class="nc">Object</span> <span class="n">bean1</span><span class="o">,</span> <span class="nc">Object</span> <span class="n">bean2</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">bean1</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">bean2</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//do interesting work here.</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I’ve been working with two mocking frameworks, <a href="http://jmock.org">jmock</a> and <a href="http://easymock.org">easymock</a>. Each of these frameworks have aspects that I like, and I’m not going to go into a comparison of the two right now, but it was very surprising to me that both of these frameworks are unable to be used in testing the above use case.</p>
<p>Easymock has the limitation <a href="http://www.easymock.org/Documentation.html">stated explicitly at the very bottom of their website</a>, but they don’t provide alternatives. Here’s the documentation provided by easymock:</p>
<p>The behavior for the three object methods equals(), hashCode() and toString() cannot be changed for Mock Objects created with EasyMock, even if they are part of the interface for which the Mock Object is created.</p>
<p>I was able to track down <a href="http://jira.codehaus.org/browse/JMOCK-55">an issue for jmock</a> to fix this limitation, and according to JIRA, it is supposedly been fixed in CVS. Looking through <a href="http://cvs.jmock.org/viewrep/jmock/jmock/core/src/org/jmock/builder/InvocationMockerBuilder.java">the files changed for the issue</a> didn’t uncover any relevent code or fixes, and there were don’t appear to be any test cases for this scenerio either. I’m not sure that this change actually exists, and if it does exist, I don’t know what release it is in. It might be sitting in CVS awaiting the next release… Jmock should really try to improve their project roadmap and changelog management.</p>
<p>Unfortunately, the only way I’ve found around this issue is to not use the standard java.lang.Object methods. Instead of using .equals(), I have been creating a similar method .isSame() (although I should probably name it isEqual()).</p>
Spring Versus The World2005-05-03T00:00:00+00:00https://codecrate.com/2005/05/spring-versus-world<p>I sometimes find it hard to make it through some of the postings on <a href="http://www.theserverside.com">The Server Side</a>. So many of the articles spiral into some kind of religious debate over .NET versus J2EE, or Tapestry versus JSF. It’s as bad as trying to read something on <a href="http://www.slashdot.org">Slashdot</a>.</p>
<p>Surprisingly, there was an <a href="http://www.theserverside.com/news/thread.tss?thread_id=33576">article posted last week</a>, that was actually informative in the whole web framework debate. A pair of developers entered a [rapid application development contest](<br />http://www.xebia.com/oth_publications_java_with_spring_just_as_productive_as_4gl.html) where every pair of developers used a different set of tools. They entered the competition using only opensource libraries at their disposal against J2EE, .NET and a slew of other development environments. I’m curious to know if any group of developers used Ruby on Rails? Instead of simply posting meaningless productivity benchmarks and claiming that a particular framework/toolset/IDE improves application development, this kind of competition is a real life use case. The opensource developer’s toolset consisted of:</p>
<ul>
<li>
<p><a href="http://www.springframework.org">Spring Framework</a></p>
</li>
<li>
<p><a href="http://www.eclipse.org">Eclipse IDE</a>with <a href="http://eclipse.org/webtools/index.html">Eclipse Web Tools Platform</a></p>
</li>
<li>
<p><a href="http://www.hibernate.org">Hibernate</a></p>
</li>
<li>
<p>Hibernate Synchronizer Eclipse plugin</p>
</li>
<li>
<p><a href="http://jakarta.apache.org/tomcat">Tomcat</a></p>
</li>
<li>
<p><a href="http://www.mysql.org">MySQL</a></p>
</li>
</ul>
<p>One of the most interesting pieces in this article is that the Spring developers claim their biggest pain point was developing the user interface. There’s no doubt in my mind that the root of this problem is that they decided to use JSP as their view technology. <a href="/2004/10/two-faces-of-jsp.html">I’ve said it once</a>, and <a href="/2005/02/jsp-late-binding.html">I’ll say it again</a>, <a href="/2005/02/jsp-is-joke.html">JSP is the bane of Java web technologies</a>. Some insightful posters at The Server Side commented that the developers could have easily improved their productivity by using a different view technology like Tapestry/Spindle or Wicket. I also question their use of the Eclipse Web Tools plugin for web development just because it’s still very early. I personally tried out the plugin and didn’t find it entirely useful or functional yet.</p>
<p>Unfortunately, the Spring developers placed in third, within 10% of the Oracle Toolset. I find it very encouraging to know that I have the best frameworks and tools at my fingertips that allow me to be more than competitive against the <a href="/2004/07/oracle-toy-store.html">big, bloated, expensive, commercial tools</a>. And now I can see where Oracle gets their <a href="/2004/07/oracle-foolset.html">pathetic claims of being 30% faster for developing web applications</a>. Developing with Spring and a standard WYSIWYG HTML editor I can develop just as fast, and create web applications a hell of a lot better.</p>
The Folly of Multilanguage Development2005-05-02T00:00:00+00:00https://codecrate.com/2005/05/folly-of-multilanguage-development<p>Let me state outright that cohesion between desperate development environments is overhyped. I fail to see how .NET can promote multilanguage development as an asset, since a fragmented development environment is anything but desirable. For example, if you’re developing an application with two people in two languages, what happens if one person leaves? That’s a simplified scenario of a major problem.</p>
<p>My previous employer is in the works to move to a new development platform (Oracle Forms) as a means to get applications out the door quicker. They believe that the “Oracle Platform” can produce applications with less time than “conventional” programming. That’s all fine and dandy, except for their intent to still use Java for applications. There is one fundamental flaw with this argument that has somehow escaped their view: the addition of another platform only fragments development further instead of unifying it.</p>
<ul>
<li>
<p>Java</p>
</li>
<li>
<p>Perl</p>
</li>
<li>
<p>PowerBuilder</p>
</li>
<li>
<p>SAP</p>
</li>
<li>
<p>Oracle Forms</p>
</li>
</ul>
<p>This is why I see the Java platform as the only choice for buisness application development. It runs the guantlet for the most diverse set of API’s and tools to cover any business need. From web applications and serverside services, to client side applications, Java is the only platform that allows developers to not only diversify to tackle any business need, but all so stay unified on one platform of development. Arguments against Java in the business world commonly point to the lack of Rapid Application Development (RAD) tools. More often then not, they are refering to developing Swing clients without a visual editor. RAD platforms like Visual Basic have their place, but definately not in the business world. Prototyping application with VB is fine, but essentially you’ve invested time in “throw away code”. When it comes down to mission critical, scalable applications, Java has shown it’s strength.</p>
Combining Project Support Tools2005-05-02T00:00:00+00:00https://codecrate.com/2005/05/combining-project-support-tools<p>There are a variety of tools out there that can be used to provide project support. I feel like these different tools need to converge somewhere to allow for users/developers easier access to information and feedback. Here are the current tools in use by projects today. All of them have their advantages and disadvantages, but the one thing they all have in common is that noone has found a way to combine and leverage all of these tools together.</p>
<p>Mailing Lists</p>
<p>Favored by developers, and shunned by users.</p>
<p>Forums</p>
<p>Slick user interfaces usually with built in search tools. Slower than mailing lists. Some forums are starting to integrate with mailing lists so that posting on one, will automatically post on the other. Most forums have functionality to display “current logged in users” (based off a session cookie).</p>
<p>Realtime Messaging</p>
<p>IRC, and online chat (instant messenger) tools fall into this category.</p>
<p>I wonder how difficult it would be for online forums to be integrated with a messaging client? It’d be nice see online forums integrate the list of online users with who’s logged into a common chatroom. Posts to that chatroom would be automatically posted on the forums as well (for archiving and searching purposes). Perhaps a certain posting syntax would be required in order to avoid “TONS” of extra noise. Here would be my ideal solution:</p>
<ol>
<li>
<p>A user is looking for help/information so they hop on the project forums first. The forums list several users/developers as “online”, and have a public chatroom available for the user to connect to.</p>
</li>
<li>
<p>The user joins the public chatroom and posts a question (which noone was able to answer).</p>
</li>
<li>
<p>The forum software automatically saves this post and sends out a cross-post to the pre-configured mailing list.</p>
</li>
<li>
<p>A developer who is not online, gets the email and replies back with an answer.</p>
</li>
<li>
<p>The forum software automatically saves this post and sends out an email to the user that their question has been answered.</p>
</li>
</ol>
<p><a href="http://www.jivesoftware.com/support-suite.jsp">Jive Software</a> seems to have a start on this idea by combining these tools, but unfortunately it’s also extremely pricey. Anyone out there seen something that opensource communities have done to solve this problem?</p>
HSQLDB Rocks2005-04-27T00:00:00+00:00https://codecrate.com/2005/04/hsqldb-rocks<p>After walking down the Test Driven Development path for the past year or so, I adopted the usual philosophy that unit tests should not interact with any external systems (webservices, databases, etc). This was all well and good for unit tests, but I have come across a number of instances where unit tests fall short of full code coverage. I have recently found a HUGE amout of value in other forms of software testing. Specifically, I have been implementing acceptance tests using the <a href="http://fit.c2.com/">FIT framework</a>, and these tests run with a full blown application instance (database, application server, etc).</p>
<p>This got me thinking that it would be very nice to use some kind of automated integration tests to verify that my Hibernate HQL was correctly formed. I definitely didn’t want to go down the path of installing something like <a href="http://www.mysql.com">MySQL</a> just to run these tests, and I didn’t want to have to rely on some external database being up and running all the time. <a href="http://hsqldb.sourceforge.net/">HSQLDB</a> is the perfect solution for this scenario. There’s even a built in <a href="http://hsqldb.sourceforge.net/doc/guide/apf.html">Swing Database Manager</a> that can view the contents of this scrap database for full debugging (org.hsqldb.util.DatabaseManagerSwing).</p>
<p>I should say that none of this would be possible without using Hibernate’s HSQLDB dialect. It’s pretty amazing that I can develop and run integration tests against an extremely lightweight embedded database and deploy the code to run against a different (more production like) database by only changing the configuration file.</p>
SNAPSHOT acceptance2005-03-31T00:00:00+00:00https://codecrate.com/2005/03/snapshot-acceptance<p>I just recently had a run-in with one of the XDoclet2 developers regarding the current hibernate plugin. Sure, <a href="http://jira.codehaus.org/browse/XDP-42">the issues I have raised</a> are “Fixed in CVS”, but the <a href="http://dist.codehaus.org/xdoclet-plugins/jars/xdoclet-plugin-hibernate-20050222.202417.jar">SNAPSHOT jar</a> is still several weeks old and without the fixes. It’s not so much a problem for me personally to download and build the jar, but I am more concerned with other developers on my projects. I use maven to resolve my project dependencies so that beginning developers do not have to worry about getting out of synch. This is especially useful in a continuous integration environment when SNAPSHOT builds can be published by other developers, and automatically picked up on the next local build.</p>
<p>I find it confusing that in this day and age, I still hear so many developers suggest for users to “Just download the code and build from CVS.” With tools like <a href="http://cruisecontrol.sf.net">cruisecontrol</a> and <a href="http://maven.apache.org">maven</a> around that understand SNAPSHOT software, why aren’t projects taking advantage of this!? When I look at a project and see they offer a SNAPSHOT version, I think to myself, “How nice. If I have any problems with this version, I will automatically pick up the latest changes when they are published.” So, it is very misleading when SNAPSHOT versions of projects are anything but SNAPSHOTS. I think the bottom line is that if projects are not going to keep SNAPSHOT versions of their software uptodate, I don’t think they should be using them.</p>
Spring's Biggest Benefit2005-03-24T00:00:00+00:00https://codecrate.com/2005/03/spring-biggest-benefit<p>Here’s a word of warning for all those developers out there that haven’t used spring yet, be careful because spring is contagious. I’ve been working with spring for a couple weeks now and decided to try and integrate it into shard to help out with the management of my hibernate configuration. It worked extremely well. Indeed, it worked so well, I decided to expand my scope and use spring to wire up and manage my velocity configurations as well.</p>
<p>This is when I discovered what I believe to be spring’s strongest selling point; Centralization of Configuration. Spring makes it extremely easy to plug in central management points for internal libraries as well as third party packages.</p>
<p>As an example, I was setting up hibernate in my tests by hand which was extremely brittle since actual users may not use the exact same configuration. Now, my tests are able to excersize that my spring configuration is setup correctly.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//old test case setup</span>
<span class="kd">public</span> <span class="nf">ShardHibernateDbUnitTestCaseSupport</span><span class="o">(</span><span class="nc">String</span> <span class="n">name</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
<span class="nc">File</span> <span class="n">file</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">File</span><span class="o">(</span><span class="s">"src/hibernate/hibernate.cfg.xml"</span><span class="o">);</span>
<span class="n">sessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Configuration</span><span class="o">().</span><span class="na">configure</span><span class="o">(</span><span class="n">file</span><span class="o">).</span><span class="na">buildSessionFactory</span><span class="o">();</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">sessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">();</span>
<span class="n">connection</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="na">connection</span><span class="o">();</span>
<span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//new testcase setup</span>
<span class="kd">public</span> <span class="nf">ShardHibernateDbUnitTestCaseSupport</span><span class="o">(</span><span class="nc">String</span> <span class="n">name</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">Exception</span> <span class="o">{</span>
<span class="kd">super</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
<span class="nc">String</span><span class="o">[]</span> <span class="n">paths</span> <span class="o">=</span> <span class="o">{</span><span class="s">"/shard-hibernate-context.xml"</span><span class="o">};</span>
<span class="n">context</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ClassPathXmlApplicationContext</span><span class="o">(</span><span class="n">paths</span><span class="o">);</span>
<span class="n">sessionFactory</span> <span class="o">=</span> <span class="o">(</span><span class="nc">SessionFactory</span><span class="o">)</span> <span class="n">context</span><span class="o">.</span><span class="na">getBean</span><span class="o">(</span><span class="s">"sessionFactory"</span><span class="o">);</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">sessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">();</span>
<span class="n">connection</span> <span class="o">=</span> <span class="n">session</span><span class="o">.</span><span class="na">connection</span><span class="o">();</span>
<span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Some may argue that this is crossing a boundry and that these tests are no longer unit tests. This may be true, and these may now be considered integration tests, but I have much higher confidence in releasing a project with these kinds of tests over strickly unit tested code. Mainly, I feel more confident that a user will be able to “plug-n-play” with my libraries since I can now test that the spring application configuration is working correctly.</p>
First Class Tools2005-03-22T00:00:00+00:00https://codecrate.com/2005/03/first-class-tools<p>Here’s a word of wisdom to all prospective open source projects, “Consider integration with other tools a first-class priority”. It’s so refreshing to see a project like spring take this approach by actively developing a <a href="http://springide-eclip.sourceforge.net/">Spring Eclipse Plugin</a>.</p>
<p>I usually agree with the open source motto coined by Hibernate, <a href="http://hibernate.org/38.html">do ONE thing well</a> (empahsis mine), but even hibernate has forged ahead and developed <a href="http://tools.hibernate.org">their own toolset</a>. What does this mean? While I agree that projects should avoid feature bloat and try to do too many things (<em>cough</em> XWork <em>cough</em>), it’s apparent that a successful project should encompass tools to make it easier for developers to adopt the project. The general consensus thus far has been that most open source projects should consist simply of the “core project” and it should be up to some other project to develop and release tools.</p>
<p><a href="http://jakarta.apache.org/tapestry/">Tapestry</a> and <a href="http://spindle.sourceforge.net/">spindle</a> as one example of this strategy; They are separate, but spindle could not exist without tapestry. In the grand scheme of things, could tapestry exist without spindle? Of course, but I’m not so sure that other open source projects COULD exist without their accompanying tools.</p>
The Re-Re-Release2005-03-18T00:00:00+00:00https://codecrate.com/2005/03/re-re-release<p>Yep, George Lucas is at it again. He’s now planning to <a href="http://today.reuters.co.uk/news/newsArticle.aspx?type=entertainmentNews&storyID=2005-03-18T085249Z_01_DEN830004_RTRUKOC_0_FILM-3D.xml">redo the entire Star Wars series in 3-D</a>. It’s finally official that Lucas has no integrity or talent. How can he pander a 20 year old film every couple years as his “true and ultimate vision”.</p>
<p>I love Star Wars (No thanks to George Lucas) since Episode V: Empire Strikes Back is by FAR the best of the series and Lucas had little to do with its brillience.</p>
<p>I think Obiwan said it best, “It’s as if a million voices all cried out in agony, and were suddenly silenced.” I think I’m going to cry myself to sleep tonight…</p>
Spring Web Flow2005-03-16T00:00:00+00:00https://codecrate.com/2005/03/spring-web-flow<p>It looks like there’s yet another web framework to check out. The <a href="http://opensource.atlassian.com/confluence/spring/display/WEBFLOW/Home">Spring Web Flow</a> framework appears to have taken a very similar approach to actions and their results as <a href="http://www.opensymphony.com/webwork">WebWork2</a>, yet I hope that this new project will prove to be more useful than the over engineered, hyper flexible Spring MVC framework. From my experience, these command pattern frameworks are by far the best development strategy for web applications, and should be a welcome addition to the Spring library. Hopefully it will replace the existing MVC framework altogether, since it certainly won’t be difficult to be better than what’s currently offered.</p>
<p>After <a href="http://opensource.atlassian.com/confluence/spring/display/WEBFLOW/Practical+Guide">a bit of reading</a> I really like how the framework can be configured programatically and doesn’t mandate the use of XML, which is a welcome change from the fighting I’ve done with the internals of the WebWork2 and XWork. You know, Spring definately has an edge in framework elegance, and making things as simple as possible. That being said, WebWork2 and XWork do an excellent job of abstracting away the internals of dealing with the HTTP environment. <a href="http://swingwork.codecrate.com">SwingWork</a> is proof that the command pattern framework makes sense for client side development as well. Heck, I can even reuse my “web” actions, on the client side, with no code changes. This is not possible with the current Spring Web Flow API since it is heavily tied to the servlet container.</p>
<p>So, maybe <a href="/2005/01/webwork-over-spring-mvc.html">my previous post</a> about using WebWork2 as an action processing framework ontop of Spring may not be needed after all. I know it’s possible to “trick” WebWork2 into using Spring, but I don’t find that to be the correct solution to the problem. I’m sure that Spring Web Flow will be much less hassle and be better supported.</p>
<p>Competition in this web action processing framework area is good, and I hope that the emergance of the Spring Web Flow project will push other projects to improve and inovate. WebWork2 definitely has a huge head start over this new project, but I think that both projects could improve in a lot of ways.</p>
Localization Terminology2005-03-08T00:00:00+00:00https://codecrate.com/2005/03/localization-terminology<p>I ran into some confusing terminology while examining localization code; i18n and l10n. After some Googling, I found that they refer to INTERNATIONALIZATION and LOCALIZATION respectively. These acronyms are actually just abbreviations of the words using this form:</p>
<p>[FIRST_CHARACTER][NUMBER_OF_CHARACTERS_BETWEEN][LAST_CHARACTER]</p>
<p>I even ran into someone referring to INSTALLATION as i10n. I think this is a very bad pattern to follow in general, since most acronyms mask the relevent “Domain Language”.</p>
Hibernate by Hand2005-03-07T00:00:00+00:00https://codecrate.com/2005/03/hibernate-by-hand<p>Well, it’s official. I’ve removed all XDoclet2 dependencies from my project (Good riddence!), and I am now writing hibernate configuration files by hand. I might look into the <a href="http://www.binamics.com/hibernatesync/">Hibernate Synchronizer</a> eclipse plugin to see if it’s worth while, but I doubt it. It looks like your code has to extend a common base class, and I’m not going to compromise my code’s design to support some tool.</p>
XDoclet2 Downfall2005-03-05T00:00:00+00:00https://codecrate.com/2005/03/xdoclet2-downfall<p>I’ve nearly reached the breaking point trying to adopt XDoclet2 and I find it ridiculous that <a href="http://marc.theaimsgroup.com/?l=turbine-maven-user&m=110977713323716&w=2">it’s developers keep pushing people to migrate to XDoclet2 when it is so unusable</a>. It’s now been over 3 weeks and I have yet to get my extremely simple hibernate project up and going. So far, I have filed four bugs with the XDoclet2 Plugin project and each one has been closed with the assurance “It should work now” (see issues <a href="http://jira.codehaus.org/browse/XDP-42">XDT-42</a>, <a href="http://jira.codehaus.org/browse/XDP-43">XDT-43</a>, <a href="http://jira.codehaus.org/browse/XDP-44">XDT-44</a> and <a href="http://jira.codehaus.org/browse/XDP-45">XDT-45</a> for the issues I’ve files so far). These problems are such show-stoppers that a single integration or acceptance test would have blown up in the developer’s faces. I’m sick and tired of being the guinea pig for their pathetic plugins. You would think the developers would take the extra twenty seconds and actually test their plugins, especially since one on the touted features of XDoclet2 is it’s “testability”.</p>
<p>To think, I was a BIG supporter of the original XDoclet and did the majority of my J2EE development with it’s help. Now, I see that XDoclet (and similar code-generation tools) should be avoided at all costs. It’s a tool that hides the greater underlying problem; if you NEED thousands of lines of XML generated for you by a tool, it’s time to look for some other tools that don’t require thousands of lines of XML.</p>
<p>I have now seriously considered just handcoding my hibernate files because although it is painfully slow, it is 100% reliable. It’s a sad day indeed…</p>
Early Optimization2005-03-02T00:00:00+00:00https://codecrate.com/2005/03/early-optimization<p>“Early optimization is the root of much evil.”</p>
<p>~Donald Knuth</p>
<p>I’ve seen a ton of variations on this quote, so I’m not sure which is the “correct” one, but I believe this quote is an absolutely essential guideline to follow for agile software development.</p>
Spring Bloat2005-02-19T00:00:00+00:00https://codecrate.com/2005/02/spring-bloat<p>I was severely disappointed yesterday to see how bloated Spring’s library is with unnecessary libraries. Sure Hibernate support is great, but why have it included as part of the core library? I use JDO currently, and so it doesn’t make sense to have the extra jars bloating the size of my webapp. It certainly isn’t difficult to componitize your application and distribute modules as seperate jars. Just take a look at <a href="http://swingwork.codecrate.com">swingwork</a> and <a href="http://shard.codecrate.com">shard</a> as examples for how to componitize your API so that user’s don’t need to download 50 packages just to get your stuff up and going. I find it disturbing that it’s acceptable for a lightweight framework to come as a <a href="http://prdownloads.sourceforge.net/springframework/spring-framework-1.1.4-with-dependencies.zip?download">27MB download</a>!</p>
<p>Here’s a short list of all the junk thrown into the “default” spring package:</p>
<ul>
<li>
<p>hibernate</p>
</li>
<li>
<p>jdo</p>
</li>
<li>
<p>a ton of jakarta-commons libraries</p>
</li>
<li>
<p>jsf</p>
</li>
<li>
<p>log4j</p>
</li>
<li>
<p>quartz</p>
</li>
<li>
<p>velocity</p>
</li>
<li>
<p>jakarta-poi</p>
</li>
<li>
<p>a whole lot more…</p>
</li>
</ul>
Maven and XDoclet22005-02-16T00:00:00+00:00https://codecrate.com/2005/02/maven-and-xdoclet2<p>It’s been a while since I’ve used XDoclet, but now that I’m starting to use Hibernate, I thought I would see what XDoclet could do for me. First let it be known that I use Maven for my projects, and I have been <a href="http://wiki.codehaus.org/maven/CreatingEjbApplications">extremely unimpressed with the XDoclet’s integration with Maven thus far</a>. That being said, I’m all for second chances, and so I decided to really give this some investigation.</p>
<p>Getting XDoclet2 up and running with Maven was surprisingly easy, and I’m very impressed that it is no longer necessary to “jump through hoops” to get up and going. I started by following the <a href="http://xdoclet.codehaus.org/maven-plugin/example-hibernate.html">examples posted on the XDoclet2 website</a>, but quickly found out that it’s out of date. I needed to use the following dependencies instead of the one’s listed in the example. Once the dependencies were in place, I was up and going by adding some pretty straightforward properties. I now can use XDoclet2 for my maven projects by manually invoking maven xdoclet2, or by setting up a pregoal for java:compile.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>xdoclet-plugins
maven-xdoclet2-plugin
1.0-SNAPSHOT
plugin
http://xdoclet.codehaus.org
xdoclet-plugins
xdoclet-plugin-hibernate
SNAPSHOT
http://xdoclet-plugins.sf.
true
</code></pre></div></div>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#snippet from project.properties
#hibernate properties
hibernate.dialect=net.sf.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:hsqldb:.
hibernate.connection.username=sa
hibernate.connection.password=
maven.hibernate.version=2.1
maven.hibernate.showsql=${hibernate.show_sql}
maven.hibernate.dialect=${hibernate.dialect}
maven.hibernate.hbm2ddlauto=${hibernate.hbm2ddl.auto}
maven.hibernate.driver=${hibernate.connection.driver_class}
maven.hibernate.jdbcUrl=${hibernate.connection.url}
maven.hibernate.userName=${hibernate.connection.username}
maven.hibernate.password=${hibernate.connection.password}
#xdoclet properties
maven.xdoclet.0=hibernate
maven.xdoclet.0.fileset.0.dir=${basedir}/src/java
maven.xdoclet.0.fileset.0.include=**/*.java
maven.xdoclet.0.hibernate=org.xdoclet.plugin.hibernate.HibernateMappingPlugin
maven.xdoclet.0.hibernate.destdir=${basedir}/target/generated-source/java
maven.xdoclet.1=hibernate2
maven.xdoclet.1.fileset.0.dir=${basedir}/src/java
maven.xdoclet.1.fileset.0.include=**/*.java
maven.xdoclet.1.hibernate2=org.xdoclet.plugin.hibernate.HibernateConfigPlugin
maven.xdoclet.1.hibernate2.destdir=${basedir}/target/generated-source/java
maven.xdoclet.1.hibernate2.showsql=${maven.hibernate.showsql}
maven.xdoclet.1.hibernate2.dialect=${maven.hibernate.dialect}
maven.xdoclet.1.hibernate2.jdbcdriver=${maven.hibernate.driver}
maven.xdoclet.1.hibernate2.jdbcurl=${maven.hibernate.jdbcUrl}
maven.xdoclet.1.hibernate2.jdbcusername=${maven.hibernate.userName}
maven.xdoclet.1.hibernate2.jdbcpassword=${maven.hibernate.password}
maven.xdoclet.1.hibernate2.hbm2ddlauto=${maven.hibernate.hbm2ddlauto}
</code></pre></div></div>
<p>I do have a couple notable complaints from my experience thus far. First, I think that it’s very confusing that XDoclet was completely rewritten using new technology, and it’s simply named XDoclet2. I think something like “NextDoclet” would do a much better job of getting people’s attention and avoiding confusion with the old platform. As a side note, I also question the rewrite of Maven that is simply named Maven2.</p>
<p>Also, one of the promises held by the developers for XDoclet2 is that it would be much easier to test and thus would have less bugs. Well, this does not seem to be the case yet. While attempting to use the new hibernate plugin, which should have been a straight forward port from the old version since no new functionality has been added, I discovered that it has some crippling bugs that render it basically unusable. I’ve filed these issues with the developers, so we’ll see when they get this plugin actually working.</p>
<ul>
<li>
<p><a href="http://jira.codehaus.org/browse/XDP-43">empty xml properties inserted into configuration file</a></p>
</li>
<li>
<p><a href="http://jira.codehaus.org/browse/XDP-42">hibernate config plugin uses wrong dtd</a></p>
</li>
</ul>
JSP Late Binding2005-02-10T00:00:00+00:00https://codecrate.com/2005/02/jsp-late-binding<p>My old friend JSP has caused me yet more pain. In my current project, I’ve been stung by the pervasive Late Binding issue with JSP. If I try and reference a method or class that doesn’t exist on the page, I get a horrendous error message at runtime. This is the ultimate of inconveniences since it has escaped through my development/testing process. The bottom line is no matter how well I’ve architected my code to only place particular objects into JSP’s context (using WebWork or any other web framework), every time I refactor or rename a method, I have to search through all of my JSP’s for references to that method. This is a BIG problem when you’ve got a system with literally thousands of JSP’s. It just doesn’t scale, and slows down development to the point that people are afraid to refactor because code might break something. Definately a problem for “agile” development.</p>
<p>I think it’s clear that JSP is not intended for large scale projects, and that it should be used only in “toy” or R&D applications. I’ve been happy with velocity, but it still has the same issues with late binding. Granted, it does a much nicer job than JSP by only printing out the unresolved expression instead of dumping a stack trace. So, maybe it’s time I checked out Tapestry. After some initial searching and reading through the documentation, it definitely fits the bill, but the project does not seem nearly as active as other web frameworks.</p>
Document Code With Units Of Work2005-02-10T00:00:00+00:00https://codecrate.com/2005/02/document-code-with-units-of-work<p>Good rule of thumb is: if you feel the need to comment a method body for how a block of code works, work should be extracted in a more understandable way. Either extract the code into a seperate class, or extract it to a shorter, simpler and more expressive method.</p>
<p>Here’s a real simple example, but I think it shows the usefulness of this technique.</p>
<h3 id="example-one">Example One</h3>
<p>Old code that does all the work and uses comments inside the method body.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kt">void</span> <span class="nf">doStuff</span><span class="o">(</span><span class="nc">Object</span> <span class="n">myClass</span><span class="o">)</span> <span class="o">{</span>
<span class="c1">//check that class is in ready state</span>
<span class="k">if</span> <span class="o">(</span><span class="n">myClass</span><span class="o">.</span><span class="na">getState</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="s">"Ready For Work"</span><span class="o">))</span> <span class="o">{</span>
<span class="c1">//do Stuff</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<h3 id="example-two">Example Two</h3>
<p>New code that extracts work into easily understandable method.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kt">void</span> <span class="nf">doStuff</span><span class="o">(</span><span class="nc">Object</span> <span class="n">myClass</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">isReadyForWork</span><span class="o">(</span><span class="n">myClass</span><span class="o">))</span> <span class="o">{</span>
<span class="c1">//do stuff</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kd">private</span> <span class="kt">boolean</span> <span class="nf">isReadyForWork</span><span class="o">(</span><span class="nc">Object</span> <span class="n">myClass</span><span class="o">)</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">myClass</span><span class="o">.</span><span class="na">getState</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="s">"Ready For Work"</span><span class="o">))</span> <span class="o">{</span>
<span class="k">return</span> <span class="kc">true</span><span class="o">;</span>
<span class="o">}</span>
<span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>
JSP is a Joke2005-02-09T00:00:00+00:00https://codecrate.com/2005/02/jsp-is-joke<p>Just when I thought JSP couldn’t get any worse, Sun announces that they are submitting <a href="http://jcp.org/en/jsr/detail?id=267">a JSR to manipulate webservices directly from JSP’s.</a> My <a href="/2004/10/two-faces-of-jsp.html">previous blog</a> listed a few things I find completely unacceptable with the current JSP technology. It’s almost as if JSP is the “kitchen sink” technology. Need to access databases? Yeah, we’ve got a tag library for that. Need to call webservices? Yep, you can do that too. What’s next? Need to pull data from legacy systems, transform to xml, and write to the user’s file system with javascript validation?</p>
<p>Sun claims that this spec is useful:</p>
<p>“A JSP tag library for Web Services is a happy union of the two technologies that will help JSP page authors integrate Web Services into their web applications with minimal effort and quick turnaround times.”</p>
<p>“A Happy Union”? I would call it, “A Shotgun Wedding”. Why can’t someone see that this is a terrible, terrible idea?</p>
java.net CVS problems2005-02-09T00:00:00+00:00https://codecrate.com/2005/02/javanet-cvs-problems<p>Have any other java.net project owners noticed that the version of CVS used to host projects has some issues? I ran headlong into an issue that has prevented me from integrating CVS commit messages into my <a href="http://jira.codecrate.com">JIRA instance</a>. The underlying problem is that you can not run an r* commands against the java.net CVS servers (ex: rlog, rdiff, etc).</p>
<p>I first went to Atlassian and opened an <a href="http://jira.atlassian.com/browse/JRA-5759">issue</a>, thinking this was a problem with JIRA. The extremely prompt and helpful Atlassian people pointed me to <a href="http://lists.gnu.org/archive/html/bug-cvs/2003-09/msg00168.html">some information</a> describing this as a bug with the CVS server. It just so happens that java.net is using this outdated version of the CVS server. The bug is scheduled to be fixed in the <a href="https://ccvs.cvshome.org/issues/show_bug.cgi?id=142">next version of CVS</a>, but my question is, when will java.net update their servers?</p>
<p>I did find that there is a bit of a <a href="https://java-net.dev.java.net/issues/show_bug.cgi?id=31">workaround</a> for this problem. Instead of using the symbolic links to the CVS repository, you can use the literal path. This is a bit more fragile, but should work for now. Instead of using :pserver:guest@cvs.dev.java.net:/cvs, use :pserver:guest@cvs.dev.java.net:/shared/data/ccvs/repository.</p>
Obsession with Hosting Javadocs2005-02-03T00:00:00+00:00https://codecrate.com/2005/02/obsession-with-hosting-javadocs<p>I don’t exactly understand what the recent obsession is with hosting javadocs (<a href="http://www.jdocs.org">jdocs</a>, <a href="http://www.koders.com">koders</a>, <a href="http://www.jsourcery.com/">jsourcery</a>). I do appreciate the fact that people are hosting them though, so that I don’t need to go and download them all the time. But, it’s irritating that every hosting site has different versions of the API. What we really need is for the artifact repository that Maven has invented to expand into hosting javadocs and source files. This would allow for archival of javadocs for each release, as well as the source files.</p>
<p>Example maven repository that holds artifacts/sources/javadocs:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/myrepo/myproject/
/jars/myjar-1.0.jar
/javadocs/1.0/index.html
/sources/1.0/Foo.java
</code></pre></div></div>
<p>I know there’s been talk about this functionality being done in Maven2, but I have yet to hear any concrete implementation details. As an added bonus, it would be great to have IDE integration to pull both javadocs and the reference sources when importing a new artifact.</p>
<p>With this recent jockying for who’s got the best source/javadoc service, I think this is definately something the Java community needs.</p>
Lego Applications2005-01-28T00:00:00+00:00https://codecrate.com/2005/01/lego-applications<p>There’s a lot of hype surrounding the term Service Oriented Architecture (SOA). This development pattern has been around a long time, but for some reason, it’s recently been brought into the lime light. While working on my last web application, I got to thinking that it would be very useful to consider all of the actions throughout the application as individual services. Common services would be things like: Login, ViewAccountInfo, DownloadStuff, etc. This mentality would lead to developing applications more like building with Legos. Each action can be linked from any number of other actions, and it’s result can be directed to any number of results.</p>
<p>This leaves me wondering why something like this doesn’t exist today? With Webwork being a prime example of this development style, why aren’t there sets of reusable web actions distributed around the net? I can see great value in a jakarta-commons type of library for reusable services or prebuilt actions. All that would be required of the developer would be to plug in the workflow to link the services/actions together.</p>
Font Chooser for Swing2005-01-19T00:00:00+00:00https://codecrate.com/2005/01/font-chooser-for-swing<p>Java.net just posted a link to an <a href="http://common.l2fprod.com/index.php">Apache licensed font chooser Swing component</a>. I wrote my own font chooser for my last application, but dang, this one looks nice.</p>
Webwork over Spring MVC2005-01-13T00:00:00+00:00https://codecrate.com/2005/01/webwork-over-spring-mvc<p>I’ve been exposed to <a href="http://springframework.org">spring</a> recently and have been impressed with it’s flexibility and power. Today, I took a look at spring MVC, and I must say that I’m not very impressed. I’ve worked with Webwork2 over the past year and find it to be a much better solution. Granted, this was just a first impression, but from what I’ve seen, the Spring MVC makes you jump through a lot more hoops, while Webwork “Just Works”.</p>
<p>My first gripe with Spring MVC is the proliferation of presentation “Bean” classes. With Webwork, I can reuse my business objects in my actions and have them populated directly from the input. Tack on Nanocontainer, and information can be populated from the Application, Session or Request scope.</p>
<p>Webwork automatically populates your view context by what you expose on your Action class, which is much more convenient that Spring’s convention of manually placing your informaiton into a hashmap. This makes Webwork extremely easy to get up and going.</p>
<p>I also really like how Webwork enforces the idea of one Action equals one Page. With Spring, a single controller can service multiple different operations, and although it’s “flexible”, it also leads to a proliferation and hard to follow workflow. With webwork, I know exactly that Welcome.action maps to WelcomeAction.java. This is simply not the case with spring. This is even more of a problem with their so called “Wizard Controller Framework”. One controller will service many parts of a wizard, yet it just makes so much more sense for them all to be separate actions. I have seen code for wizard controllers become mangled and messy trying to handle all the interrelated actions. They become bloated and extremely hard to maintain.</p>
<p>I was also quite disappointed to see that controllers hard code the result/view of their action. I think Webwork has a huge advantage where one action can be mapped to any number of results depending on the actions output (success, error, input, etc). Webworks architecture allows for building a web application in more of a component based approach, but I’ll blog more on this later…</p>
<p>I like spring and think that it shows tremendous potential, but the web MVC framework is far behind what I already have with Webwork. That being said, I think that Webwork (more specifically XWork), should swap out its internals and adopt a better IoC container like PicoContainer or Spring. I found some <a href="http://blog.sunmast.com/alex/archive/2004/12/13/1047.aspx">great info</a> on comparing these two frameworks, but I would be interested in hearing anyone else’s comments or insight.</p>
Scarab Squashed?2004-12-14T00:00:00+00:00https://codecrate.com/2004/12/scarab-squashed<p>At my last job, I was a strong supporter of using an issue tracking system to help coordinate bug fixes and features. The projects were internal only, and since I’m a big opensource nut, I pushed to use <a href="http://scarab.tigris.org">scarab</a> as our issue tracking server. The supported features were adequate, and the speed wasn’t horrible, so life was good.</p>
<p>Now that I’ve established several open source projects of my own, I decided to give <a href="http://www.atlassian.com">JIRA</a> a try. It didn’t take me long to see that JIRA is hands down the best software out there for issue tracking. I got <a href="http://jira.codecrate.com">my instance</a> up and running in a matter of minutes, and haven’t had to touch it since. Plain and simple, this software rocks!</p>
<p>Since development on scarab seems to have come to a screetching halt, I wonder how many people out there are moving to commercial issue tracking software, or if there are other good opensource solutions? And I don’t want to hear anyone mention Bugzilla!</p>
Developing a New Strategy2004-12-13T00:00:00+00:00https://codecrate.com/2004/12/developing-new-strategy<p>Infoworld has a great article that lays out <a href="http://www.infoworld.com/article/04/11/19/47FEtop20_1.html">The top 20 IT mistakes to avoid</a>. My absolute favorite in this article is number 16, Clinging to prior solutions. With it’s real world example that closely mirrors my own experience, it articulately describes the idiocy in blindly using a solution just because it’s been done before.</p>
<p>I have seen that this mentality is especially true when moving from one form of development to another. Manager X might say, “<a href="http://www.oracle.com">Company A</a> was our way of life in the <a href="http://www.sybase.com/products/developmentintegration/powerbuilder">client server world</a>, so we must use their unproven track record for N-Tier development. They may be slower to market, and be playing catch up to the other industry leaders, but we’ll simply stick with them, and not rock the boat.” Inevitably, this approach will fail. Why? Because you can not simply force solutions that worked before into a new environment without taking into consideration how the new environment should work. It could very well be that <a href="http://www.oracle.com">Company A</a> does not fully understand the environment you are migrating into, and thus you will be stuck with a <a href="/2004/07/oracle-foolset.html">mish-mash of technologies</a> and be worse off than sticking with your old solution.</p>
<p>Whether it is changing technologies or moving into a new field of interest, it is foolish to try and simply apply old tricks to a new strategy.</p>
Hacking OpenSource2004-11-17T00:00:00+00:00https://codecrate.com/2004/11/hacking-opensource<p>I find it interesting when I hear that the only reason Linux is more secure than Windows is because it’s used by fewer people. The argument is that software that doesn’t hold vast marketshare has “Security from Obscurity”. Now, with the 1.0 release of Firefox, I hear people say that it will be exploited in the same way that people have hacked Internet Explorer as it keeps stealing marketshare away from IE. Do people really believe this?</p>
<p>Mozilla introduced their <a href="http://www.mozilla.org/security/bug-bounty.html">Bug Bounty Program</a> a while back with the specific goal to “…encourage security research in Mozilla software and to reward those who help us create the safest Internet clients in existence.” With this incentive to try and find security holes in Firefox, I beg to question why we still have so many reported security holes in IE, and virtually none reported for Firefox? Could it be because Microsoft just makes it so damn easy? Could it be that Firefox is generally more stable and bulletproof? Or, could it be that developers (like myself) feel that Microsoft has somehow “wronged them” with their quirky, insolent browser and feel that some form of payback is necessary? =)</p>
<p>I vote for the option number three…</p>
Intrusive Frameworks2004-11-11T00:00:00+00:00https://codecrate.com/2004/11/intrusive-frameworks<p>The sad state of most development frameworks out there today (struts, webwork), is that they force you to code to a particular design. I’m not talking about extending their classes or implementing particular interfaces. I’m talking about how the frameworks’ objects are constructed and populated.</p>
<p>Most developers sell themselves (and their projects) short by buying into application frameworks. I spent a great deal of time integrating web frameworks like webwork and struts into my applications with the promise it would make my life easier. A younger and more naive self didn’t see a problem with having all of my actions with no-arg constructors and allowing the framwork to call setter methods to get data into my action. Now, after taking a break from these frameworks and using dependency injection (IoC type 3) for my applications, I wanted to continue using this pattern on my web framework code.</p>
<p>The “Good Citizen Pattern” has become my new pattern of choice. For those of you that don’t know about this amazing pattern, it basically states that once an object is constructed it should be in a “good state”. No additional calls are required for it to be usable. How can these frameworks help my application if they force me to use no-arg constructors?</p>
<p>Enter picocontainer and nanocontainer to save the day. Nanocontainer has an extension to support popular webframeworks like webwork, and it allows for my actions to be constructed with the objects needed to execute the actions. I am very impressed with the work thus far, and I’m sure it will continue to grow in popularity.</p>
<p>Aslak (one of the main developers of picocontainer) had a great <a href="http://theserverside.com/talks/videos/AslakHellesoy/interview.tss?bandwidth=dsl">interview</a> over at theserverside where he stated that if frameworks become intrusive to our development (ie: like forcing no-arg constructors) the framework has failed it’s goal. I agree wholeheartedly.</p>
The Two Faces of JSP2004-10-22T00:00:00+00:00https://codecrate.com/2004/10/two-faces-of-jsp<p>The same reason I have come to hate JSP is the same reason many other developers love it; it’s super flexible and has a wide range of functionality. Well, I think that JSP’s are TOO flexible for their own good. I’ll go out on a limb and state that, “Using JSP’s inherently leads to poor application design”. This is a bold statement, and I realize that it is not true 100% of the time. Here’s my rationale:</p>
<ul>
<li>There are no failsafes to STOP you from going overboard and doing all of the work in each JSP. Heck, there’s no way to even run something like checkstyle on a JSP. Has anyone out there looked at the java source of a translated JSP file?</li>
<li>Translated files lead to tough troubleshooting. Seeing an error message saying there’s a problem with line 2000 of my jsp (when the jsp is only 200 lines long), does not help much.</li>
<li>No unified direction to do operations or perform work. If the development and site design teams are seperated, there is no way to know when a JSP has done work inefficeintly or incorrectly like using scriptlet instead of custom tag.</li>
<li>In a vast majority of JSP projects, little hacks here and there sneak into JSP’s (custom scriptlets or using more and more custom tags, etc) until a bloated mess is all you are left with.</li>
<li>Confusion of responsibilities. Their is a contradiction of sorts depending on who is creating the application. If a software developer is creating a web application, they want absolute control over the application from any layer (including the JSP view). “Give me SQL tags so I can query/update databases. I need to ftp files using custom tags.” If a html developer is creating a web application, they don’t want 10,000 different ways of getting the same result. They want the “work” done elsewhere, and they handle the output and formatting.</li>
<li>Error pages not displayed correctly. If any “work” is done inside a jsp (like using a custom tag), the content has already started to stream back to the user, and any error will not correctly prompt a “Server Error” page.</li>
</ul>
<p>MVC Pull frameworks like WebWork2 remove these problems all together. The work is done upfront before streaming back to the client. Combined with a better templating system like Velocity, where you have the data fed into the template, and you’ve got a smoking setup that doesn’t have all the ugly problems of JSP.</p>
<p>Granted, you can go overboard and place excessive amounts of information on the context for the templates to use, but it is impossible for the template to overstep it’s bounds and do work on it’s own. People preach MVC using JSP, but I don’t believe it to be the right choice to use JSP as the view when it has all the power to be all three.</p>
Conventional Class Names2004-10-22T00:00:00+00:00https://codecrate.com/2004/10/conventional-class-names<p>What are the most common conventions for naming Java classes? I’ve been subject to several different conventions would like to hear if there are any good guidelines out there. Here are some of the conventions I’ve come across and I would like to know if there is a good general pattern to follow.</p>
<p>Example Interface Naming Conventions</p>
<ul>
<li>Prefix classname with “I”. ex: IClassName</li>
</ul>
<p>Example Implementation Naming Conventions</p>
<ul>
<li>
<p>Add Impl suffix. ex: ClassNameImpl</p>
</li>
<li>
<p>Put implementation in seperate package. ex: org.myapp.impl</p>
</li>
<li>
<p>DefaultMyClass</p>
</li>
</ul>
<p>Example Abstract Class Naming Conventions</p>
<ul>
<li>
<p>MyClassUtil or MyClassUtils</p>
</li>
<li>
<p>AbstractMyClass</p>
</li>
<li>
<p>MyClassSupport</p>
</li>
</ul>
<p>I’ve read some interesting articles on this topic and think that the best strategy is that a classname should not to not allow a caller to know if a class is an interface or concrete class. This allows for possible later refactoring without breaking the clients.</p>
<p>An example of this would be to start with concrete simple class called MyClass. Once multiple implementations are available, MyClass becomes an interface and the old implementation becomes DefaultMyClass. The caller “may” need to reference DefaultMyClass, but otherwise their code will remain the same.</p>
fedora core 2 network issues2004-10-07T00:00:00+00:00https://codecrate.com/2004/10/fedora-core-2-network-issues<p>I installed fedora core 2 about a month ago, and I am suprised to find how many network issues I am having. Every 2-3 days I need to restart the network service (/etc/init.d/network restart). I’ve run SuSe before without problems, so I find it hard to believe this is a hardware issue. Is FC2 just a little flaky?</p>
<p>I’m relying on my network being up to host webapplications, so I may have to move to another distribution soon unless I can figure out what’s going on. So far, no strange error messages have shown up to tell me what may be going wrong.</p>
Validate object contents against database structure2004-10-05T00:00:00+00:00https://codecrate.com/2004/10/validate-object-contents-against<p>If using object to relational database mapping tools like hibernate or jdo, how can you validate that the object has valid contents before persisting? Database errors are not consistent across platforms and for the most part users’ don’t understand what went wrong. I would like to programatically check that a field’s null/not-null status and verify that the object size does not break the database column. XWork has an object validation framework, and I’m wondering if it’s possible to hook onto that framework to make a connection to the database and validate the object contents before it’s persisted.</p>
<p>Necessary Steps:</p>
<ol>
<li>
<p>get object to validate.</p>
</li>
<li>
<p>get database connection settings.</p>
</li>
<li>
<p>extract metadata about column(s) to validate (table, column names).</p>
</li>
<li>
<p>get column size and isNullable flag.</p>
</li>
<li>
<p>compare to object field and throw “user friendly” exception if invalid.</p>
</li>
</ol>
<p>Hibernate appears to make it easy to extract both connection settings and object metadata, so I’m going to try and tackle this first. Hopefullly it won’t take long, and I’ll be able to post some results soon. If anyone out there has gone through something similar, I’d love to hear about it.</p>
<p>Resources:</p>
<ul>
<li>
<p>http://www.jguru.com/faq/view.jsp?EID=1184</p>
</li>
<li>
<p>http://wiki.opensymphony.com/display/XW/Building+a+Validator</p>
</li>
<li>
<p>http://www.hibernate.org/hib_docs/api/index.html</p>
</li>
<li>
<p>http://www.mail-archive.com/hibernate-devel@lists.sourceforge.net/msg03272.html</p>
</li>
</ul>
BeanPropertyTableModel2004-10-05T00:00:00+00:00https://codecrate.com/2004/10/beanpropertytablemodel<p>I finally have seen the light for how powerful reflection can be. I used to painstakingly create a seperate table model for each of my java objects that I wanted to display in a table. Each class had a custom case/switch statement to return the correct value for the requested column.</p>
<p>In short, it was inelegant but it worked. Now, I’ve put together a table model for <a href="https://riva.dev.java.net">riva</a> that uses <a href="http://jakarta.apache.org/commons">commons-beanutils</a> to introspect a beans properties to return the correct value. It handles setting values as well, and will only set a column as editable if the object has a setter method for that property.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//here was my old way of doing table models.</span>
<span class="c1">//each class had a custom table model.</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyObjectTableModel</span> <span class="o">{</span>
<span class="kd">private</span> <span class="nc">List</span> <span class="n">objects</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">();</span>
<span class="c1">//ommitted unimportant methods</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">addObject</span><span class="o">(</span><span class="nc">Object</span> <span class="n">myObject</span><span class="o">)</span> <span class="o">{</span>
<span class="n">objects</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">myObject</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">Object</span> <span class="nf">getObject</span><span class="o">(</span><span class="kt">int</span> <span class="n">row</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="n">objects</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">row</span><span class="o">);</span>
<span class="o">}</span>
<span class="kd">public</span> <span class="nc">Object</span> <span class="nf">getValueAt</span><span class="o">(</span><span class="kt">int</span> <span class="n">row</span><span class="o">,</span> <span class="kt">int</span> <span class="n">column</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">MyObject</span> <span class="n">object</span> <span class="o">=</span> <span class="o">(</span><span class="nc">MyObject</span><span class="o">)</span> <span class="n">getObject</span><span class="o">(</span><span class="n">row</span><span class="o">);</span>
<span class="nc">Object</span> <span class="n">value</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
<span class="k">switch</span><span class="o">(</span><span class="n">column</span><span class="o">)</span> <span class="o">{</span>
<span class="k">case</span> <span class="mi">0</span><span class="o">:</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">object</span><span class="o">.</span><span class="na">getMyField1</span><span class="o">();</span>
<span class="k">break</span><span class="o">;</span>
<span class="k">case</span> <span class="mi">1</span><span class="o">:</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">object</span><span class="o">.</span><span class="na">getMyField2</span><span class="o">();</span>
<span class="k">break</span><span class="o">;</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">value</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>You can see the new table by checking the <a href="https://riva.dev.java.net/source/browse/riva/riva-core/src/java/com/codecrate/riva/model/BeanPropertyTableModel.java">riva cvs file</a>.</p>
d20 gaming engine2004-09-20T00:00:00+00:00https://codecrate.com/2004/09/d20-gaming-engine<p>I have just launched a new project on java.net called <a href="https://shard.dev.java.net">shard</a>. It’s goal is to be an opensource d20 gaming engine that is small, lightweight and embeddable. There are several d20 applications and tools, but none that can be embedded into other applications or used as a core for pc gaming. In particular, my interest in starting an embeddable d20 engine began when I tried adapting another application to be used as a web based utility application. I won’t mention the project that was being used, but the issues were great enough that I decided that the d20 community needed a better option.</p>
<p>One of the first uses I hope to see is to convince the folks at gmgen to use the dice implementation I’ve put together. It’s solid and can handle a wide range of dice uses (multiple rolls, drop high/low rolls, etc). It would be a great boon to our gaming community (both pen/paper and electronic) to have a solid d20 engine. Can you imagine the possibilities of Neverwinter Night quality games if the d20 ruleset was already implemented for their use?</p>
<p>I have posted a <a href="http://www.codecrate.com/snipsnap/space/shard">wiki</a> for anyone interested to drop ideas/comments.</p>
Bad Beta Software2004-09-20T00:00:00+00:00https://codecrate.com/2004/09/bad-beta-software<p>I think the term BETA has got a bad rap. Microsoft has tainted the term so that when people hear the word “BETA” they think it is software that will crash their computer with a nasty “blue screen of death” and corrupt their filesystem, leaving them penniless and without friends. Okay, maybe that’s a bit extreme, but the general consensus is that BETA software has no place in a production environment. No matter the tool, I have felt considerable pressure against using beta software in my environments.</p>
<p>I use a number of tools that were labeled BETA and worked great (eclipse, maven, jdom). Both maven and jdom were labeled as BETA for so long, not because they were’nt ready for use, but because they were subject to change. I say that if software is labeled as BETA, but does what you need, you shouldn’t be afraid to use it. Sure, it may have advertised bugs, but if they don’t impact your work, it doesn’t hurt to start integrating the software before it hits the magical 1.0.</p>
No JSR for SWT2004-07-27T00:00:00+00:00https://codecrate.com/2004/07/no-jsr-for-swt<p>I don’t believe that SWT will ever make it as a JSR. It is a very good library and has done the Eclipse project well, but it should not become a Java standard. SWT libraries have only been ported to a few operating systems, and they have only been ported “well” to Windows. The reason SWT came around was because Eclipse ran into issues with Swing and decided to roll their own windowing toolkit to do what they needed to do. More power to them for doing that, but acceptance as a JSR means that SWT must be available for every platform that runs Java, otherwise what good is it to the Java “community”?</p>
<p>SWT is the first Java API that I know of that totally breaks the concept of “Write Once Run Anywhere”. If a JDK is available for an operating system, any Java application should be able to run on it. This is simply not the case with SWT, since it relies on the API to be ported to each operating system. SWT’s notion of <a href="http://www.developer.com/java/other/article.php/10936_2179061_2">resource de-allocation</a> also seems like a step backward for a Java API.</p>
<p>The JDK already has two windowing kits (AWT and Swing) that are tested on every available platform that the JDK is available. Introducing another toolkit as a Java standard would require that for every platform the JDK is available, the new toolkit must be tested and ported as well. It doesn’t seem to make much sense when there are already two API’s available.</p>
<p>Some people want SWT because it “looks” better. Well, I suggest they take a look at the <a href="http://www.jgoodies.com">JGoodies Project</a> to see their mock up of Eclipse using Swing. I was very impressed to see that it could be done, but I haven’t looked at the code to see how difficult it was to do it.</p>
<p>If Swing’s cross platform performance was the reason they created SWT, why not allow IBM to roll their own Swing implementation that ignores the cross platform look and feel, and uses the native calls just like SWT? Sure, applications wouldn’t have the same look and feel on all platforms, but you’d get the best of both worlds.</p>
Oracle Toy Store2004-07-23T00:00:00+00:00https://codecrate.com/2004/07/oracle-toy-store<p>I found it somewhat ironic that the same day I posted my blog somewhat blasting Oracle’s J2EE offerings, TheServerSide posted an <a href="http://theserverside.com/news/thread.tss?thread_id=27179">announcement</a> that Oracle has released a new demo application called “Toy Store”. There were quite a few very critical and insightful comments made by developers, and it seems that I am not alone in my frustration with Oracle’s Toolset!</p>
<p>My own critique of the “Toy Store” would follow a few of the other comments posted:</p>
<ol>
<li>
<p>Code Generation is excessively abused! See my previous blog
<a href="/2004/01/code-templates-vs-code-generation.html">why code templating should be used instead of code generation</a>.</p>
</li>
<li>
<p>XML is not code. The argument that XML is used to CONFIGURE the code is pretty ridiculous if it takes you just as much XML as Java to configure the Java. This tells me that there is a severe design flaw in the application. How is it possible to even refactor the application, when you are so tightly bound to these configuration files? Why not look into something much more elegant like AOP?</p>
</li>
<li>
<p>Oracle’s documentation and communication is absolutely horrible. Seems like the comment that <a href="http://weblogs.java.net/pub/wlg/1647">open sourcing Java would lead to bad documentation</a>is absolutely moot when you have terrible documentation comming from a commercial company. Has anyone out there tried to use their <a href="http://otn.oracle.com">OTN</a>!?!</p>
</li>
<li>
<p>It appears that there is <a href="http://radio.weblogs.com/0118231/">one sole person</a>championing knowledge of how the Oracle Tool Suite is intended to work. Maybe this is because Oracle’s own documentation is so poor that no one else has figured it out yet (including their own consultants).</p>
</li>
</ol>
JDK Source Code in Eclipse2004-07-19T00:00:00+00:00https://codecrate.com/2004/07/jdk-source-code-in-eclipse<p>I have been interested in the whole “Open Sourcing Java” argument, and one comment I hear frequently is that “If Java was Open Source, I could view where code bugs were and fix/submit them back”. The response is usually, “Sun does provide the source code along with the SDK for anyone to view”.</p>
<p>Since Sun does provide the source code allong with the SDK, I wanted to try to pull that source code into Eclipse to allow me to debug, not only my application, but also the JDK calls to see how it interacts with other resources (like the filesystem). I also wanted to get the Javadoc for the JDK calls. It was relatively simple to integrate Sun’s source code into Eclipse. Here were the steps that I went through:</p>
<ol>
<li>
<p>Go to Window > Preferences > Java > Installed JRE’s.</p>
</li>
<li>
<p>Add a new JRE and point the file system location to the value of your JAVA_HOME.</p>
</li>
<li>
<p>Select “rt.jar” and press the “Attach Source” button.</p>
</li>
<li>
<p>The location should be JAVA_HOME/src.zip</p>
</li>
</ol>
<p>Now you’ll get full Javadoc and be able to browse into Sun’s implementation to see where you’re getting that Null Pointer Exception! =)</p>
<p>NOTE: There appears to be some kind of problem with running Eclipse with the SDK JVM though. Eclipse seems to think that the class files are out of date, so it frequently cleans out my working directory and rebuilds my entire project. Changing back to use the normal JVM resolves this problem. I would be very interested to hear if anyone else has had this problem.</p>
The Oracle Foolset2004-07-12T00:00:00+00:00https://codecrate.com/2004/07/oracle-foolset<p>I’ve got issues with Oracle’s J2EE Toolset (aka: Foolset). I’ve spent 3 years building infrastructure and applications using the best open source tools and design practices available. The result was a very flexible and scalable system that used EJB session facades to access database resources (cached with EJB entity beans for heavy load areas). Recently, management decided to go with Oracle’s attempt at a J2EE solution. Throw out those standards like EJB, Swing and haul in a load of proprietary tools like BC4J, Oracle Forms!</p>
<p>Suposedly, developer productivity was a major reason for choosing the Oracle toolset. Oracle claims that using their toolset will allow for developing J2EE applications 30% faster. 30% FASTER THAN WHAT?!?! In the brief time that was spent reviewing the Oracle suite, I was able to use my existing toolset (Eclipse, XDoclet, Maven) to crank out proof of concept applications, before the other developers could even get off the ground with JDeveloper. Sure, it might be faster to develop with their weak attempt at an IDE compared to hand coding all the EJB interfaces and deployment descriptors, but who in their right mind still hand codes their EJB’s? Oracle’s claims of being more productive are flat out unjustified.</p>
<p>Next up on my list of gripes was the complete lack of J2EE knowledge held by ANY Oracle person we dealt with. Now, I’m not just talking about sales reps. We went through demonstrations with developers and even brought in an Oracle consultant to try and get their infrastructure up and running. Not only were they incompetent and unable to get working prototypes up and running, they had the audacity to blame the problems on our application design. It appears that in “Oracle’s World”, Entity beans are the major bottleneck in a J2EE application and should be avoided at all costs. They actually recommended that we removed all of our Entity Beans and used direct connections to the database instead. Excuse me?!? Since when has ANY network call been faster than an in memory cached lookup? I went through some extensive performance and load testing over the past year, and that’s WHY we were using Entity beans. I completely lost any respect these guys might have earned from me.</p>
<p>Should I blame Oracle for this frustration, or management for not researching the correct solution? The answer is both! Management was fooled by all of the “smoke and mirror” shows that Oracle put on, and didn’t bother to look underneath to hood to see that Oracle was peddling a sham of a replacement for our current architecture. I also place a good deal of blame on Oracle for the blatant tricks they were trying to pull, along with their gross incompetence in the J2EE market. Do I sound bitter at all to you?</p>
<p>NOTE: I have absolutely nothing against making an a decision like this if it is based on educated and rational information. I’ve seen other companies choose Oracle’s J2EE products for reasons like the speed of their appserver and their tight integration with their database and LDAP server, but this decision was anything but logical. I’ve been accused as only promoting open source software and shunning commercial offerings, but this is definitely not the case. I’m all for using the BEST software available whether it’s open source or not. It just so happens that more often than not, open source offers better stuff. =)</p>
Eclipse and Test Driven Development2004-07-10T00:00:00+00:00https://codecrate.com/2004/07/eclipse-and-test-driven-development<p>Eclipse has changed my life. Test Driven Development (TDD) has been a major boost to my productivity, and Eclipse has been huge factor in getting me to adopt new development style. Here’s my brief experience working with Eclipse and TDD.</p>
<p>Write Your Test Case First</p>
<p>This is one of the toughest parts when starting out with TDD. How can you write a test for classes and methods that don’t yet exist? It feels awkward at first, and the seeing “compiler errors” right off the bat, definitely pulls you out of your comfort zone.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyServiceTest</span> <span class="kd">extends</span> <span class="nc">TestCase</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">testDoSomething</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">MyService</span> <span class="n">service</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">MyService</span><span class="o">();</span>
<span class="n">assertNotNull</span><span class="o">(</span><span class="n">service</span><span class="o">.</span><span class="na">doSomething</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Get Your Test Case to Compile</p>
<p>Now that you have a skeleton testcase, Eclipse makes it a snap to get your testcase to compile. Just use Eclipse’s Quick Fix Feature (Ctrl + 1) on your constructor to create a new empty class. Then use the quick fix on the method call to create an empty method in your new class. BOOM! Just like that, you’re almost up and running.</p>
<p>Get Your Test Case to Pass</p>
<p>Since your testcase compiles now, try running it and see it’s failure. From here, implement the method as you need to in order to get the testcase to pass. Just remember to implement it in the simplest way possible. Refactoring comes later.</p>
<p>Test Driven Development has pushed me to keep my architecture simple, and Eclipse has been a huge help to get code and tests up and going as fast as possible. Many thanks to whoever introduced the “Quick Fix” into Eclipse and got it to work so well!</p>
Storing JARS in CVS2004-07-09T00:00:00+00:00https://codecrate.com/2004/07/storing-jars-in-cvs<p>I’m an avid user of Maven, and I’ve been baffled lately about the problems people have with pulling jars out of CVS and putting them into a maven repository. Maven gives us developers an elegant way of handling dependencies, and I keep hearing whining about “why change it if it isn’t broken”. The remote repository makes it extremely easy to share dependencies between projects without needing 4 copies on the filesystem. I have yet to see a single Ant build system do that (I should know since I spent over a year maintaining our old Ant build system). It’s really no different than the common practice of high traffic websites splitting thier images onto a different server to allow their codebase to change without re-releasing images.</p>
<p>Also, if you’re working with CVS, you are inherently working with branches. It makes absolutely no sense to have binary jars checked into each branch of a project. The size of a “lib” directory can grow so quickly on large projects, that the time it takes to checkout code borders on the side of craziness. This makes it nearly impossible to do agile development when, by the time you have the code checked out, a new branch has ben cut. =)</p>
<p>The last problem I see mainly has to do with Ant, but surfaces in this type of environment. “Library Rot” occurs when your “lib” directory contains a whole slew of jars, and you don’t know what’s used in your project. This is because a typical Ant build system builds the compile classpath using “lib/*.jar”, and so the lib directory continues to grow because no developer knows if something is needed or used. The only way to tell if something IS used, is to delete it and try to rebuild.</p>
<p>Yes, change is painful, but in this case, change is good.</p>
Maximized Abstraction By Dual Implementation2004-07-09T00:00:00+00:00https://codecrate.com/2004/07/maximized-abstraction-by-dual<p>How can developing the same thing twice lead to a better design? I thought it sounded a bit crazy myself until I started on a project that did just that.</p>
<p>Charged with creating a search architecture for our system, I set out to integrate with a commercial solution. Along the way, I wanted to make sure that we were flexible enough to handle any system that we could plug into. The problem was how can you abstract out possible hooks for systems that may perform totally different? It doesn’t make sense to spend time architecting a system with a series of hooks that “might” be needed X years from now with vendor Y. Well, my friends, that’s where open source comes into play. While integrating with the commercial vendor, I designed a dual implementation to work with an open source search engine called <a href="http://jakarta.apache.org/lucene">Lucene</a>.</p>
<p>Designing a second implementation forced my design to be more flexible and to abstract out the common pieces between the two. It also led to a greater understanding of how search systems in general work, which would lead to easier integration with yet a different vendor. Putting the extra work into designing a second implementation upfront, led to a much smoother integration with BOTH systems, without one or the other feeling like a hack.</p>
SwingWork: XWork integrated with Swing2004-06-29T00:00:00+00:00https://codecrate.com/2004/06/swingwork-xwork-integrated-with-swing<p><a href="http://xwork.dev.java.net">XWork</a> is the extremely powerful action processing framework that serves as the foundation for popular projects like <a href="http://webwork.dev.java.net">WebWork</a>. I have recently started a new project <a href="http://swingwork.dev.java.net">SwingWork</a> attempting to integrate XWork and Swing in a clean and consise way.</p>
<p>Currently supported features include:</p>
<ul>
<li>Action execution occurs in background thread.</li>
<li>Several basic Swing containers can be used as results (JPanel, JDialog, JFrame).</li>
<li>Progress bar during action execution that can be updated while action executes.</li>
<li>Built in splash screen for launching applications.</li>
<li>Demo application with full source code.</li>
</ul>
<p>Action frameworks are really taking off, and I would love to hear feadback (or possible participation) from anyone interested!</p>
Top 12 Things A Klingon Programmer Would Say2004-04-16T00:00:00+00:00https://codecrate.com/2004/04/top-12-things-klingon-programmer-would<p>Originally posted here: <a href="http://www.mail-archive.com/coffeehouse@glengamoi.com/msg10279.html">http://www.mail-archive.com/coffeehouse@glengamoi.com/msg10279.html</a></p>
<ul>
<li>
<ol>
<li>Specifications are for the weak and timid!</li>
</ol>
</li>
<li>
<ol>
<li>This machine is a piece of GAGH! I need dual Pentium processors if I am</li>
</ol>
</li>
</ul>
<p>to do battle with this code!</p>
<ul>
<li>
<ol>
<li>You cannot really appreciate Dilbert unless you’ve read it in the</li>
</ol>
</li>
</ul>
<p>original Klingon.</p>
<ul>
<li>
<ol>
<li>Indentation?! – I will show you how to indent when I indent your skull!</li>
</ol>
</li>
<li>
<ol>
<li>What is this talk of ‘release’? Klingons do not make software ‘releases’.</li>
</ol>
</li>
</ul>
<p>Our software ‘escapes’ leaving a bloody trail of designers and quality</p>
<p>assurance people in its wake.</p>
<ul>
<li>
<ol>
<li>Klingon function calls do not have ‘parameters’ – they have ‘arguments’</li>
</ol>
</li>
</ul>
<p>– and they ALWAYS WIN THEM.</p>
<ul>
<li>
<ol>
<li>Debugging? Klingons do not debug. Our software does not coddle the weak.</li>
</ol>
</li>
<li>
<ol>
<li>I have challenged the entire quality assurance team to a Bat-Leth</li>
</ol>
</li>
</ul>
<p>contest. They will not concern us again.</p>
<ul>
<li>
<ol>
<li>A TRUE Klingon Warrior does not comment his code!</li>
</ol>
</li>
<li>
<ol>
<li>By filing this SPR you have challenged the honor of my family. Prepare to</li>
</ol>
</li>
</ul>
<p>die!</p>
<ul>
<li>
<ol>
<li>You question the worthiness of my code? I should kill you where you</li>
</ol>
</li>
</ul>
<p>stand!</p>
<ul>
<li>
<ol>
<li>Our users will know fear and cower before our software. Ship it! Ship it,</li>
</ol>
</li>
</ul>
<p>and let them flee like the dogs they are!</p>
Cygwin Contradiction2004-04-12T00:00:00+00:00https://codecrate.com/2004/04/cygwin-contradiction<p>Java is used as a crossplatform programming language and Ant is the defacto standard build tool for Java projects. So, why are there so many Java projects out there that use Ant, yet still require a Unix like environment to build? Since I currently run Windows due to requirements within my business, I am baffled why I NEED Cygwin to emulate a Unix envirnoment to work with a Java project?</p>
<p>I agree with most developers that I talk with that using a tool like Cygwin does make development easier, but the concept that it should be required is absolutely ridiculous. The additional layer of complexity introduced by running yet another operating system, harms and does not help the adoption of many projects.</p>
Clearing JBoss' Authentication Cache2004-03-21T00:00:00+00:00https://codecrate.com/2004/03/clearing-jboss-authentication-cache<p>I’ve had several headaches lately when dealing with the JBoss authentication cache. If a user needs to change passwords, or account privilages, the cache lingers and lingers for as long as 30 min. Luckily I ran across this webblog that posts code to clear it programatically. I’ll be sure to do something similar in my next project.</p>
<p><a href="http://jroller.com/page/RickHigh/20040226#i_got_jboss_security_working1">http://jroller.com/page/RickHigh/20040226#i_got_jboss_security_working1</a></p>
Why Opensource Exists2004-03-20T00:00:00+00:00https://codecrate.com/2004/03/why-opensource-exists<p>I was recently in an interview where the topic of software engineers came up. We were discussing how software development is still in its infancy and that a day will come when our jobs will be replaced by automated systems that will automagically create the powerful, scalable, dynamic applications that we develop today. This process of “evolution” from artform to science can be compared to other industries that have gone through a similar process. Agriculture and psychology are two areas that at one time were a unique and unrefined field relying on superstition, luck, and common knowledge. Now, technology and science have generated information and standards that have replaced the majority of highly skilled positions and most work is now done according to formulas.</p>
<p>How does this relate to opensource software? As I said before, the computer industry is still in its infancy. Every single programmer is an artist of sorts, crafting and building software as their own art. Consider coding style, design and architecture, etc, as different facets of our art. And just as every artist views their own work as the best, every programer will say that their work is different and better than the next. =)</p>
<p>Until some time in the future when all of the complex parts of software development can be replicated without human intervention, our “art” will remain ours. One common trait held by ALL artists is that they want their art to be seen by as many people as possible. Since most programmers work within a corporate environment where their work can only be accessed and seen by others within the company, opensource projects provide the kind of exposure to the outside world that every artist craves. Just as Michelangelo painted the Sistine Chapel Ceiling for all the world to see, our art is meant to be viewed and used by an open and willing audience. Only then will the art be appreciated for all that it is.</p>
Eclipse Visual Editor2004-02-24T00:00:00+00:00https://codecrate.com/2004/02/eclipse-visual-editor<p>It takes a lot for an IDE to catch my interest. I have been working with the Eclipse Visual Editor, and have been completely blown away. Even in it’s prerelease state, it is one of the finest GUI designer’s I have used.</p>
<p>Installation is a snap, just download 3 eclipse plugins, extract them, and restart eclipse. The designer works great with any layout (Grid, GridBag, and even null layout for a true WYSIWYG designer).</p>
<p>What totally blew my mind though was the complete flexability of the tool. My hand coded GUI forms were very close to the generated code done by eclipse so, with VERY MINIMAL coding I was able to have my hand coded application pulled into the GUI editor. Plain and simple, this is the most amazing visual designer out there.</p>
Next Generation Reporting System2004-02-21T00:00:00+00:00https://codecrate.com/2004/02/next-generation-reporting-system<p>Although I am a big fan of the <a href="http://oreports.sf.net">openreports</a> project and their goals, I think their design is slightly flawed and could use some improvement. One flaw is the reliance on database storage. If a report is uploaded, it should be available without further configuration. Another problem is it’s webcentric nature. It is impossible to embed reports deployed on the application server into client side apps.</p>
<p>JMX may very well be the key to create the next generation reporting system and I’m tossing around ideas right now to start work on it soon. The great thing about JMX is that in a way it mirrors a database of registered components. In this reporting system, reports would be deployed as JMX components that expose 3 main functions; one for building the report, one for building a chart, and one for any required parameters to build the reports.</p>
<p>Once the reports are deployed as JMX objects, another JMX object would act as the report loader, so by passing in the JMX name of the report you want built, it would be looked up, built and cached for a period of time.</p>
<p>Still early, but it all seems to fit together. Any comments or suggestions?</p>
Live Income2004-02-13T00:00:00+00:00https://codecrate.com/2004/02/live-income<p>The recording industry has long held musicians in the palm of their hands, and have succeeded in making millions upon millions from other people’s talent. With the advent of the internet and more specifically Peer to Peer networks, the recording industry’s precious business model has been threatened. One way for bands to break out of the recording industry and still keep their heads above water is to offer something different. CD sales has never been where musicians were able to make money, since the recording’s were mainly owned by the recording companies. Instead, touring and ticket sales is where the real money is found.</p>
<p>So, what if there was a way to cut into the recording industries cash flow and reap the benifits from the live gigs? Bands such as Pearl Jam and Phish, have an increasingly popular answer. Selling live recordings from the shows not only incurages more fans to view the shows, it also gives incentive for personal keepsakes for people to remember the shows from.</p>
Slave to the Swing Visual Editor?2004-02-04T00:00:00+00:00https://codecrate.com/2004/02/slave-to-swing-visual-editor<p>Swing is a difficult platform with a high learning curve. It is also extremely flexible and powerful, but scares away it’s fare share of developers with it’s immense API. On top the core API, getting a handle on the Swing layout managers can be a nightmare for beginners. Thus, the market was opened for helpful editor’s to visually layout a Swing application for you (note the sarcasm). Many IDE’s (Netbeans, JDeveloper, JBuilder) played up the visual editor as the best thing since static methods. In a perfect world, these editors would allow you to layout your application and code buisness logic in perfect harmony allowing for such an increase in productivity that I could actually take a vacation here and there. Unfortunately, this is not so and never will be.</p>
<p>Why? Because visual editors have taken the approach of littering my well structured business logic with it’s garbage resembling Java code. Most visual designers due such a pathetic job of this code generation, that it makes me sick. Once the code has been generated, Woe to the developer that tries to modify it! I have yet to see a visual designer that can handle staying in synch between manual and visual editing. Each editor forces this mixing of concerns by putting code for the Model, View, and Controller into the same class. This generates extremely large Java files and forces vendor lockin. The visual editor SHOULD just be handling the view, and I should be free as a developer to change from designer to designer with ONLY having to rewrite the layout. Not so when you have a two thousand line Java file with intermingled generated code and buisness logic. Since these visual editors use code templates to generate your application, and each editor uses different templates, you again restrict yourself to one IDE and can not change to another.</p>
<p>The solution to this whole problem has been right in front of us the whole time. Swing is an amazing framework built upon the concept of MVC (Model View Controller). Now, why does it take a rocket scientist to realize that the use of these visual designers breaks the most fundamental concept of Swing? This mixing of concerns is not only ugly, but it is also completely unnecessary! <a href="http://uic.sf.net">UIC</a> is a project that promotes an excellent level of seperation of concerns and helps generate very maintainable applications. Layout your application using <a href="http://www.trolltech.com">QtDesigner</a>, and use UIC to generate a base Swing class. From there, you can extend the generated class to perform all of your buisness logic and dynamic coding. Sounds like MVC as it was meant to be! Also, the Eclipse project has a solution on the horizon that may quiet many of my fears. The <a href="http://www.eclipse.org/vep">Eclipse Visual Editor Project</a> appears to have an amazing product on their hands, and I will have to wait and see how it actually performs.</p>
Human Compilers2004-01-13T00:00:00+00:00https://codecrate.com/2004/01/human-compilers<p>I just finished taking an assessment test of my programming ability, and I came away feeling like I was supposed to be a Human Compiler. I’m a programmer, not a syntax machine. That’s what IDE’s and compilers are for. Several questions regarding source code structure and correctness about made me vomit. I didn’t care if it compiled or not, it was just plain ugly! If someone on my development team wrote the crappy code that I was shown today, I would have smacked them silly. I don’t care if the code works if it’s not CLEAR, CONSISE, and MAINTAINABLE.</p>
<p>If someone else’s source code is going to be used, it should be stuff that you’ll see in the real world. Otherwise, these standardized tests should simply give you a set of JUnit tests, and the code you write should be run against them to determine correctness.</p>
Code Templates vs. Code Generation2004-01-05T00:00:00+00:00https://codecrate.com/2004/01/code-templates-vs-code-generation<p>How does code templating compare to code generation? What are the benifits/drawbacks, and what should you use? Code templating is a common feature of IDE’s like netbeans and eclipse. Basically, it’s a wizard to write code for you. Code templates range in simplicity from if/else code blocks to basic Java beans and GUI design, to complex J2EE objects like EJB’s. Oracle’s JDeveloper has a template that will generate EJB interfaces (home/remote), deployment descriptor, and the implementation class. Code generation is done by a variety of tools like <a href="http://xdoclet.sf.net">XDoclet</a>. Using a design pattern very similar to MVC, the source code is only the model for of the overall application. The code generating tool will take the source code at compile time and generate files/code from some form of metadata. Code generation at runtime would be an amazing feat, and maybe AOP will address this somehow?</p>
<p>The difference between templating and generation comes AFTER the files or code have been created or modified. In my opinion, this is where the hidden cost of code templating comes into play. Using code templating, after the code is generated, the code is now owned by the developer and it is up to them to further modify or touch up the code (ex: coding style or standards).</p>
<p>Code templating and generation both have one possible drawback. At the expense of making coding faster and more efficient, there is a decreased understanding of the code’s “plumming”. Nothing frustrates me more than hearing, “I don’t know what happened, the IDE/build tool did it for me.”. Here’s a new’s flash for you, these tools are to HELP you, not BABYSIT you. If you can’t code without them, don’t code!</p>
Cell Phones and Stupid People2004-01-05T00:00:00+00:00https://codecrate.com/2004/01/cell-phones-and-stupid-people<p>Most states are looking into banning general cell phone use while driving unless you have some kind of hands free equipment. I have witnessed first hand that regardless of using a cell phone, certain people are too stupid and should not even be allowed to drive.</p>
<p>Case and point comes while I was driving this weekend and while talking on my cell phone (with NO hands free crap), some redneck in their 12 ton S.U.V. tries to merge into my driver side door. I somehow managed to lay on the horn, swerve out of the way, stay on the highway going 70MPH, and still maintain the conversation on the cell phone. Granted, I am the smartest man alive, but is it honestly that difficult to multitask? I suggest that instead of banning cell phone use for EVERYONE, stupid people should just be locked away somewhere, so they won’t get in my way.</p>
Security Administration Frustration2004-01-02T00:00:00+00:00https://codecrate.com/2004/01/security-administration-frustration<p>Let me just say that I’m frustrated at the plethora of different</p>
<p>security infrastructures that exist in my environment and their apparent</p>
<p>lack of interoperability. For starters, I’ll list the number</p>
<p>of different accounts I have to deal with on a daily basis:</p>
<p>-</p>
<p>1 Windows NT account</p>
<p>-</p>
<p>2 seperate Linux accounts</p>
<p>-</p>
<p>1 intranet account to access internal applications</p>
<p>-</p>
<p>1 Issue Tracking account (<a href="http://scarb.tigris.org">scarab</a>)</p>
<p>-</p>
<p>1 Reporting system account (<a href="http://oreports.sf.net">openreports</a>)</p>
<p>-</p>
<p>7 seperate database accounts</p>
<p>I can’t imagine the total cost of supporting this infrastructure, but it</p>
<p>has to be immense. Not to mention that managing this many accounts leads</p>
<p>to a complete lack of security. There’s no possible way for me to keep</p>
<p>up with changing all of these passwords every 3 months like I should.</p>
<p>The most frustating aspect to this setup to me is the inability to get</p>
<p>our internal applications to work with Scarab and Openreports. I’ve</p>
<p>developed a suite of internal applications that use JAAS to provide</p>
<p>independance accross any account management system (LDAP, DB, etc), and</p>
<p>it has worked EXTREMELY well. Scarab and Openreports install their own</p>
<p>set of users/roles and all security checks are done outside of a JAAS</p>
<p>configuration.</p>
<p>The question remains why would a server side Java application not use</p>
<p>container managed security? SAML and the [</p>
<p>Liberty Alliance](http://www.projectliberty.org) are still on the horizon and promise to allow these</p>
<p>desparate systems to work together somehow, but until that time, why do</p>
<p>we keep reinventing the wheel? There is an obvious need for Java open</p>
<p>source account management software. Does anything exist?</p>
Down with BI systems2003-12-30T00:00:00+00:00https://codecrate.com/2003/12/down-with-bi-systems<p>What the heck is the obsession with overpriced fancy toys called Business Information Systems? In the most general sense, they are reporting engines. Some have admiditly nice features, but none that I can justify 10,000 bucks for. Case and point is Oracle’s Reporting engine. I’ve sat through enough demo’s to see the thing in action and see my colleague’s jaws drop to the floor, regardless of the price tag. It doesn’t take a genius to realize that a “comparable” solution could be written from scratch in about a month without the feature bloat. I have done so myself, but without the little extras that the big names throw in, it turns no heads.</p>
<p>I see a genuine need in the open source community for a high performance, full featured reporting engine. Taking a look at the current offerings, I see a lot of potential. <a href="http://jasperreports.sf.net">JasperReports</a> is an EXCELLENT reporting engine, and <a href="http://www.jfree.org">JFreeChart</a> has the data graphing down to a “T”. <a href="http://oreports.sf.net">OpenReports</a> attempts bring these reports to the web tier, and I think it does a fairly good job, but there is more work to be done. Here is a list of features I need to see in a reporting solution:</p>
<ol>
<li>Display the buisness data in different report/chart combinations. Summarizing data into graphs is EXTREMELY big selling point. <a href="http://www.devx.com/xml/Article/7956/1954">Devx has a great article</a>on how to do this, and all that would need to be done would to have the report generated, then transform the XML report into a chartable dataset.</li>
<li>Caching. Reports can be data hogs and take too much time to build. Each report should be configured for a length of time to be cached. If a user queries the report with the same parameters, pull from the cache instead of requerying.</li>
<li>Scheduling and delivery. Again, long running reports are normally scheduled for “non business hours”, then either saved in cache, or delivered (ex: by email) to users.</li>
</ol>
<p>I have started a project over at java.net called <a href="http://riva.dev.java.net">RIVA</a> to address a few of these problems, and hopefully collaborate with other projects to come up with some kind of solution.</p>
Feature Driven Development2003-12-29T00:00:00+00:00https://codecrate.com/2003/12/feature-driven-development<p>There are many complex facets of software development, and in many ways, I think the open source world has adopted them quicker and better than the corporate world. There are many reasons for this, but I think the main factor is that since open source projects have developers not confined to the same office (or office hours for that matter), there must be an organized development environment and communication structure.</p>
<p>There are many different development styles (XP, SCRUM, etc), and what I’m proposing here is a simple but effective summary of some of these practices. These guidelines target 3 groups of people directly involved in the process; clients, developers, and managers.</p>
<ol>
<li>All 3 groups must communicate using a standardized platform. In general, this means using some form of issue tracking software (bugzilla, jira, <a href="http://scarab.tigris.org">scarab</a>, xplanner, etc). All too often, corporations fall into this kind of trap: clients send requests to managers, managers communicate to developers, <em>black hole</em> and clients do not know how/when features/fixes are put in place. Issue tracking is frowned upon as a “waste of time”, but considering the benifets of having direct and fluid communication between clients and developers, it’s a must have.</li>
<li>Clients define the feature set. Managers work to break down features into workable pieces, but having the clients actually involved in this creates a great deal of “project ownership” for them.</li>
<li>Clients set the priority of features, thus defining the project roadmap and release schedule. If the client decides that feature A is a hot item even though it requires a great deal of side work and wasn’t scheduled until later in the project, TOUGH! Managers should be informing clients and developers on the ramifications of these changes (possibly swaying clients to wait until time permits), but the bottom line is that the clients know what they “need”.</li>
</ol>
<p>This is a consise listing of what I would call Feature Driven Development. It doesn’t get bogged down with guidelines and rules like some other practices. I’m just a software developer, but I see the corporate environment needing a big kick in the pants to get some basic software development practices in place.</p>
My first blog2003-12-20T00:00:00+00:00https://codecrate.com/2003/12/my-first-blog<p>Okay, here goes my first blog. Ignore my innane ramblings from here on out.</p>