Lithium Problem on Rackspace

Today I came across a situation where I was deploying a PHP-based webapp written in Lithium and running on a Rackspace cloud site. In my scenario, I noticed 2 symptoms (appearing differently, but having the same cause).

  1. if the Lithium app is a subdirectory of another webapp (in my example, the main site is WordPress), you will always get a WordPress “Oops! The page you are looking for does not exist.” error.
  2. if the Lithium app is in the root, you will get an “Internal Server Error” page.

As it turns out, the problem is the .htaccess file included with Lithium.

I don’t think there’s anything wrong with the .htaccess per se, but under Rackspace you seem to have to include the “RewriteBase” directive.

So, as a result, you must edit all 3 .htaccess files in your Lithium project thus:

  • /.htaccess – RewriteBase /
  • /app/.htaccess – RewriteBase /app/
  • /app/webroot/.htaccess – RewriteBase /app/webroot/

If your webapp is a subdirectory, this subdirectory name will need to prepended to RewriteBase path:

  • /.htaccess – RewriteBase /subdir/
  • /app/.htaccess – RewriteBase /subdir/app/
  • /app/webroot/.htaccess – RewriteBase /subdir/app/webroot/

And presto, it now magically works!

Don’t Use JavaScript To Detect Browser

Just a word of warning – if you need to check for a specific version of Internet Explorer, do not rely on JavaScript. While working on a project where I was applying JavaScript to customize a closed-source package (yes, we were allowed to do this by the provider), we wanted to make sure that users were using only IE8 and up.

Fairly simple, right?

Well, no. It seems the package we were using was putting IE9 into quirks mode, which (much to my surprise) causes the user agent string to report the browser as IE7.

So, no JavaScript to detect the browser version.

On the server-side, the user agent was coming through correctly, so at least we had a different avenue on which we could proceed, but it seems rather peculiar that there would be no way to correctly identify a browser because of how it is rendering the page.

Error calling method on NPObject

I’ve had a bit of a problem with a Java Applet running in Safari on Windows. I have JavaScript code which attempts to invoke public methods in the Applet, but whenever I try to call these I get the error “Error calling method on NPObject”.

I’ve read a fair amount of BS “causes” (from things like “it’s a hidden DIV” to “Upgrade your JRE”), none of which proved to the the problem.

The real problem?

Safari doesn’t care if the applet is loaded before trying to invoke the methods.

Under Chrome, Opera, Firefox and even my much hated Internet Explorer, if you try to invoke a method on an applet which hasn’t loaded yet, the JavaScript runtime waits for the applet to complete, and then resumes. Safari does not.

So now, as part of the applet tag’s parameters, I have to include a method name which the applet must invoke in JavaScript, thereby guaranteeing that the applet is loaded and running.

Now I have the problem that apparently Safari is trying to execute JavaScript methods as URLs, thus causing a “Malformed URL” error.

Update:

After a bit of experimenting, it seems Safari does not like trying to pass and return non-String values. So, instead of using LiveConnect’s “call” method, you have to use “eval”, and don’t expect to be able to pass object around.

XML Prolog in PHP

Okay, I get it. For some PHP programmers, the notion of the PHP short-code being the same as the open and close of the XML prolog is enough to throw you into a foaming rage.

However – of all the “solutions” I’ve seen, this has to be the worst:

<?php echo ("<"); ?>?xml version="1.0" encoding="UTF-8"?<?php echo ">"; ?>

Come on now, guys … really?! That’s a good solution, is it? Hey, here’s an easy one, just for all of you who get confused and don’t like using short-codes:

<?= '<?xml version="1.0" encoding="UTF-8"?>' ?>

Geez, guys, seriously, it’s not that big of a deal!

Lithium Filters – What’s the Point?

I’ve used Lithium for 2 projects now, and I have one major issue – I honestly don’t see the benefit of “filters” vs. “callback” methods.

I understand that conceptually it’s supposed to “decouple” the filter logic from the model itself. However, every example of applying filters to Models show the filter being applied to an individual model directly using the 2 methods below:

<?php
class MyModel extends \lithium\data\Model {
    public static function __init() {
        // ...
        static::applyFilter('save', function(...) {
            // ...
        });
    }
} 

or

<?php
class MyModel extends \lithium\data\Model {
} 
MyModel::applyFilter('save', function(...) {
    // ...
});

In my humble opinion, neither of this is “decoupling”, since the actual code for the filters exists directly within the model itself anyway.

One would think you can overcome this my applying the filter to the “Model” class directly – WRONG! The filter never fires.

So, since I have a filter which is shared, I created a method in some other class which my individual filters call. How is this any different than simply having a callback which invokes the external method, too?

No – to me filters are thus-far fairly useless in the Model context (I’ve successfully used it on the Dispatcher).

XML-RPC under Ruby on Rails

On a current project, I needed to develop a series of web services for a custom single-signon (unified login) for a bunch of different websites to share. The project needed to be in Ruby on Rails, since that is what is available to the servers, and needed to use a protocol which PHP, Java and Ruby could all understand.

At first I tried to investigate using ActiveResource, but I found this to be excessively Rails-centric, and it only seemed to provide basic CRUD functionality. I needed these webservices to do a lot more work, with a lot more parameters. Since the Rails community (and a lot of web developers in general) seem to rave about RESTful services, my next direction was to write a custom series of REST-based webservices. As I proceeded, it became glaringly obvious that REST services have on major shortcoming – complex data.

Since the basic idea of REST is that all parameters become part of the URI itself (something, I might add, ActiveResource violates right away), you immediately have a problem when it comes to things like street addresses. Everyone’s solution is to use basic HTTP parameters or to URL-encode the data, but to me these solution tainted the point of REST, and made for some truly hideous looking URL’s, respectively.

I also didn’t like the lack of type control. This same lack also negated using JSON-RPC or even some custom YAML-based solution. All the experiences I had with SOAP left a bad taste in my mouth for that one, so what was I to do?

Thankfully, I discovered that Ruby had XML-RPC functionality built right in. But the problem arose that all examples I could find of using it (since Ruby’s documentation is complete and utter dog-sh*t) only showed the XML-RPC server running in stand-alone mode. I certainly couldn’t do this. So after much tinkering, I herewith present a controller class which you can extend to offer very simple XML-RPC calls from within a Rails environment:

#
# This class provides a framework for XML-RPC services on Rails
#
require 'xmlrpc/server'
class WebServiceController < ApplicationController

  # XML-RPC calls are not session-aware, so always turn this off
  session :off

  def initialize
    @server = XMLRPC::BasicServer.new
    # loop through all the methods, adding them as handlers
    self.class.instance_methods(false).each do |method|
      unless ['index'].member?(method)
        @server.add_handler(method) do |*args|
          self.send(method.to_sym, *args)
        end
      end
    end
  end

  def index
    result = @server.process(request.body)
    puts "\n\n----- BEGIN RESULT -----\n#{result}\n----- END RESULT -----\n"
    render :text => result, :content_type => 'text/xml'
  end

end

Here is a working example of using the above code:

class StringController < WebServiceController

  def upper_case(s)
    s.upcase
  end

  def down_case(s)
    s.downcase
  end

end

Invoking the remove method couldn’t be any simpler:

require 'xmlrpc/client'
require 'pp'


server = XMLRPC::Client.new2("http://localhost:3010/string")

result = server.call("upper_case", "This is my string")
pp result

result = server.call("down_case", "This is my string")
pp result

I certainly hope this simple bit of Ruby will help anyone else who may have suffered trying to figure this out as I have.

Enjoy!

When “Agile”, “Dynamic” and “Typeless” Become a Hindrance.

In recent years, I’ve seen the apparent rising popularity of “Agile” programming, powered by “dynamic” languages such as “Ruby”. While these things seem warm and fluffy at first, in the long term with large projects, they really can become a difficult beast to control.

Let’s take “Ruby on Rails” as an example. I was recently tasked with upgrading our version of Rails from 1.2.3 all the way up to 2.3.2, no easy task to be sure. We decided that a gradual, version-by-version upgrade would work the best, since it would allow us to catch deprecations and handle the framework changes a bite at a time.

What I discovered in the end was that Rails itself uses so much “magic”, and directly modifies so many core Ruby API’s that it was impossible to predict what would break between versions. As an example, a minor version change from 1.2.3 to 1.2.4 caused unexpected changes in how dates were handled. The change-logs made no reference to such modifications. The change from 2.1 to 2.2 resulted in a host of modules no longer being identified. Oh sure, if you printed it out, Ruby “thought” it was available, but the minute you tried to actually use anything within the module, you would receive “uninitialized constant” errors on the module name itself.

I know everyone has their own opinions on the matter, but from where I stand using Ruby on Rails on a system even vaguely large and complex simply raises far too many question marks on predictability and a clean upgrade path.

As a comparison, let’s refer to Java 2 Enterprise. Every piece of code I have ever written in J2EE version 1.0 runs without any issue under a J2EE version 3 container. Not even a re-compile was required. I do realise that the comparison is somewhat unfair – but the point still remains. I have very rarely needed to make major changes to any Java-based application to cater for a new framework – especially between minor version numbers.

I hate to make a blanket case for all agile/dynamic frameworks, so I’ll admit that was probably unfair (Grails, Django are on my to-do list). However, my case is even held fast on a more superficial level – my own benchmarks on a variety of languages clearly show that although time and effort may be saved on initial development time, dynamic/typeless languages will always suffer in raw speed, and agile frameworks will always suffer from a degree of unpredictability when upgrading (this becomes immensely exaggerated when “auto-magic” comes into play, as there is no clear path when anything does break).

To be clear, I won’t abandon agile frameworks – if I just want a simple website up, and expect maybe a dozen hits a month, I’m certainly not going to do it in a full blown enterprise container – but in the same token, I would certainly not use any such framework in a banking environment!

Partial Mocking/Stubbing and why it’s not evil.

Over the last few years, I’ve started expanding the places where I use automated testing (both test driven development and behaviour driven development, even though one would have to admit that in reality there’s little difference between them). I had only every written very simplistic JUnit tests for Java modules, but never really for the greater overall project. This changed when I starting working on a Ruby on Rails, where we were required to make extensive use of RSpec.

One of the things I learned to appreciate was the heavy use of stubbing (and expectations) that RSpec provided. Obviously, this was easier to do for a dynamic language such as Ruby (ignoring all the other shortcomings of the language itself).

When I started writing Java applications again, I obviously wanted to be able to perform similar tests with similar stubbings. To my dismay, the more pedantic amongst us programmers somehow decided that partial mocking/stubbing was somehow a truly terrible thing to do. I began reading all sort of justifications for why it was bad, and how one should refactor the class being tested in order to test it.

jMock and Mockito both adhered to this belief, EasyMock seemed less stringent, but stubbing was overly string-based (making refactorying later on a little annoying since tests would fail for no other reason than renaming a method).

Following is an example of the EasyMock mechanism (as shown in their documentation)

ToMock mock = createMock(ToMock.class,
   ToMock.class.getMethod("mockedMethod", null));

Unfortunately, all these folks fail to take into account the real world, and situation under which you code might not want to allow users to screw around with dependent objects. Here is a real example:

I created a class which did a load of work (let’s call it FlowClass), and part of this work was to use another class (let’s call it LoaderClass) which started up operating system processes. I needed to test the flow of FlowClass, but I didn’t want to start firing off all sorts of new processes. Easily enough, I was able to move the instantiation of LoaderClass into another method, but using something like jMock, how do I prevent that one single method from causing processes to load? I emphatically do not want the user to have to set instance of LoaderClass (like a JavaBean property), because I needed to keep strict control over the flow. The idea of having to introduce potential erratic program behaviour simply in order to test is completely unacceptable by any stretch of the imagination.

One site I came across suggested subclassing FlowClass directly in the test (even though, once more, the author makes all sort of claims of this being evil but delicious). This did the job, but it seems like so many lines of code to do nothing more than force a value to be returned. On top of that, what if I wanted to check to make sure the method was even ever called?

My needs eventually led me to create JavaStubs. It doesn’t do all the work that the other mocking frameworks do, but what it does do is allow me to quickly and easily stub method, including capturing exceptions for testing, and counting how many times they were called. I tried to be as string-less as possible (thank goodness for Java generics), and make it easily readable (much thanks to Mockito for suggestions on that one).