Friday, July 17, 2009
Hibernate-memcached 1.2 Released
The 1.2 release updates the Maven dependencies to spymemcached 2.3.1, which includes some bug fixes and reduces the dependencies by one jar (spy.jar is gone). The main purpose of the hibernate-memcached release is to add support for the new binary protocol released with memcached 1.4. Previous versions of memcached only supported the ascii protocol. This has always performed well in it's own right; but the binary protocol reduces CPU compute time and can decrease response time as well.
The hibernate-memcached release also includes a minor tweak to use getMulti in Memcached when DogpilePrevention is enabled. Not a big deal, but someone pointed out an opportunity for it; so I added it.
You can download hibernate-memcached here. Or you can setup your maven project by following these instructions. As always, the source is available via github.
Enjoy!
-Ray Krueger
Sunday, May 17, 2009
Rails Authentication: restful_authentication vs. authlogic
The Restful authentication library is the current popular choice. I believe this is due to it being one of the first real options, as well as coverage in books like "Advanced Rails Recipes". The library is incredibly complex and opaque though. It relies heavily on generators and hidden code to produce its functionality. The install instructions are an exercise in command line arguments rather than code.
Authlogic has proven to be far simpler to digest. No real magic involved. One of the stated goals of the library is to be able to treat sessions as you would an active record model. You create a session, save a session and destroy a session like you would any other model. There are no generators you write the code yourself, and there is very little of it. The basic set of columns you need for a "User" show you that the library is well thought out with regards to security and usefulness. There are a number of columns though and this leads to a heavy initial copy & paste though. I felt a bit dirty having to do that, but I'll get over it. The rest of the code I have to write is transparent and understandable, a big plus. Oh, and do not assume that because "restful" isn't in the title that it lacks there. It doesn't, follow the tutorial and you'll produce a very restful solution.
You can probably tell from the above two paragraphs that I'm favoring Authlogic at this point. I definitely like the transparency and simplicity of it. To learn more about Authlogic you can follow along with the README in the main repository as well as the fantastic tutorial app. There are also a few extra tutorials on Ben Johnson's blog around password resets and openId.
Thursday, April 16, 2009
Follow up to the AbstractHibernateDao
If you do want your DAOs to throw Spring DataAccessExceptions there are two simple things to do.
- Add the @Repository annotation to your DAO impl.
- Add a PersistenceExceptionTranslationPostProcessor bean to your Spring setup.
What this does is tell Spring to wrap an interceptor around your DAO bean that handles the exception translation.
Looking at the UserDaoImpl from the past article...
@Repository
public class UserDaoImpl extends AbstractHibernateDao<User> implements UserDao {
public UserDaoImpl(SessionFactory sessionFactory) {
super(User.class, sessionFactory);
}
...
}
Then in your Spring application context.xml you simply add one line...
Now, this pattern I present is somewhat old school. There is all this fancy component scanning stuff you can do with the Spring 2.5 XML namespaces. Honestly the amount of voodoo that goes on there freaks me out a bit. You can study that on your own if you'd like. A good place to start is here.
Thursday, April 02, 2009
Amazon Elastic MapReduce
Amazon Elastic MapReduce
Thursday, March 12, 2009
Announcing Tiny VH
Announcing Tiny VH
Friday, January 30, 2009
Announcing Fidgetr | >140 Characters
My friend Paul Kehrer over at the "> 140 Characters" blog has released his new WordPress plugin called Fidgetr. From his blog...
Fidgetr is a WordPress widget that displays the latest photos from your Flickr photostream in an attractive manner. It features support for its own themes along with very simple setup and good compatibility with various WordPress themes.
If you use WordPress and Flickr you should check it out.
Thursday, January 22, 2009
Thursday, December 18, 2008
Simple Maven Archetype
The problem I have with this (besides the menu being hideous) is that Maven still defaults the compiler to use source/target settings for java 1.4. Every project I do that uses Java 1.5 needs to have the compiler config settings tweaked to allow the use of 1.5. It is really annoying, so I created my own simple archetype that I can use and uploaded it to github for easy access. http://github.com/raykrueger/simple-archetype/tree/master
This new archetype generates an empty project with compiler settings for 1.5, includes the dev.java.net maven repository and has dependencies for slf4j and junit.
I may move this archetype project in the future into a collection of archetypes. So I can have a simple java one, a webapp one, and whatever else I come up with. If I do move them, I'll update this blog :)
Sunday, December 07, 2008
Hibernate-memcached 1.1.0 Released!
- Support for the Whalin memcached client
- New Key strategies: Md5KeyStrategy, Sha1KeyStrategy for reducing the length of keys
- Better Exception handling during cache failure scenarios
This is the first release after moving the source to github.
I need to do some wiki work to get documentation up for how to enable and configure the Whalin/Danga memcached client. I hope to get to that some time this week.
The new KeyStrategy implementations for Md5 and Sha1 are there to reduce the size of the keys. Raymond He emailed me to point out that the obnoxiously long keys that Hibernate generates take up a lot of memory in memcached. Many records + ~250 char keys = a lot of wasted space. The new Md5 and Sha1 keys strategies simply take the fully qualified key name generated by hibernate-memcached and hash them up to take a lot less space.
The improved exception handling revolves around the addition of a new MemcachedExceptionHandler interface and a default LoggingMemcacheExceptionHandler implementation. Essentially the Spy and Danga memcached clients are wrapped up to eat any exception that comes out of them. There's really no reason for the cache layer to throw exceptions at Hibernate. Errors are logged as Errors, and a null is returned.
Enjoy!
Saturday, November 22, 2008
Rails 2.2 Released!
What's most interesting, it almost only matters to JRuby users! For more information; have a look at Charles Oliver Nutter's post from a little while back: "Q/A: What Thread-safe Rails Means".
Friday, November 21, 2008
3 Reasons to Switch to Git from Subversion � markmcb
3 Reasons to Switch to Git from Subversion � markmcb
Friday, November 14, 2008
Grails 1.0.4 Released
SpringSource Team Blog: First Grails Release Under the SpringSource Banner
Tuesday, November 11, 2008
YouTube - Google Techtalk on Git
YouTube - Google Techtalk on Git
Graeme Rocher's Blog: Groovy and Grails join the Spring family
Graeme Rocher's Blog: Groovy and Grails join the Spring family
SpringSource Team Blog: More Weapons for the War on Complexity: SpringSource Acquires Groovy/Grails Leader
Wednesday, November 05, 2008
InfoQ: Writing JEE applications with Grails and Flex
InfoQ: Writing JEE applications with Grails and Flex
Sunday, October 19, 2008
O'Reilly Feeds Gone Wild
Fix it Tim(s)!
Wednesday, October 15, 2008
Yesterday's Post
Anyway, if you missed it, check out
"Using JRuby and ActiveRecord Migrations to Manage Database Change".
Thanks :)
Monday, October 13, 2008
Using JRuby and ActiveRecord Migrations to Manage Database Change
Managing change to your application databases is a very common requirement for any development team. The usual approach seems to consist of piling scripts into some "db/changes" folder in your project. This is probably fine for the most part, but when you have multiple databases in multiple environments, managing that across multiple developers can be a problem. If have the usual minimum of three environments (dev, test, prod) you have to remember to apply the right scripts in the right order in each environment. If you are doing iterative development you may be making small database tweaks here and there over a period of a week or two. The difficulty comes in trying to remember what script you applied last and which script you need to apply today.
Following our first instinct of storing sql scripts in source control, let's add another complication into the mix. What if you have to support multiple database engines, say MySQL and Postgres. There will be subtle differences in statements, and database specific properties that need to be set. Managing two sets of scripts becomes a huge pain pretty quickly. Now, as as Java developer, we get to use Hibernate to maintain database portability. Hibernate is a fantastic ORM library, and it comes with tools to generate the DDL needed to create your database from scratch. Unfortunately, it does not include any tools for managing incremental updates to that schema.
The Ruby on Rails folks came up with a solution to the issues above; ActiveRecord Migrations. Migrations are small, incrementally versioned Ruby classes that are designed to bring your database up to date in a controlled fashion. The basic concept is very simple. Store a "version" in the database and maintain a set of Ruby classes that can bring your database up to the latest version. The Ruby classes are numbered using the version they represent and include an "up" and "down" operation. So, let's say we have a current version in the database of "6" and Ruby classes numbered up through "10". When we execute the "migrate" command ActiveRecord will see the current version and see we have scripts that go beyond that and begin to execute their "up" methods in order 7.up, 8.up, 9.up, 10.up. If we wanted to bring our database down to version 8 ActiveRecord would in-turn run the "down" methods. Executing 10.down, 9.down; leaving us at version 8. ActiveRecord Migrations also address our second issue of portability. Your individual migration classes are written in a database agnostic "Domain Specific Language", which allows for the SQL to be generated at runtime for your specific database. Note that you can also execute arbitrary SQL if needed as well.
I intend to show how to do this from the perspective of a Java developer, deploying these changes into a Java deployment environment. This is where JRuby comes in. At my company we already have Java on all of our servers and development machines, but not Ruby (except maybe on dev boxes). Using JRuby allows us to run Ruby on top of the installed JVM without having to worry about installing Ruby. So, let's get crackin' here and do something.
Install JRuby
Download Jruby (1.1.4 as I write this) and extract it somewhere. For me I've dumped it in "~/dev/jruby-1.1.4". Set an environment variable called JRUBY_HOME that points to this location; EX: in .bash_profile: export JRUBY_HOME="~/dev/jruby-1.1.4". Add JRUBY_HOME/bin to your path and you're good to go; EX: in .bash_profile: export PATH=$PATH:$JRUBY_HOME/binInstall Required Gems
Ruby has a library distribution mechanism called ruby-gems. A gem is a library, every gem has a version and some dependencies. JRuby comes with ruby-gems pre-installed, all you need to do is tell it to install the other libraries you want. We'll need a few of them to get started. Note that I'm going to use mysql via jdbc in this example. You can use the native Ruby drivers for your database of choice, or one of the supported jdbc adapters.
- jruby -S gem install jruby-openssl (we won't use this, but JRuby will complain when installing gems without it)
- jruby -S gem install activerecord
- jruby -S gem install rake
- jruby -S gem install activerecord-jdbcmysql-adapter
Since we're using the jdbcmysql adapter we'll need to throw the mysql jdbc driver into our JRUBY_HOME/lib directory.
Configure the Project
Let's start by creating a directory structure to work with. Let's create a folder called "activerecord" with a subfolder named "db" and a subfolder inside "db" named "migrate". Executing "mkdir -p activerecord/db/migrate" will do the trick. In our "activerecord" folder create a file named "database.yml". The .yml file extension means this is a yaml file, Yaml stands for "YAML Ain't Markup Language"; cute right? We're not going to get into yaml much, suffice to say our use of it here is like a properties file. We'll stick to name/value pairs. Our "database.yaml" file will have the following contents...
adapter: jdbcNote that I am assuming mysql running on the localhost with a database called test. Adjust this file accordingly for whatever your database settings are.
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/test
username: root
password: whatever
Prepare Your Rakefile
Again, in our "activerecord" folder we're going to create a file named "Rakefile.rb". If you are familiar with Ant then you're familiar with the concept of Rake. Rake is the defacto build tool for Ruby and Rails applications. The Rakefile.rb file is equivalent to the Ant build.xml file, except that it's written in Ruby not XML. As a straight up copy and paste operation, your "Rakefile.rb" will have the following contents...
require "active_record"If you look at it this file you can see how it is similar to an Ant build.xml file. The "task" blocks (the block is denoted by the do/end) are like "targets" in Ant. Here we've got a task named "migrate" that depends on the "environment" task. The "environment" task sets up our database connection using our Yaml file, and configures a log file to write to. Our migrate task simply tells the ActiveRecord Migrator where the classes are and optionally a specific VERSION to move to. Specifying a version is commonly used for rolling back to some point in the past.
require "yaml"
task :default => :usage
task :usage do
print "Executing \"rake migrate\" will bring the databse up to date\n"
print "To upgrade/downgrade to a specific version use: \"rake migrate VERSION=X\"\n"
end
task :migrate => :configure do
ActiveRecord::Migrator.migrate("db/migrate", ENV["VERSION"] ? ENV["VERSION"].to_i : nil )
end
task :configure do
ActiveRecord::Base.establish_connection(YAML::load(File.open("database.yml")))
ActiveRecord::Base.logger = Logger.new(File.open('migrate.log', 'a'))
end
Write Your First Migration
I'll put together the migration classes necessary to build a "user" table, and a "messages" table, with a cross-reference table joining users to messages in a one-to-many relationship. I'll do this in small steps so we can see it as a serious of migration steps. Let's start right off with the User table. In the "db/migrate" folder create a file named "001_create_user_table.rb". The name of this file is important and significant. The first part represents our version, in this case "1". Everything after that is actually ruby standard class file naming. We're defining a class named "CreateUserTable", which therefore means it should be in a file named "create_user_table". Why the swich from camel to case to underscores? I haven't a clue...
class CreateUserTable < ActiveRecord::MigrationThe migration above is a Class that extends ActiveRecord Migration, it defines two instances methods named "up" and "down". The "up" method calls a method (on Migration) called create_table and passes it a block. When create_table executes the block it will pass it a "TableDefnition" instance, which we named "T". We then call the "string" method on the TableDefinition and pass it "symbols" stating the name and a map (the comma-delimited name/value pairs) containing the options for the column. The "down" method just calls the "drop_table" method. If I have to explain what that does, you're in way over your head :)
def self.up
create_table :user do |t|
t.string :username, :null => false, :limit => 15
t.string :fullname, :null => false, :limit => 30
end
end
def self.down
drop_table :user
end
end
OK, let's try it! Bring open a terminal to your "db" folder and run "jruby -S rake migrate". The "-S" I keep using tells Jruby to execute one of command from JRUBY_HOME/bin. If all goes well you should see the following output:
(in C:/source/activerecord)Once we've executed this migration we should be able to see our new table in mysql:
== 1 CreateUserTable: migrating ===============================================
-- create_table(:user)
-> 0.0031s
-> 0 rows
== 1 CreateUserTable: migrated (0.0036s) ======================================
mysql> show tables;The user table is our new table and the schema_migrations table was created by ActiveRecord to track the current version essentially. ActiveRecord actually keeps track of all the migrations applied to it as of ActiveRecord 2.0. If you see a schema_versions, table then you weren't following along very well as you have a really old version of ActiveRecord :)
+-------------------+
| Tables_in_test |
+-------------------+
| schema_migrations |
| user |
+-------------------+
Migrating the Rest of the Way
W'e're now going to push through our last migration; that message table I mentioned. First create file in "db/migrate" named "002_create_message_table.rb". That file will have the following:
class CreateMessageTable < ActiveRecord::MigrationThe new feature we're seeing here in the message table migration is the use of "t.references". Our create_table operation will always create an "id" column for us to represent the surrogate primary key for our table. In doing so ActiveRecord can follow some conventions here. Using "t.references" tells ActiveRecord to setup a foreign key to our user table id column. After that we tell ActiveRecord to create a text (clob) column named "message".
def self.up
create_table :message do |t|
t.references :user
t.text :message
end
end
def self.down
drop_table :message
end
end
We're ready to execute our next migration. Again, ActiveRecord will look at the versions on our scripts we have provided and compare that with the schema_migrations table to decide what needs executing. Once that decision is made it will walk through them in order...
Executing "jruby -S rake migrate" should give the following output...
(in C:/source/dbupdate/activerecord)Now let's have a look at what's in mysql...
== 2 CreateMessageTable: migrating ============================================
-- create_table(:message)
-> 0.0061s
-> 0 rows
== 2 CreateMessageTable: migrated (0.0085s) ===================================
mysql> show tables;We should also see that our schema has been migrated up to version 2 by looking at our schema_migrations table...
+-------------------+
| Tables_in_test |
+-------------------+
| message |
| schema_migrations |
| user |
+-------------------+
mysql> select * from schema_migrations;
+---------+
| version |
+---------+
| 1 |
| 2 |
+---------+
2 rows in set (0.00 sec)
Downgrading
Our Rakefile.rb was looking for a VERSION parameter to read from to force our migration to go to a specific version. Generally speaking you use that to downgrade to a prior version for whatever reason. Let's try that now, execute the "jruby -S rake migrate VERSION=1" command to tell ActiveRecord to step us back to version 1. You should get the following...
== 2 CreateMessageTable: reverting ============================================
-- drop_table(:message)
-> 0.0044s
-> 0 rows
== 2 CreateMessageTable: reverted (0.0067s) ===================================
As you might have guessed ActiveRecord executed our CreateMessageTable.down method, at which point we executed the drop_table method to undo that version. And, again, if we look at the "schema_migrations" table we'll see that it too has been stepped down to version 1.
mysql> select * from schema_migrations;
+---------+
| version |
+---------+
| 1 |
+---------+
1 row in set (0.00 sec)
The Right Tool for the Job
By trade, I am a Java guy. I dabble in Groovy and Ruby and fun stuff like that, but still, I'm paid to be a Java guy. Sometimes you have to know when to use the right tool for the job. Even if you're not familiar with Ruby you really don't need to think of it that way. Ruby is used to provide you with the domain specific language used to handle portable database migrations. You don't need to concern yourself with learning the full extent of the Ruby libraries, or all of the fancy dynamic language features. You just need to pay attention to what values you're passing to these methods and in some cases (maps/hashes) their funky syntax. Honestly I've been looking at doing an article like this for a long time. I'm glad I finally sat down and right it. Hopefully this helps some folks see the power in stepping out from behind our Java comfort zone.
References
- http://rails.aizatto.com/2007/05/27/activerecord-migrations-without-rails/
- http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
- http://www.scribd.com/doc/1083725/Migrations-in-Rails-20