| 1 | package Net::Amazon::MechanicalTurk::Command::SetQuestionPostValidationOnError; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Net::Amazon::MechanicalTurk::QAPValidator; | ||
| 5 | use Carp; | ||
| 6 | |||
| 7 | our $VERSION = '1.00'; | ||
| 8 | |||
| 9 | # | ||
| 10 | # Extension method which hooks the CreateHIT api call | ||
| 11 | # in order to validate the QAP on XML error and try to give | ||
| 12 | # a better error message. | ||
| 13 | # | ||
| 14 | # Note: There is a CPAN module called XML::Validate | ||
| 15 | # (It didn't find and download the schema on MSXML though for some reason). | ||
| 16 | # | ||
| 17 | # This code is experimental and currently only works on Windows. | ||
| 18 | # | ||
| 19 | |||
| 20 | sub setQuestionPostValidationOnError { | ||
| 21 | my ($mturk, $value) = @_; | ||
| 22 | |||
| 23 | if ($value) { | ||
| 24 | createValidator(); # Make sure there is a validator | ||
| 25 | if (!$mturk->filterChain->hasFilter(\&validator)) { | ||
| 26 | $mturk->filterChain->addFilter(\&validator); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | else { | ||
| 30 | $mturk->filterChain->removeFilter(\&validator); | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | sub createValidator { | ||
| 35 | return Net::Amazon::MechanicalTurk::QAPValidator->create; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub validator { | ||
| 39 | my ($chain, $targetParams) = @_; | ||
| 40 | my ($mturk, $operation, $params) = @$targetParams; | ||
| 41 | |||
| 42 | if ($operation ne "CreateHIT") { | ||
| 43 | return $chain->(); | ||
| 44 | } | ||
| 45 | else { | ||
| 46 | my $result; | ||
| 47 | eval { | ||
| 48 | $result = $chain->(); | ||
| 49 | }; | ||
| 50 | if ($@) { | ||
| 51 | my $error = $@; | ||
| 52 | if (exists $params->{Question} and | ||
| 53 | $mturk->response and | ||
| 54 | $mturk->response->errorCode and | ||
| 55 | $mturk->response->errorCode =~ /XMLParseError/) | ||
| 56 | { | ||
| 57 | my $validated = 1; | ||
| 58 | my $info = {}; | ||
| 59 | eval { | ||
| 60 | $validated = createValidator()->validate($params->{Question}, $info); | ||
| 61 | }; | ||
| 62 | if (!$validated) { | ||
| 63 | Carp::croak(sprintf "%s\n%s\nLocation: line %s column %s.\n\n%s", | ||
| 64 | $error, | ||
| 65 | $info->{message}, | ||
| 66 | $info->{line}, | ||
| 67 | $info->{column}, | ||
| 68 | $params->{Question}); | ||
| 69 | } | ||
| 70 | else { | ||
| 71 | Carp::croak(sprintf "%s\n\n%s", | ||
| 72 | $error, | ||
| 73 | $params->{Question}); | ||
| 74 | } | ||
| 75 | } | ||
| 76 | else { | ||
| 77 | Carp::croak($error); | ||
| 78 | } | ||
| 79 | } | ||
| 80 | return $result; | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | return 1; |