Archive for the 'Programming' Category

Calling All EJBs — From Ruby?

After installing and playing with JRuby a few days ago, I started wondering if it would be possible to access an EJB from a JRuby script. After all, the Java code to call an EJB is purely client code, only communicating with an application server over an HTTP-like protocol (HTTP-like in BEA’s case, anyway). At my current project, the OptimalJ team generates all their domain code and delivers business services around that in the form of session EJBs to us, the web frontend team. We’re using BEA WebLogic Portal to code the frontend. Now if we’d have EJB access from JRuby, and Rails on JRuby (which seems to be only a matter of time), I guess we would be able to build a frontend like this in Rails. There’s just the tiny matter of convincing the company’s enterprise architect, who’s already sick of hearing me talk about Ruby and Rails.

Anyway, to the code! To my surprise (after 6 years of experience with EJBs, anything EJB-related working instantly comes as a great surprise) it was just a matter of JRubyfying the Java code that you would write to use an EJB. It just works, there’s nothing more to it. Here’s an example of the magic code:

require 'java'
 
include_class 'java.util.Properties'
include_class 'javax.naming.Context'
include_class 'javax.naming.InitialContext'
 
properties = Properties.new
properties.put(Context::INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory")
properties.put(Context::PROVIDER_URL, "t3://localhost:7001")
context = InitialContext.new(properties)
home = context.lookup("business-ejb-jndi-name")
business_ejb = home.create
result = business_ejb.someBusinessMethod(parameters)

Okay, here’s some small print. The example works on a BEA WebLogic application server. For another JEE application server you’ll need to fill in the correct InitialContextFactory class name. Fill in the JNDI name for the EJB after the lookup call. Also, before running the script, you’ll have to put the right libraries in the CLASSPATH environment variable. For example, for the BEA server I had to include weblogic.jar and the EJB client jar containing the home interface to the EJB. But once you’ve figured that out, it should work; I got it to work on JBoss as well as BEA. Consult your local Java guru if necessary.

I’ve put all this in a JRuby module (to be downloaded here), which enables you to write just this to call your favourite EJB:

require 'rejb'
business_ejb = Rejb::ejb("business-ejb-jndi-name")
result = business_ejb.someBusinessMethod(parameters)

I’ve been feeling very happy over the last few days, even though there’s no Spring in sight. Must be the summer of Ruby that’s coming…

2006-04-13. 4 responses.

Rails Team Ends Second In Dutch Development Contest

In Holland we have a yearly development contest called “Development Tools” (formerly RAD Race). In two days, several teams consisting of two coders build an administrative application according to fixed requirements, with database access, forms, reports, the works. The contest was originally organized for 4GL RAD tools, but in recent years Java teams have entered the competition. Without too much success though, for no Java team has up till now managed to beat the 4GL tools. This year, for the first time, a Rails team joined up. And not just any Rails team; my co-bloggers from “rubyenrails.nl“, Remco van ‘t Veer and Michiel de Mare were in it. Today the results from the contest were published, and guess what — Remco and Michiel came in second! They beat all the Java teams; first place was for the CrossmarX Application Engine. Congratulations to Remco and Michiel, and to Rails of course!!

2006-03-29. One response.

How Java is Ruby?

Following up on my recent post on Ruby and Rails’ enterprise-readiness, we might want to rethink any strategies comparing or opposing Ruby with Java. Don’t get me wrong: Ruby is a breeze where Java is a mouldy draught; Ruby is a butterfly where Java is an ostrich; Ruby makes you smile where Java is often a maniacal grin. But also they’re both gusts of air, both have wings, both evoke emotion. Both are object oriented languages, both have classes, and methods, and instance variables, and structured in-code documentation, and closures (more or less), both are pass-by-reference-by-value, both have apis for Lists and Maps and Files and Regexps… The list goes on and on.

Most Java coders that are first introduced to Ruby recognize a lot of things; and what they don’t know, still feels like what they’ve always wanted. There is the new syntax to learn, and so many new apis, and Ruby’s coding standards differ from Java’s — but let’s not overreact. If you’re a good Java (or otherwise OO) programmer, you will easily pick up Ruby.

All this goes to say that the introduction of Ruby and Rails in the (Java-oriented) enterprise must not be hindered by arguments like “We have already invested so much in Java, we don’t want that to go to waste.” If you have invested in a Java infrastructure, in Java-skilled developers, you have already invested in Ruby and Rails. You have (hopefully) trained your developers to understand object orientation, as well as things like MVC architecture, test-driven development, standards-based programming. Java is but a tool — or at least it should be. Ruby just builds on that.

The same goes for the Java-based infrastructure. Investments there aren’t wasted either. The time will come, sooner rather than later, when Ruby and Rails will neatly run inside a JEE application server. We will be able (if we aren’t already) to develop web frontends in Rails, talking to JEE business components, message queues, connectors, web services, data sources and what not. We will be freed from the restraints that Java forces upon frontend developers, with its xml and pojos and faces and struts.

Let Ruby and Java blossom in the enterprise — together like a daisy and a rambler rose!

2006-03-28. 3 responses.

Ruby and Rails Get Enterprise-Ready

In the recent, rather entertaining discussion between James McGovern and the rest of the world, about Ruby and Rails being enterprise-ready or not, a lot of emphasis was placed on the speed of development that Ruby and Rails may offer. Anne Zelenka correctly stated that speed of development isn’t all that important in an enterprise environment.

In a way it is sad, but big enterprises, large corporations, might not care much whether an application could be developed with Rails in half the time it would take with Java. Development (I’m including design here) is only a small piece of the entire implementation of an application. There’s functional testing to be done, training of end-users as well as support staff, setting up and maintaining the technical infrastructure for development, test, acceptance and production environments, data conversion, and overhead costs like project management, meetings, planning, the works. Things you can happily do without (more or less) if you’re a web startup, but not so for your average enterprise. (I’m not saying an enterprise couldn’t cut back on them, but most just don’t or won’t — it seems to be a given when you’re entering the enterprise world). And then of course there is application maintenance. Long ago I learned that, as a rule of thumb, application maintenance costs 20% of application development — yearly. That’s 20% of the costs of design, development and testing. Which means that, if you keep developing new applications, your yearly planning slowly fills up with maintenance work.

Instead of just focussing on the amount of development time you might save on, why not focus more on the reasons why development time can be saved on? For example, one of the reasons developing in Rails is so much faster, is the principle of ‘convention over configuration’. I think that might hold some attraction, as it is something that many enterprises are already trying to achieve, for instance with software factories: standards based coding. As a by-product of this, you need less code for your application, which also means less code to maintain. Another example is the shorter build cycle (at my current Java project, the “record” for longest build time stands at 1.2Ms). And how about prototyping? You might actually sit down with an end user and prototype view, model and controller in a Rails application. I’ve never seen that done properly in a Java environment. Prototyping often results in better user acceptance. Or test driven development, which in Rails is not an afterthought as it is in Java. TDD can prevent many unnecessary bugs, so also means less maintenance. (At the moment I am on a project where unit tests “are not needed because all code is generated with OptimalJ.” Yeah right.)

If Ruby and Rails can solve problems that enterprises currently have in their development environment, and save time and money in the process, they could become more interesting for bigger companies.
Of course, there are also reasons why enterprises may not want to use Ruby and Rails — but that’s for another post. Or maybe I should leave that to James McGovern.

Disclaimer: I am neither an enterprise architect, nor a thought leader on that subject. My opinions are based on my work for Dutch enterprises, which may not be comparable to U.S. enterprises. And I’m talking primarily about developing web applications, where Rails excels.

2006-03-27. 8 responses.

Can You XML a DSL, And Would You Want To?

For me, one of the principles of programming has always been: “Use the programming language best suited for the job; and if there is none, create a new language.” I believe this is directly related to the idea of Domain Specific Languages (DSL) that are all the rage right now. Creating a new language that is best suited for a specific problem domain: that really says it all, doesn’t it? Still, it’s a quote that I first heard when I started my programming career, which was about twenty years ago — and it may very well be even older than that. How did people go about creating a language back then? (I mean parsing and compiling or interpreting it, not designing the language.) And how do we do it today? Has anyone ever asked the questions:

  • “What programming language is best suited for implementing another (DS) language?”
  • “At what point will creating and maintaining a new (DS) language result in less work than using a second-best language for solving the problem?”
  • “Can we describe a new language that is meant specifically for creating DSLs, a meta-DSL?”

I was led to these questions after reading a post by Obie Fernandez on his blog. He describes how his team created a DSL that describes a data model. Depending on its context, the DSL code will either create a table creation script, a script for creating stored procedures, or XHTML code for display in a browser. His description is not all too elaborate, I must say, so maybe I’m missing some interesting feature here. But it sounded to me like nothing more than doing some data transformations. Wouldn’t XML and some XSLT scripts have done the job here? Also, if you create a DSL for this, you have the added disadvantage that you’ll have to maintain the DSL implementation as well (even if the DSL is easy to write in Ruby). Three DSL implementations even, one for each context you can use. The idea of contexts is nice, until you need to implement an extra feature in one context that will conflict with the others. Unfortunately, Obie never got round to answer this question that I put in my comment on his blog post.

I believe a lot of XML code written out there could actually be called a DSL in its own right. Someone wrote the other day (in one of the 40,000 blogs I try to read now and then) that XML is Java’s tool for creating DSLs; and I agree to some point. To some point. I mean, I write XML every day (in the form of JSPs), so by now I’m used to writing conditional statements and loops in the form of XML tags, but it’s hardly elegant if you think of it. It’s actually plain ugly. (And if you think that’s not ugly enough, go take a look at the next step in XML programming: Jelly, executable XML. Yuck!)

Mixing data and code is (in principle) a bad thing, I think; whether you start of with data and mix in code (like in XML) or you start with creating a DSL and add in data (like in Obie’s example). I would prefer to to put the data in XML (or Yaml, or a database, or some other form of structured data) and keep the code separate. This will also give you better insight whether you’ll need to create a DSL for processing the data, of if you can simply use XSLT.

P.S. “Simply use XSLT”? Did I just write that down? I take it back! I can fully understand how having to write XSLT can drive any sane person to code his own DSL. In assembler, if needs be!

2006-03-23. 3 responses.

Linux Revisited

Over the last two weekends, I spent numerous hours trying to install OpenSuse Linux on my laptop. Actually, installing it wasn’t the real problem; getting the built-in wireless network adapter to talk to my wireless network was.

I remember the days when Linux was still fresh and new, and there were only one or two distributions. It was 1994 when I first installed Linux, probably RedHat, on a faculty computer, because they wanted their own webserver (after I persuaded them that the web was going to be big. Anyday now. I remember being awestruck at the end of ’93, when I first saw an Australian museum’s website with photos on it, so I went and made a website for the Rotterdam law faculty where I worked at the time, with scanned photos of the city of Rotterdam on it.) Linux came on a couple of disks back then, and installed and ran happily on an old 386sx that was gathering dust in a corner. Text only of course, no fancy GUIs available yet. Fortunately I had just had a Unix course for the Convex number-cruncher that the university had just bought (does Convex still exist?).
Continue Reading »

2006-02-23. No responses.

Start Your Own Campfire

After marvelling over the idea behind Campfire, I wondered how easy Rails would make it to start my own campfire. After all, the concept doesn’t seem to be all that complex: log people’s messages and feed them back to all the other people in the same chatroom. There’s some bells and whistles around that, like logging in, creating your own room, inviting others to join your room, etcetera. But I think, if you’ve got the basic concept covered, the rest will follow easy enough. And that basic concept didn’t proof to be all that hard to build — with Rails.

First, I created a very simple database table to hold all messages with a timestamp and username for each message. Then I created my Rails application, with one model class for the messages and one ChatController. ChatController contains an index method that initially reads all messages from the database and passes them and a fresh new Message object to the view. There’s a create method that will store a newly entered message in the database. And finally there’s a refresh method for periodically refreshing the div in the view that contains the message log. The index.rhtml displays the messages using a _messages.rhtml partial that is also used for refreshing them, with a periodically_call_remote call. To add some more Ajax, newly entered messages are sent back with a form_remote_tag, so the visitor never sees the screen blank for server requests.

That’s it, really. Nothing more to it. For the basics, anyway. I could think of a ton of features I’d like to add. First thing I’ll do is to add authentication; then put it on DreamHost and tell my colleagues and friends. We won’t be needing Campfire’s services, thank you very much. Blame Rails for making it easy.

Download the source here: Kampvuur (Dutch for Campfire) 0.1 BETA

Kampvuur screenshot

2006-02-21. One response.

News of the World

M. and I were just talking about how much the web has changed our lives. She can now find, read and print scientific articles for her work via large databases on the web; articles from bonafide, peer-reviewed magazines, that sometimes are not even published on paper anymore. In my own work, the web is indispensable as well: JavaDocs can be downloaded but are just as easily accessed online; and for most programming problems or weird error messages there’s an answer to be found via Google. We are all connected to an immense network of information and experience; connected to the world, it feels like. Next thing, I open up Bloglines, start reading the first post and wind up on this website (made in Holland I am proud to say) where the world map literally cries out its news flashes as they happen. Yesterday Campfire, today this; what will I find tomorrow? I love the web.



Screenshot from What’s Up. I guess, for Dallas, this is world news…

2006-02-18. No responses.

Ruby’s Exclamations: A Dream Come True

After writing the post about exclamation mark methods in Ruby yesterday evening, I couldn’t get to sleep (lesson learned: don’t go straight to bed after blogging). My mind was still churning away over the whole issue. And just before I fell asleep, in the short period of time when a lucid state of geniality bordering on insanity sometimes befalls you, when either the greatest ideas or the worst flops come to you — I dreamed up this code.

srand Time.now.to_i

class Ruby
    S = ['yes', 'no', 'absolutely not',
        'of course', 'you already know', 'of course not',
        'who knows?', 'I guess so...', 'I guess not...',
        'maybe', 'perhaps', 'certainly not',
        'positively so', 'try google', 'who cares?',
        'why not?', 'the answer is in your heart',
        'we may never know for sure']
    def self.exclamation_mark!
        @@r = rand
        Ruby
    end
    def self.is_redundant?
        q = @@r * S.size
        S[q]
    end
end

puts Ruby.exclamation_mark!.is_redundant?

2006-01-23. No responses.

Ruby’s Redundant Exclamation Marks

When I first read (in Why’s (Poignant) Guide to Ruby) about Ruby having ‘destructive’ methods, I couldn’t think why such a redundancy would be necessary in a language. Destructive methods are those ending with an exclamation mark; they are called destructive because they may change the instance its operating on. Take for example the String#gsub method. In its non-destructive form it returns the substitution you ask it to perform:

irb(main):001:0> s = "abcde"
=> "abcde"
irb(main):002:0> s.gsub(/bcd/, 'thlet')
=> "athlete"
irb(main):003:0> s
=> "abcde"

As you can see, the object s remains unchanged after the gsub. If you do the same thing with the destructive variant, s will be changed:

irb(main):003:0> s
=> "abcde"
irb(main):004:0> s.gsub!(/bcd/, 'thlet')
=> "athlete"
irb(main):005:0> s
=> "athlete"

Redundant, because you could also have used the non-destructive gsub and assigned its result back to s. Sure, it’s shorter; but only by two characters in the source code; and I don’t believe it’s a DRY violation to write s = s.gsub(...).
Since then, however, I have come to believe there may be good uses of the destructive method construct. For example when you’re writing a business method that needs to alter the object it’s operating on. In that case, using an exclamation mark notation will alert you about the method’s ‘destructive’ behaviour.

My friendly Ruby guru took an altogether different approach to all this, when he wanted destructive variants of methods he’d already written. Obviously, he didn’t want to duplicate the code; but he also didn’t want to write a wrapper for every destructive variant. So he used meta programming to write a def_variants method that can be used to add a destructive variant, and — as a bonus — a class method with the same name. The gsub! method can now be written as def_variants :gsub. (Well, not quite, but you’d have to read the entire post. Which is, unfortunately, in Dutch. The code samples aren’t though, and if you send Remco an email he might consider an English translation.)
I’m still not sure though if his solution put an end to this redundancy, or introduced even more redundancy…

2006-01-22. 3 responses.

« Prev - Next »