Welcome to openkapow Sign in | Join
in Search

Mashup demos

These are demo mashups that shows the potential of using openkapow robots.

About the "CountryCard" demo

Select a country on the list and see information about the country from different sources. Each category of information is pulled from more sources and displayed in collapsed text blocks.
  

The CountryCard example demonstrates how openkapow REST and Clipping robots can be used in the context of a object oriented PHP setting. This is illustrated by collecting information about a country from different facts and travel sites, and displaying the available information on a single web page. The example focuses on how to encapsulate REST calls in a PHP class and to use exceptions to handle errors from the service.

The demo page

This very basic example has a drop down to select a country. For each category a number of robots are called and if the robot returns succesfully the information is displayed in a box with a reference to the information provider. Each category of information is displayed in a collapsable section to let the user focus on the necessary information.

The information sources

There are many sources for information about countries. We have chosen a few examples that are reasonable fast, has a well organized structure and is available without registration.

  • CIA World Fact Book lists a lot of factual information about countries with a bias towards military related information.
  • Lonely Planet Offers travel advice, detailed maps, travel news, popular message boards and health information. Also lists information and updates regarding guidebooks.
  • Rough Guides features online coverage of thousands of travel destinations.
  • Flickr hosts millions of tagged user submitted photos about everything and nothing.

A simple REST robot

Most of the robots in this example are simple REST services and follows the pattern shown below. We find and click tags based on an input value and extract the result into the result atrribute of the RESTOutput object. If any errors occur during the execution, we collect a message in the errorMessage attribute of the RESTOutput


To simplify the wrapping of the responses in PHP all robots apply the same output format. Each robot names a result and errorMessage field in the RESTOutput object and when XML is choosen as output format, it will result in the XML seen below.

 

<?xml version="1.0" encoding="UTF-8"?>
<response>
<result> ... </result>
<errorMessage/> ... <errorMessage>
</response>

Your outermost tag might be different from this example. You can choose the name of the root tag in the robot configuration under output formats in RoboMaker. Be convention we decide that any robot response with content in the <errorMessage> is considered an error response.

Using REST robots in PHP

The basic idea behind using our REST robots in PHP is to wrap the call in a SimpleRESTService object, call the xml_call method with the needed parameters and catch any exceptions thrown during the execution of the robot. An example can be seen in the lising below.

<?php
    
try {
        
$service = new SimpleRestService("http://www.openkapow.com/
            LonelyPlanetProperties.rest");
        
$params = array("country" => $this->ename);
        
$xml $service->xml_call($params);
    }
    catch (
KapowHTTPException $h) {
        echo 
$h->toHTMLAlert();
    }
    catch (
KapowRobotException $r) {
        echo 
$r->toHTMLAlert();
    }
    catch (
KapowPHPException $e) {
        echo 
$e->toHTMLComment();
    }
?>

The use of customized exception classes allows us to handle different exceptions differently. In the example KapowHTTPException and KapowRobotExeptions are rendered on the webpage, but KapowPHPExceptions are hidden as HTML comments.

The result of the xml_call method is a SimpleXMLElement that can be read using normal XML functions available in PHP. The result_call is a wrapper function that returns only the text content of the first <result> tag.

The SimpleRESTService class

The SimpleRESTService class is responsible for calling a REST robot on the openkapow server and return appropriate results or error messages. The only parameter needed to construct a SimpleRESTService is the URL of the service. Any parameters to the REST service is given when the service is called with the xml_call or result_call method.

<?php
    
class SimpleRESTService {
        var 
$requestURL;
        var 
$httpStatus 0;
         
        function 
__construct($url) {
            
$this->requestURL $url;
        }
         
        function 
xml_call($values) {
            
... 
        }
         
        function 
result_call($values) {
            
... 
        }
    }
?>

The SimpleRESTService object can return the XML response from the service via its xml_call function. Before calling the URL each parameter is encoded and added to the call. After the file_get_contents call we check if we got a succesfull (200) HTTP status code back. If we dont, we simply throw a suitable exception. If we get all the way through we return the parsed XML.
Please note that a robot returning an error by filling out the <errorMessage> tag does not raise an exception, while the result_call method handles that situation.

<?php
    
function xml_call($values) {
        
$hasError false;
        
$errorMsg NULL;
        
// create request
        
$request $this->requestURL;
        
$request .= "?";
        
$first true;
        foreach (
$values as $key => $value) {
            if (!
$first$request .= "&";
            
$first false;
            
$request .= urlencode($key)."=".urlencode($value);
        }
        
//Send request and get response
        
$response file_get_contents($request);
        if (!
$response) {
            throw new 
KapowException("The url in [".$request."] did not 
                give any response."1);
        }
        
//Get HTTP status
        
list($version$httpStatus$msg) = explode(' '
            $http_response_header[0], 3);
        
//Check HTTP status
        
switch($httpStatus) {
            case 
200:
            
// success
            
break;
            case 
400:
            
$errorMsg "HTTP Status 400: Bad request";
            break;
            case 
403:
            
$errorMsg "HTTP Status 403: Forbidden";
            break;
            case 
503:
            
$errorMsg "HTTP Status 503: Service unavailable";
            break;
            default:
            
$errorMsg "HTTP Status: " $httpStatus;
        }
        
// if there has been an HTTP error
        
if ($errorMsg != "" && $errorMsg != NULL) {
            throw new 
KapowHTTPException($errorMsg$httpStatus$request);
        }
        
//Read response if no errors have occurred so far
        
$xml simplexml_load_string($response) or die ("Unable to 
            read response from $request");
        return 
$xml;
    }
?>

To simplify the parsing of the most simple REST robots we also provide a result_call method that returns the text version of the result from the robot. If the robot returns a message in the <errorMessage> tag an KapowRobotException is thrown.

<?php
    
function result_call($values) {
        
// get the xml response
        
$xml $this->xml_call($values);
        
// get content of the tags
        
$result $xml->result;
        
$errorMsg $xml->errorMessage;
        
//throw an exception if there is an errorMessage
        
if ($errorMsg != "" && $errorMsg != NULL) {
            throw new 
KapowRobotException($errorMsg2);
        }
        
//else return the result
        
if ($result) {
            return 
$result;
        } else {
            
// if there was no result throw an exception
            
throw new KapowRobotException("There was no result 
                or errorMessage in response from $request"3);
        }
    }
?>

Putting it all together

Now we put all our information providers (inform of REST robots) in a single array and process the results.

<?php
     
    
require("include/CIACountry.inc");
    require(
"include/RoughGuideCountry.inc");
    require(
"include/LonelyPlanetCountry.inc");
     
     
    
$countryName $_GET['country'];
     
    
$providers["CIA"] = new CIACountry($countryName);
    
$providers["RoughGuide"] = new RoughGuideCountry($countryName);
    
$providers["LonelyPlanet"] = new LonelyPlanetCountry($countryName);
     
     
    
// function to display a property from all providers
    
function displayPropertyFromProviders($property) {
        global 
$providers;
        echo 
"
            <div class='collapsable'>
            <a class='collapsable_control' href='BLOCKED SCRIPT void();'>
            <img class='collapsable-image' src='graphics/bullet.jpg'>
            $property</a>
            <div class='collapsable-div'>"
;
        foreach (
$providers as $provider) {
            try {
                echo 
$provider->getPropertyDisplay("$property");
            }
            catch (
KapowHTTPException $h) {
                echo 
$h->toHTMLComment();
            }
            catch (
KapowRobotException $r) {
                echo 
$r->toHTMLAlert();
            }
            catch (
KapowPHPException $e) {
                echo 
$e->toHTMLComment();
            }
        }
        echo 
"
            </div>
            </div>
            "
;
    }
?>

You might have noticed that this demo takes a little time to load. Because we are loading our robots in sequence each robot has to wait for the others to finish. Generally robots are very fast, but of cause they are limited by the web pages they are loading. In this case most of the run-time in the demo is actually spend vaiting for the information providers webservers to respond. The best way around this issue is to load your sources asynchronously, but that is outside the scope of this demo.

Published Wednesday, November 29, 2006 1:15 PM by madsh
Filed under: , , ,

Attachment(s): countrycard.zip

Comments

No Comments
Anonymous comments are disabled
Copyright 2006, 2007 KapowTech.com All Rights Reserved Company | Contact | Terms | Privacy