RESTful Clients
Demo time!
WebQ survey integration.
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(param);
use LWP::UserAgent;
use Crypt::SSLeay;
use XML::LibXML;
use Digest::MD5;
use Time::HiRes qw(gettimeofday tv_interval);
my $time = [gettimeofday]; #benchmark
## Config
$ENV{HTTPS_CERT_FILE} = '/etc/apache2/ssl/cert.pem';
$ENV{HTTPS_KEY_FILE} = '/etc/apache2/ssl/key.pem';
my $survey_title = 'REST Example';
my $version = 'v1';
my $url = 'https://catalysttools.washington.edu/rest/webq';
my $my_url = 'http://example.washington.edu/pub/webq_client/';
my $use_cache = 0;
## CGI
print "Content-type: text/html\n\n";
#Locate version
my $xpath = wsCall($url, 'GET');
my ($node) = $xpath->findnodes('//*[@class="version" and . = "v1"]');
$url = $node->getAttribute('href');
#locate survey
$xpath = wsCall($url, 'GET');
($node) = $xpath->findnodes("//*[\@class='survey' and . = '$survey_title']");
$url = $node->getAttribute('href');
#locate participants resource
$xpath = wsCall($url, 'GET');
($node) = $xpath->findnodes('//*[@rel="participants"]');
$url = $node->getAttribute('href');
#add a participant, if needed
if(my $new_id = param('new_id')){
wsCall($url, 'POST', "<element class='rest_id'>$new_id</element>");
}
#list participants
print "<h1>Survey: $survey_title</h1><ul>";
$xpath = wsCall($url, 'GET', undef);
for my $node ($xpath->findnodes('//*[@class="participant"]')) {
my ($link) = $node->findnodes('.//*[@class="rest_id"]');
my ($results) = $node->findnodes('.//*[@class="response_count"]');
my $survey_url = $link->getAttribute('href'). "?return_url=$my_url";
my $has_taken = $results->textContent() ? 'Has taken survey.' : 'Has NOT taken survey.';
print "<li><a href='$survey_url'>". $link->textContent()."</a> - $has_taken</li>";
}
print "</ul><br><br><form method='POST'><input name='new_id'><input type='submit' value='Add new participant'></form>";
print "<br><br>".tv_interval($time, [gettimeofday]) ." seconds";
exit;
## Functions
#Make a call to the web service, return xml doc of response
sub wsCall {
my $url = shift;
my $method = shift;
my $content = shift;
my $cache_filename = Digest::MD5::md5_hex($url);
my $response_text;
if($method eq 'GET' && $use_cache && -e "cache/$cache_filename"){
$response_text = `cat cache/$cache_filename`;
}else{
my $ua = LWP::UserAgent->new;
$ua->agent("Solstice Webservices Client/0.1 ");
my $req = HTTP::Request->new( $method => $url );
$req->content($content) if $content;
my $res = $ua->request($req);
$response_text = $res->content();
if($use_cache){
open my $cachefile, ">", "cache/$cache_filename";
print $cachefile $response_text;
close $cachefile;
}
}
my $parser = XML::LibXML->new();
$parser->load_ext_dtd(0);
return $parser->parse_string($response_text);
}