This Mason component handles the generic output format options for
text string parsers/checkers like check_routestring.
+# typical url for this script:
+# http://www.chiark.greenend.org.uk/ucgi/~clareb/mason/pirates/qtextstring?what=routestring?format=json&ocean=Midnight&string=d
+
</%doc>
+
+<%args>
+$ocean
+$format
+$ctype => undef
+$string
+$what
+$dbh => undef
+$debug => 0
+</%args>
+
<%flags>
inherit => undef
</%flags>
use JSON;
use Data::Dumper;
use HTML::Entities;
+use CommodsWeb;
+use Scalar::Util qw(blessed);
+
+die if $what =~ m/[^a-z]/;
+my $chk= $m->fetch_comp("check_${what}");
+
+my $mydbh;
+$dbh ||= ($mydbh= dbw_connect($ocean));
+
+my $debugf= !$debug ? sub { } : sub {
+ print escapeHTML("@_")."\n";
+};
+
+$debugf->("QTSC STRING '$string'");
+
+my $emsg= '';
+my @results;
+my $canontext;
+
+$string =~ s/^\s*//;
+$string =~ s/\s$//;
+$string =~ s/\s+/ /g;
-my ($emsg, $canontext, $results)= $m->call_next();
+if ($chk->method_exists('execute')) {
+ ($canontext, @results)= eval {
+ $chk->call_method('execute',
+ dbh => $dbh, string => $string,
+ debugf => $debugf);
+ };
+ if ($@) {
+ die unless blessed $@ && $@->isa('CommodsWeb::ExpectedError');
+ $emsg= $@->emsg();
+ }
+} else {
+ my $sqlstmt= $chk->scall_method("sqlstmt");
+ my $sth= $dbh->prepare($sqlstmt);
+ my @sqlstmt_nqs= $sqlstmt =~ m/\?/g;
+ my $sqlstmt_nqs= @sqlstmt_nqs;
+
+ my @specs= $chk->attr('multiple')
+ ? (split m#\s*[/|,]\s*#, $string)
+ : ($string);
+
+ foreach my $each (@specs) {
+ next unless $each =~ m/\S/;
+ my ($temsg, @tresults) =
+ dbw_lookup_string($each,
+ $sth, $sqlstmt_nqs,
+ $chk->attr_exists('abbrev_initials'),
+ $chk->attr('maxambig'),
+ $chk->scall_method("nomatch", specq => escerrq($each)),
+ $chk->scall_method("manyambig"),
+ sub {
+ $chk->scall_method("ambiguous",
+ specq => escerrq($each),
+ couldbe => $_[1])
+ });
+ if (defined $temsg) {
+ $emsg= $temsg;
+ last;
+ }
+ push @results, [ @tresults ];
+ };
+}
+
+if (!defined $canontext) {
+ $canontext= join ' | ', map { $_->[0] } @results;
+}
$emsg='' if !defined $emsg;
+@results=() if length $emsg;
-my $format= $ARGS{'format'};
-my $ctype= $ARGS{'ctype'};
+$debugf->("QTSC EMSG='$emsg' RESULTS='@results'");
if ($format =~ /json/) {
- $r->content_type($ctype or $format);
+ $ctype ||= $format;
+ die unless grep { $_ eq $ctype }
+ qw(application/json text/plain text/xml);
+ $r->content_type($ctype);
my $jobj= {
success => 1*!length $emsg,
- show => (length $emsg ? encode_entities($emsg) :
+ show => (length $emsg ? $emsg :
length $canontext ? encode_entities($canontext) :
' '),
};
print to_json_shim($jobj);
}
-if ($format =~ /return/) {
- return {
- Error => $emsg,
- Results => length $emsg ? $results : undef
- };
-}
if ($format =~ /dump/) {
$r->content_type('text/plain');
- print Dumper($emsg, $canontext, $results);
+ print Dumper($emsg, $canontext, \@results);
}
+$mydbh->rollback() if $mydbh;
+
+return $emsg,
+ $canontext,
+ @results;
+
</%perl>