<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Viking Hammer</title>
	
	<link>http://vikinghammer.com</link>
	<description>Just some rambling</description>
	<lastBuildDate>Thu, 02 Feb 2012 16:31:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
	
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/VikingHammer" /><feedburner:info uri="vikinghammer" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://vikinghammer.com/?pushpress=hub" /><item>
		<title>Connecting Highcharts and jqGrid with trigger and bind</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/sZf02xIi07M/</link>
		<comments>http://vikinghammer.com/2012/02/02/connecting-highcharts-and-jqgrid-with-trigger-and-bind/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 16:31:25 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[highcharts]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=238</guid>
		<description><![CDATA[I have a page where I&#8217;m using Highcharts for a graph, and jqGrid for a grid; they&#8217;re showing different views of similar data, but are sourced from two different calls to the backend. The graph is a summary, and the grid is detailed data, and it doesn&#8217;t make much sense for that to come back [...]]]></description>
			<content:encoded><![CDATA[<p>I have a page where I&#8217;m using <a href="http://www.highcharts.com/products/highcharts">Highcharts</a> for a graph, and jqGrid for a grid; they&#8217;re showing different views of similar data, but are sourced from two different calls to the backend. The graph is a summary, and the grid is detailed data, and it doesn&#8217;t make much sense for that to come back in one call.</p>

<p>In my graph, I have several lines; Highcharts lets the user show/hide those lines manually. I want to make the data in the grid reflect what&#8217;s been shown or hidden in the graph.</p>

<p>I first tried to bind the Highcharts series via Knockout, somehow, to what should be shown in the grid. Maybe it&#8217;s possible, but I couldn&#8217;t figure out how to get Knockout to bind to variables deep inside the Highcharts object structure.</p>

<p>But Javascript and jQuery have event listeners, right? Hopefully Highcharts is nice enough to use those, so I can get an event when the series visibility is changed.</p>

<p>I looked in the Highcharts source, and down in the Series&#8217; <strong>setVisibility</strong> method (more than 10000 lines deep), I found this:</p>

<pre><code>fireEvent(series, showOrHide);
</code></pre>

<p>(The &#8220;showOrHide&#8221; variable is always either &#8220;show&#8221; or &#8220;hide&#8221;.)</p>

<p>That looks promising, but what does fireEvent do?</p>

<pre><code>fireEvent = function (el, type, eventArguments, defaultFunction) {
    var event = jQ.Event(type),
        detachedType = 'detached' + type;
    extend(event, eventArguments);

    // Prevent jQuery from triggering the object method that is named the
    // same as the event. For example, if the event is 'select', jQuery
    // attempts calling el.select and it goes into a loop.
    if (el[type]) {
        el[detachedType] = el[type];
        el[type] = null;
    }

    // trigger it
    jQ(el).trigger(event);

    // attach the method
    if (el[detachedType]) {
        el[type] = el[detachedType];
        el[detachedType] = null;
    }

    if (defaultFunction &amp;&amp; !event.isDefaultPrevented()) {
        defaultFunction(event);
    }
};
</code></pre>

<p>Most of that is necessary stuff that I don&#8217;t care about, but the key line is this one:</p>

<pre><code>jQ(el).trigger(event);
</code></pre>

<p>That means that if I grab the Series object and wrap it with a jQuery call, I can call &#8220;bind&#8221; on it and be notified any time &#8220;trigger&#8221; is called. So I did that, for each series object:</p>

<pre><code>var listener = function() {
    MyGrid.updateGrid(MyGraph.visibleSeries());
};
for (var i=0; i &lt; this.chart.series.length; i++) {
    $(this.chart.series[i]).bind("show", listener);
    $(this.chart.series[i]).bind("hide", listener);
}
</code></pre>

<p>I created a function and saved it to a variable, and bound it to the &#8220;show&#8221; and &#8220;hide&#8221; events on each of my Series. I could have passed it in as an anonymous function, but I would have had to define it twice. I could have created it as an actual function on my object, but this way it&#8217;s scoped right here and won&#8217;t be accessible anywhere else.</p>

<p>On my MyGraph object, I need to be able to check which series are currently visible:</p>

<pre><code>function visibleSeries() {
    var selected = [];
    for (var i=0; i &lt; MyGraph.chart.series.length; i++) {
        if (MyGraph.chart.series[i].visible) {
            selected.push(MyGraph.chart.series[i].name);
        }
    }
    return selected;
}
</code></pre>

<p>That returns a list of series names, which I can then pass to the MyGrid object to update which lines it should display:</p>

<pre><code>var updateGrid = function(events) {
    var newData = {};
    newData.page = 1;
    newData.total = 1;
    newData.rows = [];
    for (var i=0; i &lt; MyGrid.gridData.rows.length; i++) {
        if ($.inArray(MyGrid.gridData.rows[i].cell[1], events) != -1) {
            newData.rows.push(MyGrid.gridData.rows[i]);
        }
    }
    newData.records = newData.rows.length;
    MyGrid.updateData(JSON.stringify(newData));
};
</code></pre>

<p>I&#8217;ve stored &#8220;gridData&#8221; in MyGrid, which is all the data for the grid that was returned from the server. It doesn&#8217;t get updated here, which means I can look at the full dataset again each time the visible series changes, and update the grid accordingly.</p>

<p>Victory! Now, whenever the user hides a series in the graph, it disappears from the grid. When they add it back, it reappears in the grid. The grid also updates its display of total records available, and the number of pages, and always jumps back to the first page.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/sZf02xIi07M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2012/02/02/connecting-highcharts-and-jqgrid-with-trigger-and-bind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2012/02/02/connecting-highcharts-and-jqgrid-with-trigger-and-bind/</feedburner:origLink></item>
		<item>
		<title>Cassandra Counter Columns</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/bVpQ0fO0suI/</link>
		<comments>http://vikinghammer.com/2012/01/26/cassandra-counter-columns/#comments</comments>
		<pubDate>Thu, 26 Jan 2012 16:44:25 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Cassandra]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=231</guid>
		<description><![CDATA[Cassandra supplies &#8220;counter columns&#8221;, which are used to store a number that incrementally counts a value. You might use a counter to keep track of pageviews or other events. I couldn&#8217;t find much documentation about how to use these, especially through the CLI (which is where I typically start out when trying to investigate a [...]]]></description>
			<content:encoded><![CDATA[<p>Cassandra supplies &#8220;counter columns&#8221;, which are used to store a number that incrementally counts a value. You might use a counter to keep track of pageviews or other events. </p>

<p>I couldn&#8217;t find much documentation about how to use these, especially through the CLI (which is where I typically start out when trying to investigate a new feature). So here goes with an explanation of what I&#8217;ve found.</p>

<p>Create your &#8220;counter&#8221; column family:</p>

<pre><code>create column family MyCounters with default_validation_class=CounterColumnType and comparator=UTF8Type;
</code></pre>

<p>Note that you don&#8217;t <em>have</em> to create the column family with a &#8220;default&#95;validation&#95;class&#8221; of CounterColumnType, but by doing so you get a few major advantages:</p>

<ol>
<li>You can create arbitrary column names as counters, rather than having to add them explicitly and being required to know ahead of time what you&#8217;ll be counting</li>
<li><p>I couldn&#8217;t figure out how to actually do that, despite the fact that the documentation I read seemed to indicate it should be possible; instead, when I attempted to <strong>update column family</strong> with some column&#95;metadata, it failed, like so:</p>

<pre><code>[default@MyTest] update column family MyCounters with column_metadata = [{column_name:thing-1, validation_class:CounterColumnType}];
org.apache.thrift.TApplicationException: Internal error processing system_update_column_family
</code></pre></li>
</ol>

<p>That&#8217;s all the information you get in the CLI. Apparently, when you see &#8220;Internal error&#8221;, that means you need to look in <strong>/var/log/cassandra/system.log</strong>, where you&#8217;ll see:</p>

<pre><code>ERROR [pool-2-thread-1] 2012-01-26 09:41:01,705 Cassandra.java (line 4038) Internal error processing sys
tem_update_column_family
java.lang.RuntimeException: org.apache.cassandra.config.ConfigurationException: Cannot add a counter col
umn (thing-1) in a non counter column family
        at org.apache.cassandra.thrift.CassandraServer.system_update_column_family(CassandraServer.java:
1049)
        at org.apache.cassandra.thrift.Cassandra$Processor$system_update_column_family.process(Cassandra
.java:4032)
        at org.apache.cassandra.thrift.Cassandra$Processor.process(Cassandra.java:2889)
        at org.apache.cassandra.thrift.CustomTThreadPoolServer$WorkerProcess.run(CustomTThreadPoolServer
.java:187)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:680)
Caused by: org.apache.cassandra.config.ConfigurationException: Cannot add a counter column (thing-1) in a
 non counter column family
        at org.apache.cassandra.config.CFMetaData.validate(CFMetaData.java:994)
        at org.apache.cassandra.config.CFMetaData.fromThrift(CFMetaData.java:684)
        at org.apache.cassandra.thrift.CassandraServer.system_update_column_family(CassandraServer.java:
1045)
        ... 6 more
</code></pre>

<p>So that&#8217;s why it&#8217;s important to <strong>create column family</strong> as a &#8220;counter column family&#8221; from the start. Because of this, I intend to use these counter column families as what are essentially extra, metadata-only denormalized column families; ie, I won&#8217;t be mixing actual data in with these counters. Instead, the actual data will live elsewhere, and the counters will live apart, by themselves. Remember, in Cassandra, this sort of denormalization is considered not only acceptable, but required.</p>

<p>Okay, enough of that diversion. Let&#8217;s continue with using the CLI to make and use our counter column family.</p>

<p>I usually tell the CLI to use UTF-8, rather than raw hex bytes (I don&#8217;t know why it defaults to expecting you, a human, to be able to read and write raw bytes):</p>

<pre><code>assume MyCounters keys as utf8;
</code></pre>

<p>Now you can use <strong>incr</strong> to increment your counters:</p>

<pre><code>incr MyCounters['key-1']['thing-1'];
incr MyCounters['key-1']['thing-2'];
incr MyCounters['key-1']['thing-1'];
incr MyCounters['key-2']['thing-1'];
incr MyCounters['key-2']['thing-3'];
incr MyCounters['key-2']['thing-3'];
incr MyCounters['key-1']['thing-4'] by 5;
</code></pre>

<p>And you can pull out the whole thing with <strong>list</strong>:</p>

<pre><code>[default@MyTest] list MyCounters;
Using default limit of 100
-------------------
RowKey: key-1
=&gt; (counter=thing-1, value=2)
=&gt; (counter=thing-2, value=1)
=&gt; (counter=thing-4, value=5)
-------------------
RowKey: key-2
=&gt; (counter=thing-1, value=1)
=&gt; (counter=thing-3, value=2)

2 Rows Returned.
Elapsed time: 8 msec(s).
</code></pre>

<p>Or you can <strong>get</strong> the values for a single RowKey:</p>

<pre><code>[default@MyTest] get MyCounters['key-1'];
=&gt; (counter=thing-1, value=2)
=&gt; (counter=thing-2, value=1)
=&gt; (counter=thing-4, value=5)
Returned 3 results.
Elapsed time: 8 msec(s).
</code></pre>

<p>You can also <strong>get</strong> the value of a single counter within a column:</p>

<pre><code>[default@MyTest] get MyCounters['key-1']['thing-1'];
=&gt; (counter=thing-1, value=2)
Elapsed time: 8 msec(s).
</code></pre>

<p>As you can see, counter columns are not actually complicated or difficult to use. This got me around some of the initial issues I encountered, so hopefully it helps someone else.</p>

<p><strong>One last thing</strong></p>

<p>When using counters, there are <a href="http://www.datastax.com/docs/1.0/ddl/column_family#about-counter-columns">some things to consider</a> when it comes to your consistency level:</p>

<blockquote>
  <p>it’s important to understand that unlike normal columns, a write to a counter requires a read in the background to ensure that distributed counter values remain consistent across replicas. If you write at a consistency level of ONE, the implicit read will not impact write latency, hence, ONE is the most common consistency level to use with counters.</p>
</blockquote>

<p>I haven&#8217;t addressed this yet, but I&#8217;ll keep it in mind.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/bVpQ0fO0suI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2012/01/26/cassandra-counter-columns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2012/01/26/cassandra-counter-columns/</feedburner:origLink></item>
		<item>
		<title>Using Dependo to help with testing</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/hRFwElVTNnA/</link>
		<comments>http://vikinghammer.com/2012/01/08/using-dependo-to-help-with-testing/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 21:06:54 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Dependo]]></category>
		<category><![CDATA[Rspec]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=226</guid>
		<description><![CDATA[Last week, I introduced Dependo, my new dependency injection framework for Ruby. Today, I want to demonstrate something that it makes very easy &#8212; and something that I wouldn&#8217;t know how to adequately test without it. In our OCSP responder, we rely on a Redis database and can configure (at startup) whether we want to [...]]]></description>
			<content:encoded><![CDATA[<p>Last week, I <a href="http://vikinghammer.com/2012/01/04/ruby-dependency-injection-introducing-dependo/">introduced Dependo</a>, my new dependency injection framework for Ruby.</p>

<p>Today, I want to demonstrate something that it makes very easy &#8212; and something that I wouldn&#8217;t know how to adequately test without it.</p>

<p>In our OCSP responder, we rely on a Redis database and can configure (at startup) whether we want to copy the &#8220;nonce&#8221;* from the request into the response.</p>

<p><em>* The idea of the &#8220;nonce&#8221; is that it increases the browser&#8217;s ability to trust a response from the server, because not only is the response signed, the signed response contains the timestamp that was given in the request. It makes it much, much more difficult for a replay attack to work against the service. This is mostly irrelevant to my discussion of Dependo, I just wanted to explain it (a little) so you&#8217;re not too confused.</em></p>

<p>But in our unit tests, we need to mock the Redis database (because we don&#8217;t want to have to actually run a database in order for our tests to pass) and re-configure that &#8220;copy nonce&#8221; behavior between tests.</p>

<p>First, before each test, we set up our <strong>Dependo::Registry</strong> with the values we&#8217;re going to want. We clear it out from the previous test, set the Logger to not log anything (we can change that if we want to see logging to help figure something out, but generally we don&#8217;t want to log anything during tests), mock Redis, set a default &#8220;copy nonce&#8221; setting (defaults to false here), and read our config file (I&#8217;d really rather not do it like this, we&#8217;ll get around to it later, I hope).</p>

<pre><code>before :each do
    # clear the dependo before each test
    Dependo::Registry.clear
    Dependo::Registry[:log] = Logger.new(nil)

    # we always want to mock with a new redis
    @redis = double("redis")
    Dependo::Registry[:redis] = @redis

    # default value for :copy_nonce is false (can override on a per-test basis)
    Dependo::Registry[:copy_nonce] = false

    # read the config.yaml
    Dependo::Registry[:config_pool] = R509::Config::CaConfigPool.from_yaml("certificate_authorities", File.read("config.yaml"))
end
</code></pre>

<p>Now, we haven&#8217;t finished setting up each test. In our <strong>config.ru</strong>, we also add an R509::Ocsp::Signer object to the Dependo::Registry. The Ocsp::Signer is constructed from the other items in the Dependo::Registry that are configured, in production, in the config.ru file. So where did we put it?</p>

<pre><code>def app
    # this is executed after the code in each test, so if we change something in the dependo registry, it'll show up here (we will set :copy_nonce in some tests)
    Dependo::Registry[:ocsp_signer] = R509::Ocsp::Signer.new(
        :configs =&gt; Dependo::Registry[:config_pool].all,
        :validity_checker =&gt; R509::Validity::Redis::Checker.new(Dependo::Registry[:redis]),
        :copy_nonce =&gt; Dependo::Registry[:copy_nonce]
    )
    R509::Ocsp::Responder
end
</code></pre>

<p>I define it in my spec file&#8217;s #app method because of the order of execution. That order is:</p>

<ol>
<li>The code in &#8220;before :each&#8221;</li>
<li>The code in the individual test</li>
<li>The code in #app</li>
</ol>

<p>Why is that relevant?</p>

<p>Because, in the case where we want to override the default value of Dependo::Registry[:copy_nonce], we need to be able to do that in the individual test code, and then read it in the #app method where the R509::Ocsp::Signer is built.</p>

<pre><code>it "copies nonce when copy_nonce is true" do
    @redis.should_receive(:hgetall).with("cert:/C=US/ST=Illinois/L=Chicago/O=Ruby CA Project/CN=Test CA:872625873161273451176241581705670534707360122361").and_return({"status" =&gt; R509::Validity::VALID})

    # set to true for this test (this works because the app doesn't get set up until after this code)
    Dependo::Registry[:copy_nonce] = true

    get '/MHsweTBSMFAwTjAJBgUrDgMCGgUABBQ4ykaMB0SN9IGWx21tTHBRnmCnvQQUeXW7hDrLLN56Cb4xG0O8HCpNU1gCFQCY2eXAtMNzVS33fF0PHrUSjklF%2BaIjMCEwHwYJKwYBBQUHMAECBBIEEDTJniOQonxCRmmHAHCVstw%3D'
    request = OpenSSL::OCSP::Request.new(Base64.decode64("MHsweTBSMFAwTjAJBgUrDgMCGgUABBQ4ykaMB0SN9IGWx21tTHBRnmCnvQQUeXW7hDrLLN56Cb4xG0O8HCpNU1gCFQCY2eXAtMNzVS33fF0PHrUSjklF+aIjMCEwHwYJKwYBBQUHMAECBBIEEDTJniOQonxCRmmHAHCVstw="))
    ocsp_response = R509::Ocsp::Response.parse(last_response.body)
    request.check_nonce(ocsp_response.basic).should == R509::Ocsp::Request::Nonce::PRESENT_AND_EQUAL
end
</code></pre>

<p>Without Dependo (or a framework with similar capability), it&#8217;d be more difficult to test this behavior. Frankly, I don&#8217;t know if you could even do it, much less do it elegantly.</p>

<p>So the first time a tough spot like this came up, I found myself glad to have <a href="https://github.com/sirsean/dependo">Dependo</a>.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/hRFwElVTNnA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2012/01/08/using-dependo-to-help-with-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2012/01/08/using-dependo-to-help-with-testing/</feedburner:origLink></item>
		<item>
		<title>Ruby Dependency Injection: Introducing Dependo</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/TFQ_mW3bnag/</link>
		<comments>http://vikinghammer.com/2012/01/04/ruby-dependency-injection-introducing-dependo/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 21:41:17 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Dependo]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=215</guid>
		<description><![CDATA[Today, I discovered that I need Dependency Injection in Ruby. Other people who are probably smarter than I am have said you don&#8217;t need it, because Ruby is so dynamic and you can just do whatever you want to without having the structure provided by dependency injection. DI frameworks are unnecessary. In more rigid environments, [...]]]></description>
			<content:encoded><![CDATA[<p>Today, I discovered that I need Dependency Injection in Ruby. Other people who are probably smarter than I am <a href="http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming">have said you don&#8217;t need it</a>, because Ruby is so dynamic and you can just do whatever you want to without having the structure provided by dependency injection.</p>

<blockquote>
  <p><strong>DI frameworks are unnecessary.</strong> In more rigid environments, they have value. In agile environments like Ruby, not so much. The patterns themselves may still be applicable, but beware of falling into the trap of thinking you need a special tool for everything. Ruby is Play-Doh, remember! Let’s keep it that way.</p>
</blockquote>

<p>Others have apparently taken that to mean that dependency injection is simply unnecessary in Ruby, despite the fact that that&#8217;s explicitly not what Jamis Buck is saying here.</p>

<blockquote>
  <p>So, is there no room for DI in Ruby? There definitely is. I use DI nearly every day in Ruby, but I do not use a DI framework. Ruby itself has sufficient power to represent any day-to-day DI idioms you need.</p>
</blockquote>

<p>He talks about the ways he injects his dependencies, using Ruby without any framework:</p>

<ul>
<li>Factory method that takes an optional class and instantiates an object for you</li>
<li>A second factory method that you can override in a subclass for testing</li>
<li>Pass in either classes or implementations in a constructor</li>
</ul>

<p>But let&#8217;s say you&#8217;ve got the following problem:</p>

<ul>
<li>You&#8217;re writing a web app, using Sinatra (or anything else, really)</li>
<li>You&#8217;re using an ORM library, like Sequel

<ul>
<li>Your models have methods on them</li>
</ul></li>
<li>You want some sort of logging

<ul>
<li>You want to define just one Logger object and use it in your Sinatra app and your Sequel models</li>
</ul></li>
</ul>

<p>Passing the Logger instance from the Sinatra app to the Sequel models either in a constructor or in each method is an ugly hack, and a non-starter. So what do you do?</p>

<p>Enter: <a href="https://github.com/sirsean/dependo">Dependo</a>!</p>

<p>Dependo lets you register your Logger object. I do this in my config.ru:</p>

<pre><code>require "dependo"
Dependo::Registry[:log] = Logger.new(STDOUT)
</code></pre>

<p>Then, you can just include everything in the Registry as methods in your Sinatra app, and use them as if they&#8217;re instance methods:</p>

<pre><code>class MyApp &lt; Sinatra::Base
    include Dependo::Mixin

    get "/?" do
        log.info "I'm logging!"

        "Hello, world."
    end
end
</code></pre>

<p>You can also include the methods in your Sequel models:</p>

<pre><code>class MyThing &lt; Sequel::Model
    include Dependo::Mixin
    extend Dependo::Mixin

    def self.do_some_query
        log.info "I'm querying with a class method"
        self
    end

    def perform_some_other_action
        log.info "I'm calling an instance method"
    end
end
</code></pre>

<p>Note that in the model class, we used both <strong>include</strong> and <strong>extend</strong>. We do that so we can get the Dependo functionality in both instance methods (via include) <em>and</em> class methods (via extend).</p>

<p>Now, the Dependo::Registry doesn&#8217;t care what you put in it. You&#8217;ve already seen that we can put an object in it (like a Logger, as above). You can also put in a number,</p>

<pre><code>Dependo::Registry[:my_important_number] = 7
</code></pre>

<p>or a string,</p>

<pre><code>Dependo::Registry[:my_important_string] = "seven"
</code></pre>

<p>or even a function,</p>

<pre><code>Dependo::Registry[:my_important_proc] = Proc.new { |x| x + 7 }
</code></pre>

<p>or a lambda,</p>

<pre><code>Dependo::Registry[:my_important_lambda] = lambda { |x| x * 7 }
</code></pre>

<p>and you&#8217;ll use those like so:</p>

<pre><code>class DemoClass
    include Dependo::Mixin

    def do_things
        puts my_important_number
        puts my_important_string
        puts my_important_proc.call(5)
        puts my_important_lambda.call(6)
    end
end
</code></pre>

<p><em>* I don&#8217;t know how to call a Proc or a lambda in this case without using #call on them. I&#8217;d much rather the syntax be something like &#8220;my&#95;important&#95;lambda(6)&#8221; &#8230; so, does anybody have any ideas? Thanks!</em></p>

<p>Do I think dependency injection is necessary, even in Ruby? I do. It helps with separation of concerns, so each of your classes can do only the things it cares about; it helps with unit testing, so you can mock your classes&#8217; dependencies rather than test them all the way through (as you might in an integration test). You also don&#8217;t have to muck up your constructors or method definitions; your code&#8217;s API can stay the way you want it, and having to &#8220;include&#8221; and/or &#8220;extend&#8221; a mixin is a small price to pay (I think) for what you get.</p>

<p>I&#8217;m using Dependo with some success. Let me know if you do too &#8212; or, more importantly, if you find something about it that sucks, so I can try to fix it.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/TFQ_mW3bnag" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2012/01/04/ruby-dependency-injection-introducing-dependo/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2012/01/04/ruby-dependency-injection-introducing-dependo/</feedburner:origLink></item>
		<item>
		<title>Ruby OpenSSL::X509::Name throws away unknown subject component names?!</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/UM1g3z4hdPY/</link>
		<comments>http://vikinghammer.com/2011/12/21/ruby-opensslx509name-throws-away-unknown-subject-component-names/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 21:46:55 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[OpenSSL]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=203</guid>
		<description><![CDATA[OpenSSL::X509::Name is a class in Ruby&#8217;s OpenSSL bindings that lets you deal with the subject line of SSL certificates. It&#8217;s useful and necessary, though dealing with it can be kind of annoying. But as of Ruby 1.9.3, there&#8217;s a big bug that threatens to be a deal-breaker for anyone doing significant SSL work in Ruby: [...]]]></description>
			<content:encoded><![CDATA[<p>OpenSSL::X509::Name is a class in Ruby&#8217;s OpenSSL bindings that lets you deal with the subject line of SSL certificates. It&#8217;s useful and necessary, though dealing with it can be kind of annoying. But as of Ruby 1.9.3, there&#8217;s a big bug that threatens to be a deal-breaker for anyone doing significant SSL work in Ruby: its handling of undefined OIDs.</p>

<p>You&#8217;re accustomed to dealing with subject components by their shortname, things like &#8220;CN&#8221; or &#8220;O&#8221; or &#8220;C&#8221;, etc. But underneath the shortname is a different representation; the longname can be something like &#8220;1.3.6.1.4.1.311.60.2.1.3&#8243; instead.</p>

<p>Now, you&#8217;re allowed to create an OpenSSL::X509::Name object with an unknown OID like this.</p>

<pre><code>name = OpenSSL::X509::Name.new [["CN", "vikinghammer.com"], ["1.3.6.1.4.1.311.60.2.1.3", "US"]]
</code></pre>

<p>And if you now get the subject line, all is well.</p>

<pre><code>name.to_s
#=&gt; "/CN=vikinghammer.com/1.3.6.1.4.1.311.60.2.1.3=US"
</code></pre>

<p>But sometimes you want to get that array (like the one you passed into the constructor) back out and deal with it directly. We&#8217;re doing that in one of our projects, where we want to wrap OpenSSL::X509::Name in a friendlier interface. But what happens if you do it?</p>

<pre><code>name.to_a
#=&gt; [["CN", "vikinghammer.com", 12], ["UNDEF", "US", 12]]
</code></pre>

<p><strong>UNDEF</strong>?! What help is that, you guys? I mean, after all &#8230;</p>

<pre><code>OpenSSL::X509::Name.new name.to_a
#OpenSSL::X509::NameError: invalid field name
#    from (irb):8:in `initialize'
#    from (irb):8:in `each'
#    from (irb):8:in `initialize'
#    from (irb):8:in `new'
#    from (irb):8
</code></pre>

<p>Yeah, you can&#8217;t pass the output from OpenSSL::X509::Name#to&#95;a back into the constructor; if you try, it&#8217;ll blow up.</p>

<p>But I kind of need to do that; when we parse a CSR or a certificate, it contains an OpenSSL::X509::Name, and we need to be able to read it. When we do that, we read the array out of #to&#95;a, because parsing the subject line string out of #to&#95;s is dangerously fragile (because the delimiters, &#8220;/&#8221; and &#8220;=&#8221;, can be used unescaped in the subject component values).</p>

<p>Enough complaining. What&#8217;s the solution?</p>

<p>We staged a two-pronged attack on this problem. The first step was to <a href="https://github.com/reaperhulk/ruby/compare/ruby:trunk...aa668275">patch Ruby</a>, to fix <a href="http://bugs.ruby-lang.org/issues/5787">the bug</a> in its OpenSSL bindings. My teammate <a href="http://langui.sh">Paul Kehrer</a> did this.</p>

<pre><code>short_name = OBJ_nid2sn(OBJ_ln2nid(long_name));
if (strcmp(short_name,"UNDEF") == 0) {
    return_name = &amp;long_name;
} else {
    return_name = short_name;
}
</code></pre>

<p>It&#8217;s a fairly simple fix (once you&#8217;ve, you know, gotten deep enough into Ruby&#8217;s C source). It used to attempt to translate the longname into a shortname, and if no translation was found, it&#8217;d just leave the shortname as UNDEF. Instead, he checks for UNDEF and if that&#8217;s the shortname, he resets it to be the (original) longname. That way, the OID is preserved in the OpenSSL::X509::Name object. Victory!</p>

<p>But &#8230; that&#8217;d mean our project would only work on a custom patch of Ruby 1.9.3, and we were hoping to maintain compatibility across both 1.8 and 1.9, and we certainly can&#8217;t rely on people to use Paul&#8217;s patch rather than the actual release of Ruby. And even if (hopefully &#8220;when&#8221;) Ruby accepts the patch, that&#8217;d mean we&#8217;d have to require Ruby (at least) 1.9.4, which is pretty close to unacceptable. We need an interim solution &#8212; where &#8220;interim&#8221; is taken to mean &#8220;useful for at least a few years, potentially indefinitely&#8221;.</p>

<p>That&#8217;s where the second prong of our attack comes in. Sanitizing the OpenSSL::X509::Name#to&#95;a right in Ruby!</p>

<pre><code># Sanitize an X509::Name. The #to_a method replaces unknown OIDs with "UNDEF", but the #to_s
# method doesn't. What we want to do is build the array that would have been produced by #to_a
# if it didn't throw away the OID.
class NameSanitizer
    # @option name [OpenSSL::X509::Name]
    # @return an array of the form [["OID", "VALUE], ["OID", "VALUE"]] with "UNDEF" replaced by the actual OID
    def sanitize(name)
        line = name.to_s
        array = name.to_a.dup
        used_oids = []
        undefined_components(array).each do |component|
            begin
                # get the OID from the subject line that has this value
                oids = line.scan(/\/([\d\.]+)=#{component[:value]}/).flatten
                if oids.size == 1
                    oid = oids.first
                else
                    oid = oids.select{ |match| not used_oids.include?(match) }.first
                end
                # replace the "UNDEF" OID name in the array at the index the UNDEF was found
                array[component[:index]][0] = oid
                # remove the first occurrence of this in the subject line (so we can handle the same oid/value pair multiple times)
                line = line.sub("/#{oid}=#{component[:value]}", "")
                # we record which OIDs we've used in case two different unknown OIDs have the same value
                used_oids &lt;&lt; oid
            rescue
                # I don't expect this to happen, but if it does we'll just not replace UNDEF and continue
            end
        end
        array
    end

    private

    # get the components from #to_a that are UNDEF
    # @option array [Array&lt;OpenSSL::X509::Name&gt;]
    # @return [{ :index =&gt; the index in the original array where we found an UNDEF, :value =&gt; the subject component value }]
    def undefined_components(array)
        components = []
        array.each_index do |index|
            components &lt;&lt; { :index =&gt; index, :value =&gt; array[index][1] } if array[index][0] == "UNDEF"
        end
        components
    end
end
</code></pre>

<p>This solution, as you may have noticed, is a little bit more complicated. I&#8217;ll try to explain.</p>

<p>First, we take advantage of the fact that OpenSSL::X509::Name#to&#95;s contains <strong>all</strong> the data we need, despite the fact that #to&#95;a throws it away. So we loop over #to&#95;a to find all the subject components whose name is UNDEF and record their index in the #to&#95;a array, as well as their value (we don&#8217;t need to record their names, because we know they&#8217;re always UNDEF).</p>

<p>Then, we loop over all those UNDEF subject components, and we determine what the original OID was from the subject line string from #to&#95;s. For that, we take advantage of the fact that these unknown OIDs will be of the form 1.2.3.4.5, or something like that; ie, our regex looks for anything with digits and periods in the place of the subject component name, <em>with the same value</em> as the undefined subject component.</p>

<p>Note that we also rely on the fact that #to&#95;s and #to&#95;a maintain the order of subject components, so as we loop over the unknown OIDs, the current one will always correspond to the first match from the subject line. </p>

<p>After updating the subject component name in the array, we remove the subject component from the subject line (but only the first occurrence of it), and we record that we&#8217;ve used that OID. Both of those steps are to ensure that if the same OID occurs multiple times, or if two different OIDs have the same value, that we handle that properly and correctly maintain the order of the components.</p>

<p>And now &#8230;</p>

<pre><code>sanitizer = NameSanitizer.new
sanitizer.sanitize(name)
#=&gt; [["CN", "vikinghammer.com", 12], ["1.3.6.1.4.1.311.60.2.1.3", "US", 12]]

OpenSSL::X509::Name.new(name.to_a)
#OpenSSL::X509::NameError: invalid field name

OpenSSL::X509::Name.new(sanitizer.sanitize(name))
#=&gt; /CN=vikinghammer.com/1.3.6.1.4.1.311.60.2.1.3=US
</code></pre>

<p>It works! As long as we pass the original name to the sanitizer, we can get the original OIDs in the array structure we need (the same one returned from #to&#95;a).</p>

<p>This will work across Ruby 1.8 and 1.9, and if Ruby accepts Paul&#8217;s patch, it&#8217;ll also work in 1.9.4; if the bug is fixed, NameSanitizer#undefined&#95;components will not find any UNDEF subject components, and none of our complex code will ever be touched.</p>

<p>I think this exercise demonstrates a few things:</p>

<ul>
<li>It&#8217;s considerably simpler to fix this kind of thing at a lower level, if possible.</li>
<li>Even if a bug in your language gets fixed, you should still try to figure out a backwards-compatible fix.</li>
<li>Use open source languages! It&#8217;s awesome to have the option of fixing Ruby and submitting a patch.</li>
<li>If you&#8217;re working on an open source project, you can write posts like this about it.</li>
</ul>

<p>This turned a horrifyingly annoying Tuesday evening (when Paul discovered the bug) into a pretty fun Wednesday morning (when we fixed it).</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/UM1g3z4hdPY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2011/12/21/ruby-opensslx509name-throws-away-unknown-subject-component-names/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2011/12/21/ruby-opensslx509name-throws-away-unknown-subject-component-names/</feedburner:origLink></item>
		<item>
		<title>Mocking unit tests in Ruby, with Rspec 2 and test doubles</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/5UvQpJ66jTk/</link>
		<comments>http://vikinghammer.com/2011/12/13/mocking-unit-tests-in-ruby-with-rspec-2-and-test-doubles/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 17:08:51 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Rspec]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=199</guid>
		<description><![CDATA[Mocking in your unit tests is a useful and powerful thing. My experience with it had been with JMock, in Java. But for one of my current projects I&#8217;ve found that I need it with rspec, in Ruby. I didn&#8217;t find a ton of helpful documentation on the subject, so hopefully this explanation helps someone [...]]]></description>
			<content:encoded><![CDATA[<p>Mocking in your unit tests is a useful and powerful thing. My experience with it had been with JMock, in Java. But for one of my current projects I&#8217;ve found that I need it with rspec, in Ruby. I didn&#8217;t find a ton of helpful documentation on the subject, so hopefully this explanation helps someone out.</p>

<p>The concept of this class is that it looks up an SSL certificate serial number in a Redis database, and returns some status information. Those details are mostly irrelevant to the question of mocking, but I thought I&#8217;d get it out of the way.</p>

<pre><code>module R509::Validity::Redis
    class Checker &lt; R509::Validity::Checker
        def initialize(redis)
            raise ArgumentError.new("Redis must be provided") if redis.nil?
            @redis = redis
        end

        def check(serial)
            raise ArgumentError.new("Serial must be provided") if serial.nil? or serial.to_s.empty?

            hash = @redis.hgetall("cert:#{serial}")
            if not hash.nil? and hash.has_key?("status")
                R509::Validity::Status.new(
                    :status =&gt; hash["status"].to_i,
                    :revocation_time =&gt; hash["revocation_time"].to_i || nil,
                    :revocation_reason =&gt; hash["revocation_reason"].to_i || 0
                )
            else
                R509::Validity::Status.new(:status =&gt; R509::Validity::UNKNOWN)
            end
        end
    end
end
</code></pre>

<p>If you just write tests for this, and your constructor looks like:</p>

<pre><code>R509::Validity::Redis::Checker.new(Redis.new)
</code></pre>

<p>then you&#8217;re going to have to actually have a Redis database running for your tests, and you need to have the correct data in it in order for the tests to pass. Obviously, that sucks. You want to avoid that kind of environmental dependency in your unit tests.</p>

<p>Enter mocking. Here&#8217;s a pair of rspec tests that makes sure it returns an UNKNOWN status if nothing is found:</p>

<pre><code>it "gets unknown when serial is not found (returns {})" do
    redis = double("redis")
    checker = R509::Validity::Redis::Checker.new(redis)
    redis.should_receive(:hgetall).with("cert:123").and_return({})
    status = checker.check(123)
    status.status.should == R509::Validity::UNKNOWN
end
it "gets unknown when serial is not found (returns nil)" do
    redis = double("redis")
    checker = R509::Validity::Redis::Checker.new(redis)
    redis.should_receive(:hgetall).with("cert:123").and_return(nil)
    status = checker.check(123)
    status.status.should == R509::Validity::UNKNOWN
end
</code></pre>

<p>(I have two tests here because I&#8217;ve seen the Redis driver return {} if a Hash isn&#8217;t found, but I want to make sure my code still works if it returns nil.)</p>

<p>The first key line is:</p>

<pre><code>redis = double("redis")
</code></pre>

<p>It&#8217;s called &#8220;double&#8221; because you&#8217;re creating a &#8220;test double&#8221; object instead of an actual connection to the Redis database. The test double doesn&#8217;t actually do anything, but if it receives a method call that you didn&#8217;t tell it to expect (or if it doesn&#8217;t receive a method call that you <em>did</em> tell it to expect), it&#8217;ll give you a failing test.</p>

<p>The next key line is where you tell your test double what to expect (and what it should do):</p>

<pre><code>redis.should_receive(:hgetall).with("cert:123").and_return({})
</code></pre>

<p>Let&#8217;s break this down. You&#8217;re telling your test double that it &#8220;should_receive&#8221; a call to the &#8220;hgetall&#8221; method (you use the symbol :hgetall for this), &#8220;with&#8221; the single parameter &#8220;cert:123&#8243;, and it should return an empty hash object {}.</p>

<p>The test double verifies that our Checker#check implementation does actually make this call (and only this call) to the Redis object, and it helpfully returns {}, which then exercises the &#8220;nothing found in the database&#8221; code path. Thus, we can then check that the returned status should equal R509::Validity::UNKNOWN (which would only happen if we reacted properly to the data we told the test double to return).</p>

<p>And what about testing something else, for example that the serial number <em>does</em> exist in the database? Here&#8217;s the spec for a certificate that&#8217;s been revoked:</p>

<pre><code>it "gets revoked with revocation time and reason" do
    redis = double("redis")
    checker = R509::Validity::Redis::Checker.new(redis)
    redis.should_receive(:hgetall).with("cert:123").and_return({"status" =&gt; "1", "revocation_time" =&gt; "789", "revocation_reason" =&gt; "5" })
    status = checker.check(123)
    status.status.should == R509::Validity::REVOKED
    status.revocation_time.should == 789
    status.revocation_reason.should == 5
end
</code></pre>

<p>Here, we say that our test double should receive the &#8220;hgetall&#8221; method with the single parameter &#8220;cert:123&#8243;, and it&#8217;ll return a populated hash with some certificate information (its status, revocation time, and revocation reason). We then verify that the status should be REVOKED, and that the revocation<em>time and revocation</em>reason are correctly translated to integers.</p>

<p>Now, so far we&#8217;ve only seen expectations where the method should receive only one parameter. Expecting multiple parameters is exactly what you&#8217;d expect: just pass multiple parameters to should_receive. Here&#8217;s an example of a spec for the R509::Validity::Redis::Writer class, where our test double will expect to receive multiple parameters:</p>

<pre><code>it "when reason isn't provided" do
    redis = double("redis")
    writer = R509::Validity::Redis::Writer.new(redis)
    redis.should_receive(:hmset).with("cert:123", "status", 1, "revocation_time", Time.now.to_i, "revocation_reason", 0)
    writer.revoke(123)
end
</code></pre>

<p>Here, our test double should receive the &#8220;hmset&#8221; method, with a slew of parameters (obviously, it maintains the type and order of the parameters, in addition to their values). Note also that we don&#8217;t specify any &#8220;and_return&#8221; here, since we don&#8217;t care about the return value from this method call.</p>

<p>Hopefully that helps to explain rspec mocks, in the interest of getting you to make them yourself. It beats the hell out of having a database running for your unit tests to work.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/5UvQpJ66jTk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2011/12/13/mocking-unit-tests-in-ruby-with-rspec-2-and-test-doubles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2011/12/13/mocking-unit-tests-in-ruby-with-rspec-2-and-test-doubles/</feedburner:origLink></item>
		<item>
		<title>Local Time Calculator for Java (Android)</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/tXXmzgBaJho/</link>
		<comments>http://vikinghammer.com/2011/11/30/local-time-calculator-for-java-android/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 21:20:13 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=194</guid>
		<description><![CDATA[Have you ever noticed that both MLB and NFL only give the starting times of their games in Eastern time? Through their websites, and even through their mobile apps &#8212; which I find especially egregious since your phone knows what timezone it&#8217;s in. One of the big features, in my opinion, that my MLB Scoreboard [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever noticed that both MLB and NFL only give the starting times of their games in Eastern time? Through their websites, and even through their mobile apps &#8212; which I find especially egregious since your phone knows what timezone it&#8217;s in.</p>

<p>One of the big features, in my opinion, that my <a href="https://market.android.com/details?id=com.vikinghammer.mlb.scoreboard.full">MLB Scoreboard</a> app has over MLB&#8217;s official apps (or any other third party scoreboard apps that I know of) is that it converts the given Eastern times into your local time. I&#8217;ve just started using that same code in my new <a href="https://market.android.com/details?id=com.vikinghammer.nfl.scoreboard.free">NFL Scoreboard</a> app (which I&#8217;ve decided to make <a href="https://github.com/sirsean/NFL-Scoreboard">open source</a>, for some reason).</p>

<p>I want to be able to use this essentially like so:</p>

<pre><code>LocalTimeCalculator calculator = new LocalTimeCalculator("12:30", "PM");
// if I'm in Central time (which I am), this will yield 11:30 AM
Date localTime = calculator.getLocalTime().getTime();
</code></pre>

<p>I want it to return a Calendar instead of a Date so I can easily set the date (year/month/day) if I want to; I do that sometimes, but I didn&#8217;t feel that it should be part of the local time calculation.</p>

<p>So here&#8217;s my <a href="https://github.com/sirsean/NFL-Scoreboard/blob/master/src/com/vikinghammer/nfl/scoreboard/date/LocalTimeCalculator.java">LocalTimeCalculator</a>:</p>

<pre><code>public class LocalTimeCalculator {

    private String mTime;
    private String mAmpm;

    public LocalTimeCalculator(String time, String ampm) {
        mTime = time;
        mAmpm = ampm;
    }

    public Calendar getLocalTime() {
        String[] timeArray = mTime.split(":");
        int hour = Integer.parseInt(timeArray[0]);
        int minute = Integer.parseInt(timeArray[1]);

        hour = convertToHourOfDay(hour, mAmpm);

        Calendar eastern = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
        eastern.set(Calendar.HOUR_OF_DAY, hour);
        eastern.set(Calendar.MINUTE, minute);

        Calendar local = Calendar.getInstance();
        local.setTimeInMillis(eastern.getTimeInMillis());

        return local;
    }

    private int convertToHourOfDay(int hour, String ampm) {
        if ("AM".equalsIgnoreCase(ampm)) {
            if (hour == 12) {
                return 0;
            } else {
                return hour;
            }
        } else {
            if (hour == 12) {
                return 12;
            } else {
                return hour + 12;
            }
        }
    }
}
</code></pre>

<p>First, I split the &#8220;12:30&#8243; time into hour and minute, and then convert the hour to 24-hour time based on the AM/PM field. Then I get a Calendar instance set to Eastern time (&#8220;America/New_York&#8221;), and set its time. I get a new Calendar instance, which will default to local time,* and set the time on it based on the original Eastern Calendar.</p>

<p><em>* On my Android phone, this updated as soon as I changed to a different timezone. It was working fine for me for the first few months of the MLB season before I finally went somewhere else (my trip to Las Vegas for DEFCON) and got to test that it was working in a timezone other than Central. Exactly what I was hoping for.</em></p>

<p>I don&#8217;t know if local time conversion was a big reason anybody wanted to use MLB Scoreboard or NFL Scoreboard rather than the official apps, but I do think it&#8217;s the kind of thing all apps should do. Your phone knows what timezone it&#8217;s in; you shouldn&#8217;t have to keep translating times in your head.</p>

<p>It&#8217;s not complicated, and it makes things better for your users. If you&#8217;re making Android apps, I think you should be doing this.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/tXXmzgBaJho" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2011/11/30/local-time-calculator-for-java-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2011/11/30/local-time-calculator-for-java-android/</feedburner:origLink></item>
		<item>
		<title>Android ListView: Maintain your scroll position when you refresh</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/Ibs7jA8cJRg/</link>
		<comments>http://vikinghammer.com/2011/06/17/android-listview-maintain-your-scroll-position-when-you-refresh/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 13:42:52 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=191</guid>
		<description><![CDATA[Refreshing an Android ListView is a pretty common thing &#8212; but the best way to do it isn&#8217;t immediately obvious. Here&#8217;s my progress through the different patterns. The Obvious I figured that when I&#8217;ve downloaded the new list of stuff I want to show, that I could just create a new adapter and stuff it [...]]]></description>
			<content:encoded><![CDATA[<p>Refreshing an Android ListView is a pretty common thing &#8212; but the best way to do it isn&#8217;t immediately obvious. Here&#8217;s my progress through the different patterns.</p>

<h2>The Obvious</h2>

<p>I figured that when I&#8217;ve downloaded the new list of stuff I want to show, that I could just create a new adapter and stuff it into the list.</p>

<pre><code>EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
mEventListView.setAdapter(eventLogAdapter);
</code></pre>

<p>This works, in that the list gets updated. But it always scrolls all the way back up to the top. Sometimes that might be what you want, but most of the time you&#8217;ll want to maintain your scroll position.</p>

<h2>The Naive</h2>

<p>I tried getting pixel-level scroll position using getScrollY(), but it always returned 0. I don&#8217;t know what it&#8217;s supposed to do. I ended up going with a solution that got <em>close</em> to maintaining your scroll position.</p>

<pre><code>int firstPosition = mEventListView.getFirstVisiblePosition();
EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
mEventListView.setAdapter(eventLogAdapter);
mEventListView.setSelection(firstPosition);
</code></pre>

<p>This figures out the first item in the list you can see before resetting the adapter, and then scrolls you to it. This maintains your scroll position <em>within some unknown/arbitrary range</em>, and can cause you to jump around in the list a little bit when you refresh.</p>

<p>If you&#8217;re scrolled halfway through a list item, it&#8217;ll snap you to the top of it so it&#8217;s completely visible. Unfortunately, if you&#8217;re scrolled halfway through a list item, that probably wasn&#8217;t the one you were paying the closest attention to.</p>

<h2>The Elegant</h2>

<p>There had to be a better way!</p>

<p>And, of course, there is. Romain Guy, an Android developer who haunts Stack Overflow and Google Groups dropping golden hints when people ask questions, <a href="http://groups.google.com/group/android-developers/browse_thread/thread/2e425f0cca0c0e8b?pli=1">pointed out</a>:</p>

<blockquote>
  <p>The problem is that you are creating a new adapter every time you reload the data. That&#8217;s not how you should use ListView and its adapter. Instead of setting a new adapter (which causes ListView to reset its state), simply update the content of the adapter already set on the ListView. And the selection/scroll position will be saved for you. </p>
</blockquote>

<p>There are two problems with Romain Guy: 1) he doesn&#8217;t have a central repository of these hints/answers so I can learn what to do before doing everything wrong first, and 2) they really are just <em>hints</em>, in that they point you in the right direction without getting you all the way there.</p>

<p>In this case, yes, updating the adapter without creating a new one every time <em>will</em> maintain your scroll position. Except that you&#8217;ll frequently get an &#8220;IllegalStateException: The content of the adapter has changed but ListView  did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.&#8221;</p>

<p>It turns out that you need to call notifyDataSetChanged() on your adapter after changing its contents; fortunately, that &#8220;only from the UI thread&#8221; bit was a red herring, because I didn&#8217;t really want to do any processing that could/should be asynchronous on the UI thread.</p>

<p>I added a refill() method to my adapters:</p>

<pre><code>public void refill(List&lt;EventLog&gt; events) {
    mEvents.clear();
    mEvents.addAll(events);
    notifyDataSetChanged();
}
</code></pre>

<p>And I call it when my download is complete:</p>

<pre><code>if (mEventListView.getAdapter() == null) {
    EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
    mEventListView.setAdapter(eventLogAdapter);
} else {
    ((EventLogAdapter)mEventListView.getAdapter()).refill(events);
}
</code></pre>

<p>If the list doesn&#8217;t already have an adapter, then I create one. But if it <em>does</em> have an adapter, then I just refill it. And it maintains my scroll position exactly!</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/Ibs7jA8cJRg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2011/06/17/android-listview-maintain-your-scroll-position-when-you-refresh/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2011/06/17/android-listview-maintain-your-scroll-position-when-you-refresh/</feedburner:origLink></item>
		<item>
		<title>Simplified DAO helper for using JDO with Google Appengine</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/8R2SAW2zePQ/</link>
		<comments>http://vikinghammer.com/2011/02/09/simplified-dao-helper-for-using-jdo-with-google-appengine/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 19:56:27 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Appengine]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JDO]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=189</guid>
		<description><![CDATA[I&#8217;ve been playing with Appengine for Java lately, and using JDO (which stands for Java Data Objects) for the first time. All the example code is pretty annoying; apparently, in every DAO method, you have to grab a PersistenceManager from the PersistenceManager factory, use it to build and execute a Query, and then close the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing with Appengine for Java lately, and using JDO (which stands for Java Data Objects) for the first time. All the example code is pretty annoying; apparently, in every DAO method, you have to grab a PersistenceManager from the PersistenceManager factory, use it to build and execute a Query, and then close the PersistenceManager before you return. The framework that has to be included in every method looks like this:</p>

<pre><code>PersistenceManager pm = pmFactory.getPersistenceManager();
try {
    // do something with the pm here
} finally {
    pm.close();
}
</code></pre>

<p>So that&#8217;s five lines of crap, in every method. But the only thing that actually matters, that I actually want to write in my DAO methods, is the meaty part, the part that says &#8220;do something&#8221; in that comment there. So, I wrote a little library to let me do just that: it&#8217;s my <a href="https://github.com/sirsean/vh-dao">vh-dao</a> project at Github.</p>

<p>It starts with a DAO interface, which says that every DAO class has a store method; I&#8217;ve been on too many projects where sometimes that method is called &#8220;store&#8221; and sometimes it&#8217;s &#8220;save&#8221; and sometimes it&#8217;s &#8220;storeWidget&#8221; or &#8220;saveWidget&#8221; (where &#8220;Widget&#8221; is the name of the model class). Enough.</p>

<pre><code>public interface VHDao&lt;T&gt; {
    public void store(T model);
}
</code></pre>

<p>Then, I have an abstract base class that implements a few things that&#8217;ll be the same for every DAO; including that store method, so when you create a new DAO you never have to worry about that.</p>

<pre><code>public abstract class BaseVHDao&lt;T&gt; implements VHDao&lt;T&gt; {

    @Autowired
    protected PersistenceManagerFactory pmFactory;

    @Override
    public void store(T model) {
        PersistenceManager pm = pmFactory.getPersistenceManager();
        try {
            pm.makePersistent(model);
        } finally {
            pm.close();
        }
    }

    protected List&lt;T&gt; list(VHQuery vhQuery, Object... args) {
        PersistenceManager pm = pmFactory.getPersistenceManager();
        try {
            Query query = pm.newQuery(vhQuery.getClazz());
            if (vhQuery.hasFilter()) {
                query.setFilter(vhQuery.getFilter());
            }
            if (vhQuery.hasOrdering()) {
                query.setOrdering(vhQuery.getOrdering());
            }
            if (vhQuery.hasRange()) {
                query.setRange(vhQuery.getRangeStart(), vhQuery.getRangeEnd());
            }
            List&lt;T&gt; list = (List&lt;T&gt;)query.executeWithArray(args);
            list.size();
            return list;
        } finally {
            pm.close();
        }
    }

    protected T first(VHQuery vhQuery, Object... args) {
        PersistenceManager pm = pmFactory.getPersistenceManager();
        try {
            Query query = pm.newQuery(vhQuery.getClazz());
            if (vhQuery.hasFilter()) {
                query.setFilter(vhQuery.getFilter());
            }
            if (vhQuery.hasOrdering()) {
                query.setOrdering(vhQuery.getOrdering());
            }
            query.setRange(0, 1);
            List&lt;T&gt; list = (List&lt;T&gt;)query.executeWithArray(args);
            if (list.size() &gt; 0) {
                return list.get(0);
            } else {
                return null;
            }
        } finally {
            pm.close();
        }
    }

}
</code></pre>

<p>As you can see, there are two methods that we can use in the subclass: list() and first(). They get a PersistenceManager, set up a Query based on the VHQuery you pass in, execute the Query based on all the (optional) parameters you give, and then close the PersistenceManager.</p>

<p>That VHQuery object is there to define the filter/ordering/range that I need to enter into the actual JDO Query object; its reason for being is twofold:</p>

<ul>
<li>The JDO Query object is created by calling the PersistenceManager, which I won&#8217;t have access to in the DAO subclass since I want to instantiate it in the base methods</li>
<li>Prevent a leaky abstraction of requiring the subclass to know about the JDO Query object</li>
</ul>

<p>I originally had a method that built and returned the Query object that I could then fill in and execute, but I couldn&#8217;t close the PersistenceManager after executing it, which would have led to annoying memory leaks. This seems nicer.</p>

<p>Here&#8217;s what a method looks like that just wants to grab a single item from the database:</p>

<pre><code>public Greeting getLatestByAuthor(User author) {
    VHQuery query = new VHQuery(Greeting.class);
    query.setFilter("author == :author");
    query.setOrdering("date desc");
    return first(query, author);
}
</code></pre>

<p>It just sets up the VHQuery and asks the base class to give it the first result that matches the given query parameters.</p>

<p>And here&#8217;s one that returns a list:</p>

<pre><code>public List&lt;Greeting&gt; mostRecent(int count) {
    VHQuery query = new VHQuery(Greeting.class);
    query.setOrdering("date desc");
    query.setRange(0, count);
    return list(query);
}
</code></pre>

<p>As you can see, your DAO methods now have no extraneous lines that don&#8217;t have anything to do with the query you&#8217;re trying to execute. That&#8217;s all handled generically for you, and you don&#8217;t have to worry about it.</p>

<p><strong>Note</strong>: I&#8217;ve written this so I can use it with the Appengine datastore, and haven&#8217;t tried it with an SQL database. JDO is supposed to work just fine with an RDBMS, so this will probably help. I guess I&#8217;ll find out when I get around to that.</p>

<p>I&#8217;m guessing there was already something that does this, because I can&#8217;t imagine that everyone using JDO is okay with typing all that boilerplate in every method; I couldn&#8217;t find it, though, and am open to someone pointing me in the right direction. I&#8217;m also sure there will be more additions to this DAO abstraction as I find needs &#8212; what do you think I&#8217;ve missed?</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/8R2SAW2zePQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2011/02/09/simplified-dao-helper-for-using-jdo-with-google-appengine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2011/02/09/simplified-dao-helper-for-using-jdo-with-google-appengine/</feedburner:origLink></item>
		<item>
		<title>Using Ruby’s extend and include to inject functionality into Sequel model classes</title>
		<link>http://feedproxy.google.com/~r/VikingHammer/~3/DlXbHQ59_8Q/</link>
		<comments>http://vikinghammer.com/2011/02/02/using-rubys-extend-and-include-to-inject-functionality-into-sequel-model-classes/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 22:17:13 +0000</pubDate>
		<dc:creator>sirsean</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Sequel]]></category>

		<guid isPermaLink="false">http://vikinghammer.com/?p=186</guid>
		<description><![CDATA[I was writing a program that needed to delete some items out of several different tables &#8212; but we want to be safe and keep a record of what was deleted, in case we need to put it back in. Since we&#8217;re guessing we won&#8217;t find out what the problems will be, if any, until [...]]]></description>
			<content:encoded><![CDATA[<p>I was writing a program that needed to delete some items out of several different tables &#8212; but we want to be safe and keep a record of what was deleted, in case we need to put it back in. Since we&#8217;re guessing we won&#8217;t find out what the problems will be, if any, until a lot of new data has been inserted into the database, simply dumping the database and reverting to a backup isn&#8217;t going to be an adequate solution.</p>

<p>I&#8217;m using Ruby here, along with the awesome Sequel ORM library.</p>

<p>My idea is that whenever a record is deleted from our database, I want to create an identical record in a &#8220;slum&#8221; database. These slums won&#8217;t be used for anything, hopefully, but if we need to use them they&#8217;ll have everything &#8212; including the id&#8217;s &#8212; that we deleted.</p>

<p>At first, my models each had methods that supported this &#8230; and it got pretty cumbersome. Then I remembered, &#8220;hey wait a minute, this is Ruby, and I can probably do something awesome!&#8221;</p>

<p>Indeed, you can do awesome things.</p>

<p>First, I created a &#8220;SlumBuilder&#8221; module that adds a class method called &#8220;build&#8221; to all the classes that <strong>extend</strong> it. In Ruby, when you <strong>extend</strong> a module its classes are included as class methods, and when you <strong>include</strong> a module its classes are included as instance methods. That&#8217;s an important distinction, because we&#8217;ll be doing both.</p>

<p>Here&#8217;s SlumBuilder:</p>

<pre><code>module SlumBuilder
    def build(original)
        object = self.new
        original.keys.each do |field|
            object[field] = original[field]
        end
        object.save
    end
end
</code></pre>

<p>As you can see, it instantiates a new object of whatever type has extended SlumBuilder, and fills it with all the fields (keys) in the given model object (original).</p>

<p>A Slum model object might look like this:</p>

<pre><code>class SlumCoolThing &lt; Sequel::Model(:cool_thing)
    extend SlumBuilder
    self.db = $slum_db
end
</code></pre>

<p>That&#8217;s it. It gets the available fields from the database (thank you Sequel!) and all its functionality from SlumBuilder. We just need to set the database it uses, since we&#8217;re using two different databases.</p>

<p>The regular model object, the one we&#8217;ll need to delete some records out of, would look like this:</p>

<pre><code>class CoolThing &lt; Sequel::Model(:cool_thing)
    include ModelDestroyer
    self.db = $regular_db
end
</code></pre>

<p>Simple enough. As you can see, I went with the convention that the slum&#8217;s model class is the same as the regular model&#8217;s class with &#8220;Slum&#8221; prepended. This is important, as you&#8217;ll see here in ModelDestroyer:</p>

<pre><code>module ModelDestroyer
    def slum_class
        Object::const_get("Slum#{self.class}")
    end

    def destroy
        begin
            self.slum_class.build(self)
        rescue
            # failed to build a slum, probably because the class doesn't exist, but we'll just continue on with the deletion
            puts "Failed to build slum: #{self.inspect}"
        end
        self.delete
    end
end
</code></pre>

<p>This is where most of the magic happens. The &#8220;slum_class&#8221; method uses Ruby&#8217;s cool &#8220;get the constant, like a class, that has the given name&#8221; functionality to get the class that has the same name as whichever one has included our ModelDestroyer with &#8220;Slum&#8221; prepended.</p>

<p>Our &#8220;destroy&#8221; method gets that Slum class and calls its &#8220;build&#8221; class method, discussed above, that copies all the fields and saves a new record to the slum database. It then calls Sequel&#8217;s &#8220;delete&#8221; method to remove the record from our database.</p>

<p>So if we had a variable, cool_thing, that we pulled out of the CoolThing database and we wanted to delete it, we now have two options:</p>

<pre><code>cool_thing.delete
</code></pre>

<p>Which just removes cool_thing from the database. The other option is:</p>

<pre><code>cool_thing.destroy
</code></pre>

<p>Which removes cool_thing from the database <strong>AND</strong> inserts a perfect copy of it into a separate slum database.</p>

<hr />

<p>You&#8217;re probably not going to need to do exactly this, with inserting duplicate copies of a row upon deletion. But being able to inject functionality like SlumBuilder and ModelDestroyer into a class is really cool &#8212; we couldn&#8217;t use inheritance for this, because our model classes already inherit from Sequel::Model.</p>

<p>It&#8217;s bending my mind right now to think about how I&#8217;d do this in Java. I think it might be a bit more verbose &#8230; if it&#8217;s even possible.</p>
<img src="http://feeds.feedburner.com/~r/VikingHammer/~4/DlXbHQ59_8Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://vikinghammer.com/2011/02/02/using-rubys-extend-and-include-to-inject-functionality-into-sequel-model-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://vikinghammer.com/2011/02/02/using-rubys-extend-and-include-to-inject-functionality-into-sequel-model-classes/</feedburner:origLink></item>
	</channel>
</rss>

