Archive for October, 2006


Friday wrap-up #3

Saturday, October 28th, 2006

This was a busy week, a lot of catching up from all the time spent at CASCON last week. Continuing on from last week, I’ve gotten more intimate (?) with Dojo and its inner workings. I wrote about Dojo a couple months ago, and I’m still really impressed with everything going on there. A lot of big name sites are built off this toolkit, including Meebo.

IBM results came out last week, the System i had a rough quarter, but IBM did well overall. Last year at this time (3Q05) the System i had a break out quarter due to an upgrade cycle. This year (3Q06) there were no new upgrades and results were the same as 3Q04. This article sums things up:

IBM revenue for the System i fell 22 percent in the third quarter of 2006, or 23 percent at constant currency when compared to the same period of 2005. At the same time, nearly every other major IBM business unit saw revenue increase. Overall, earnings rose 47 percent compared to the previous year, up to $2.22 billion on revenues of $22.6 billion, which were up 5 percent.

The supply chain issues IBM faced in the second quarter of this year for System i sales, which were connected to a 7 percent drop in revenue for System i over the second quarter of 2005, have cleared up. IBM CFO Mark Loughridge noted that IBM’s supply chain did a superb job delivering System p, i, z, and storage but faltered over System x deliveries, contributing to the low rise of 4 percent for the System x. System p revenues increased 10 percent, and System z was a breakout star with a 25 percent increase in revenues while IBM delivered a 16 percent increase in System z MIPS (millions of instructions per second).

For the System i, IBM says 3Q06 compares to a particularly strong 3Q05 quarter, which was driven by upgrade activity from a fully refreshed roadmap, which in turn caused slowing revenue as customers leveraged those previous upgrades. Overall, IBM notes that System i revenue performance remains dependent upon cyclical upgrades.

I was at a Halloween fund raiser for Diabetes last night, it was a good time for a good cause. I’m amazed that no matter what type of social event I may be at, there’s always someone thats directly involved with the System i in some way.

In other news, RedHat got murdered this week in the markets. Cisco announced they would be creating a fork the RedHat’s version of Linux and providing half price support until the new year. If any good can be seen out of this, it just re-affirms RedHat’s dominance in the Enterprise Linux market.

FireFox 2 came out this week, it generally seems more responsive, but definitely not as polished as it should be. The memory leak issue doesn’t seem to have been fixed, since as I type FireFox is using upwards of 80mb memory and climbing. The new spell checking feature is great though, any work misspelled get underlined in red, right click the and suggestions appear.

Friday wrap-up #2

Friday, October 20th, 2006

CASCON was running this week from Monday to Thursday. I didn’t realize this was a free conference for everyone, including people outside IBM. I saw a bunch of professors from McMaster also, some were giving talks.

I went to the Ruby on Rails workshop and it was going OK until one of the presenters starting comparing Ruby on Rails (RoR) to PHP. People need to get something straight: Ruby is the programming language and Rails is a framework. Comparing RoR to PHP isn’t fair, since PHP is the programming language with no framework. If you’re going to compare them, make sure your using some type of template engine like Smarty, etc.

Tuesday, Wednesday and Thursday I had a display at the Technology Showcase from 11:30am to 1:30pm, presenting WDSC and JWL. The experience was good, I met a lot of great people really interested in AJAX and JSF.

Doug Crockford is a smart guy, he’s a JavaScript guru and the creator of JSON. Earlier this year he wrote a paper describing JSONRequest, here’s the abstract:

XMLHttpRequest has a security model which is inadequate for supporting the next generation of web applications. JSONRequest is proposed as a new browser service that allows for two-way data exchange with any JSON data server without exposing users or organization to harm. It exchanges data between scripts on pages with JSON servers in the web. It is hoped that browser makers will build this feature into their products in order to enable the next advance in web application development.

It’s a good read and not a bad idea (though received a lot of criticism). There has also been heavy discussion about this on the Dojo mailing list. Doug’s personal website is filled with great JavaScript articles and resources – especially this article on objects in JavaScript.

I read Chapter 5 of Roy Fielding’s dissertation, which introduced REST or Representational State Transfer. REST is a lot like the Relational Database, conceptually its easy, but has the potential to revolutionize how we do certain things.

How To: Making a PHP REST client to call REST resources

Friday, October 20th, 2006

A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.

An example would be Yahoo!’s Geocoding API, with the following URL:

Code:
http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&street=701+First+Street&city=Sunnyvale&state=CA

I would get:

Code:
<Result precision="address">
   <Latitude>37.416384</Latitude>
   <Longitude>-122.024853</Longitude>
   <Address>701 FIRST AVE</Address>
   <City>SUNNYVALE</City>
   <State>CA</State>
   <Zip>94089-1019</Zip>
   <Country>US</Country>
</Result>

So Yahoo! exposes the Geocode URL and allows you to query this resource using URL parameters like appid and street. Dynamically building your URL to query a given resource is OK, generally that’s what people do, like the following:

Code:
$base = 'http://xml.amazon.com/onca/xml3';
$query_string = "";

$params = array( 'ManufacturerSearch' => "O'Reilly",
    'mode'  => 'books',
    'sort'  => '+salesrank',
    'page'  => 1,
    'type'  => 'lite',
    'f'     => 'xml',
    't'     => 'trachtenberg-20' ,
    'dev-t' => 'XXXXXXXXXXXXXX' ,
);

foreach ($params as $key => $value) {
    $query_string .= "$key=" . urlencode($value) . "&";
}

$url = "$base?$query_string";
$output = file_get_contents($url);

The problem here, is that REST is meant to take advantage of HTTP methods GET, POST, PUT, DELETE, etc.. When people are showing examples which dynamically build queries and call file_get_contents, the average user doesn’t appreciate (understand) what type of request is being made. Do they care? Should they care? We’ll that’s another story. Eventually though, more intense REST resources will become widely available, and it will be critical the user (developer) understands if their making a POST or PUT request.

I came across a great PEAR package the other day called HTTP_REQUEST, which among many things supports GET/POST/HEAD/TRACE/PUT/DELETE, basic authentication, proxy, proxy authentication, SSL, file uploads and more. Using this package, I got started on a simple wrapper class called RESTclient, which gives intuitive support for making REST resource calls.

So if I was going to use RESTclient to call the Geocode API above, it would look like this:

Code:
<?php

require_once "RESTclient.php";

$rest = new RESTclient();

$inputs = array();
$inputs["appid"] = "YahooDemo";
$inputs["street"] = "701 First Street";
$inputs["city"] = "Sunnyvale";
$inputs["state"] = "CA";

$url = "http://api.local.yahoo.com/MapsService/V1/geocode/"
$rest->createRequest("$url","POST",$inputs);
$rest->sendRequest();
$output = $rest->getResponse();
echo $output;

?>

At this point, you might be thinking, who cares — what’s the difference between using a loop to dynamically generate the URL or RESTclient. There are lots of reasons, first off, I can easily call the Geocode resource again using another address just by changing:

Code:
$inputs["street"] = "1600 Amphitheatre Parkway";
$inputs["city"] = "Mountain View";

There was no need to re-generate the URL. Furthermore, I’m explicitly specifying a POST request. Just as easily I can make a PUT, DELETE, etc. request on a given resource by changing the createRequest method parameters.

The class below is RESTclient. Note, I put this together to prove a point, it still needs some work if you plan on using it.

Code:
<?php

require_once "HTTP/Request.php";

class RESTClient {

    private $root_url = "";
    private $curr_url = "";
    private $user_name = "";
    private $password = "";
    private $response = "";
    private $responseBody = "";
    private $req = null;

    public function __construct($root_url = "", $user_name = "", $password = "") {
        $this->root_url = $this->curr_url = $root_url;
        $this->user_name = $user_name;
        $this->password = $password;
        if ($root_url != "") {
            $this->createRequest("GET");
            $this->sendRequest();
        }
        return true;
    }

    public function createRequest($url, $method, $arr = null) {
        $this->curr_url = $url;
        $this->req =& new HTTP_Request($url);
        if ($this->user_name != "" && $this->password != "") {
           $this->req->setBasicAuth($this->user_name, $this->password);
        }        

        switch($method) {
            case "GET":
                $this->req->setMethod(HTTP_REQUEST_METHOD_GET);
                break;
            case "POST":
                $this->req->setMethod(HTTP_REQUEST_METHOD_POST);
                $this->addPostData($arr);
                break;
            case "PUT":
                $this->req->setMethod(HTTP_REQUEST_METHOD_PUT);
                // to-do
                break;
            case "DELETE":
                $this->req->setMethod(HTTP_REQUEST_METHOD_DELETE);
                // to-do
                break;
        }
    }

    private function addPostData($arr) {
        if ($arr != null) {
            foreach ($arr as $key => $value) {
                $this->req->addPostData($key, $value);
            }
        }
    }

    public function sendRequest() {
        $this->response = $this->req->sendRequest();

        if (PEAR::isError($this->response)) {
            echo $this->response->getMessage();
            die();
        } else {
            $this->responseBody = $this->req->getResponseBody();
        }
    }

    public function getResponse() {
        return $this->responseBody;
    }

}
?>

Friday wrap-up #1

Friday, October 13th, 2006

Update (Nov. 18 2006): I’ll try and do this weekly, but no guarantees.

Last thing I want to do is write another AJAX framework, but it seems that’s the only way to fully understand large-scale AJAX development. We’ll see what happens — I’ve spent a lot of time looking into Object Notations (ON) (JSON, YAML, etc.) this past week, weighing out trade-offs between run-time extensions to server side scripts. I’ve been getting a lot of people asking for another AJAX tutorial to continue from the original — I’ll try and write something soon.

This past Tuesday, I sat in on the 3rd and final Technology Showcase my 2nd line manager had organized. This one in particular was on C, C++, and Fortran Compilers. A lot of cool stuff in the works, we even got a demo (video) of the PS3 in action.

Motivated by Ryan’s idea of KeyboardCast, I made a couple suggestions to the Target Management (Remote Systems Explorer) subproject in Eclipse, about being able to execute a single shell command on multiple servers (or targets). After some discussions, agreeing to help out in specs/code/discussions, I got sucked into testing for their 1.0 release! Ah, it was ok, I had a small commitment of 2 hours.

I finally submitted my 2nd application for a patent @ IBM. Considering the backlog at the US patent office is something ridiculous like 2+ years — I have a while to wait. The patent is for a revolutionary new type of XML Parser that a manager and I came up with — that’s all I can say about it now.

Next week is the CASCON conference. Aside from the keynotes and walk-in talks, I’ve signed up for 3 workshops:

  • Hands-on: Building a Ruby on Rails application with DB2 Express-C 9
  • Social Computing: Best Practices
  • Social Computing: How the Social Web (R)evolution is Changing the Business Landscape

I’ll also be holding a Technology Showcase @ CASCON on WDSC & JWL Tuesday, Wednesday and Thursday from 11:30am till 1:30pm:

WDSC JWL 3.0 in Action
This exhibit will demonstrate the rich JSF/JavaScript-based widget library JWL. Currently in the finishing stages of development, JWL will revolutionize the way users interact with applications. Widgets/abilities include full AJAX support, key press bindings, calendars, panel dialogs, panel menus, context assist, converters, and much more.

I fallen off my great quest to become an expert at object oriented design patterns — I seriously have to spend some this weekend.

How to: Building dynamic PHP objects and URL decoding example

Friday, October 6th, 2006

PHP is a powerful programming language; with every release I’m amazed with the new power and functionality. The ability to build dynamic objects (the way I’ll describe) I believe was introduced as of PHP 5. In any case, this is good stuff. There are lots of reasons why you would want to create a dynamic object, in my example below; you’ll see how to create a dynamic object of the URL query parameters.

At the heart of building dynamic PHP objects are the PHP Magic Methods. From the PHP manual:

The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __set_state, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Magic methods get called automatically through the parser when certain events occur. For example, just before you transition pages all objects you’ve created will call their respective __sleep methods. Most likely you wouldn’t have this method defined, so nothing would happen.

So now lets look at what happens when a certain method (or variable) of a given PHP object is called. Take the following code as an example:

Code:
$x = new obj();
$x->method1();
$x->var1;

When a method of a given object is called (like method1) the first thing the parser does is look for the associated name in the instance of the object. If the method is found, then the parser gives control to the method. If the method is not found, then the __call function is called with the function name and input values as a parameter. If this function returns true, then the object will return successfully. If a __call function does not exist, the parser will check the parent class (if exists) and so forth.

Similarly, if a variable of an object is requested (like var1) the parser looks in the object for a variable with that name. If a variable does not exist, the __get method is called with the name of the variable as a parameter, and so forth.

You should be able to see how we can now simulate (fake) the existence of methods and variables by using these magic methods. The code below shows the parent class G_Dynamic. This class would be the parent to specific subclasses that would require dynamic method/variable access.

Code:
<?php

/*  */

/**
 *
 * PHP versions 5.1.4
 *
 * George A. Papayiannis
 *
 * This class provides the magic functions needed to create
 * a dynamic object.  Subclasses would extend this object
 * and call the constructor with a parsed array.  See
 * g_url_decode.class.php for an example of creating a
 * dynamic object from the URL query string.
 *
 */

/**
 * Class definition
 */

class G_Dynamic {

    private $param = array();

    public function __construct($init) {
        $this->param = $init;
    }

    private function __get($name) {
        if (isset($this->param[$name])) {
            $res = $this->param[$name];
        } else {
            $res = false;
        }
        return $res;
    }

    private function __set($name, $val) {
        if (isset($this->param[$name])) {
            $this->param[$name] = $val;
            $res = true;
        } else {
            $res = false;
        }
        return $res;
    }

    private function __isset($name) {
        return isset($this->param[$name]);
    }

    private function __unset($name) {
        unset($this->param[$name]);
    }

    private function __call($name, $var) {
        // add code to simulate function call
        // return TRUE for success
    }

}

?>

As an example, I created a subclass to G_Dynamic called G_URL_Decode. This class takes the URL query string as input, parses it into an array and calls the parents (G_Dynamic) constructor. The code for G_URL_Decode is below:

Code:
<?php

/*  */

/**
 *
 * PHP versions 5.1.4
 *
 * George A. Papayiannis
 *
 * This class extends the G_Dynamic class to create a
 * dynamic object of the URL query string.  In another
 * file, you would have:
 *
 * require_once "g_url_decode.class.php";
 * $x = new G_URL_Decode($_SERVER['QUERY_STRING']);
 *
 * then you could have $x->(url param name) to access
 *
 */

require_once "g_dynamic.class.php";

/**
 * Class definition
 */

class G_URL_Decode extends G_Dynamic {

    private $queryParam = array();

    public function __construct($qs) {
         parent::__construct($this->parseURL($qs));
    }

    public function getQueryParam() {
        return $this->queryParam;
    }

    private function parseURL($qs) {
        $this->queryParam = array();
        $qs_parsed = explode("&", $qs);
		foreach ($qs_parsed as $value) {
			$paramVal = explode("=",$value);
			if (array_key_exists(1,$paramVal)) {
				$this->queryParam[htmlspecialchars(urldecode($paramVal[0]))] = htmlspecialchars(urldecode($paramVal[1]));
			}
		}
		return $this->queryParam;
    }
}

?>

Once the URL query string is successfully parsed, you can access the parameter names through the object. The code to bring it all together is below.

Code:
<?php

require_once "g_url_decode.class.php";
$x = new G_URL_Decode($_SERVER['QUERY_STRING']);
echo $x->var1;

?>

Using this as a base, you should be able to build some pretty cool dynamic objects.
Click here to download the source.

The best (free) PHP IDE..

Friday, October 6th, 2006

Update (Mar. 5/07): Eventually you would need some type of version control and I just saw an Eclipse Plugin for SVN.

I’ve been a long time fan of simple development environments. Give me EditPlus with syntax highlighting and I’m good to go. I’ve always known about TM (Target Management) or better known around here at Remote Systems Explorer. As the name says, the plug-in lets you work with remote systems from within Eclipse. So no matter were I am, I can connect to my server (through SSH, FTP, etc.) and work remotely. I can even launch a shell from within Eclipse! The TM group hasn’t released 1.0 yet, but it should be there within a couple weeks.

Along the same lines, a couple weeks ago I got exposed to the PHP IDE project. This is another Eclipse project in the works, being sponsored mainly by Zend with support from IBM and others. Their in version 0.7 right now, and expect to release version 1.0 sometime near the end of the year. The plug-in is stable, but I’ve noticed small problems ranging from automatic formatting issues to context assist errors. Aside from the small problems, this plug-in is amazing — The syntax highlighting is great, there is automatic publishing and an integrated debugger in the works.

With RSE + PHP IDE almost at 1.0, I have a feeling Eclipse will soon be my development environment of choice — If only Eclipse loaded as fast as EditPlus. Here are some screen shots of Eclipse + TM + PHP IDE. Click the image to see a large shot.


Eclipse


Eclipse