| 1 | # $Id: /mirror/gungho/lib/Gungho/Provider/YAML.pm 1743 2007-05-28T06:34:14.539886Z lestrrat $ | ||
| 2 | # | ||
| 3 | # Copyright (c) 2007 Daisuke Maki <daisuke@endeworks.jp> | ||
| 4 | # All rights reserved. | ||
| 5 | |||
| 6 | package Gungho::Provider::YAML; | ||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use base qw(Gungho::Provider); | ||
| 10 | use Best [ | ||
| 11 | [ qw(YAML::Syck YAML) ], | ||
| 12 | qw(LoadFile) | ||
| 13 | ]; | ||
| 14 | |||
| 15 | __PACKAGE__->mk_classdata($_) for qw(read_done requests); | ||
| 16 | |||
| 17 | sub new | ||
| 18 | { | ||
| 19 | my $class = shift; | ||
| 20 | my $self = $class->next::method(@_); | ||
| 21 | |||
| 22 | $self->has_requests(1); | ||
| 23 | $self->read_done(0); | ||
| 24 | $self->requests([]); | ||
| 25 | $self; | ||
| 26 | } | ||
| 27 | |||
| 28 | sub pushback_request | ||
| 29 | { | ||
| 30 | my ($self, $c, $req) = @_; | ||
| 31 | |||
| 32 | my $list = $self->requests; | ||
| 33 | push @$list, $req; | ||
| 34 | $self->has_requests(1); | ||
| 35 | } | ||
| 36 | |||
| 37 | sub _load_from_yaml | ||
| 38 | { | ||
| 39 | my ($self, $c) = @_; | ||
| 40 | my $filename = $self->config->{filename}; | ||
| 41 | die "No file specified" unless $filename; | ||
| 42 | |||
| 43 | my $config = eval { LoadFile($filename) }; | ||
| 44 | if ($@ || !$config) { | ||
| 45 | die "Could not read YAML file $filename: $@"; | ||
| 46 | } | ||
| 47 | } | ||
| 48 | |||
| 49 | sub dispatch | ||
| 50 | { | ||
| 51 | my ($self, $c) = @_; | ||
| 52 | |||
| 53 | if (! $self->read_done) { | ||
| 54 | my $config = $self->_load_from_yaml(); | ||
| 55 | |||
| 56 | foreach my $conf (@{ $config->{requests} || []}) { | ||
| 57 | my $req = Gungho::Request->new( | ||
| 58 | $conf->{method} || 'GET', | ||
| 59 | $conf->{url} | ||
| 60 | ); | ||
| 61 | |||
| 62 | my($name, $value); | ||
| 63 | while (($name, $value) = keys %{ $conf->{headers} || {} }) { | ||
| 64 | $req->push_header($name, $value); | ||
| 65 | } | ||
| 66 | |||
| 67 | while (($name, $value) = each %$conf) { | ||
| 68 | next if $name =~ /^(?:method|url|headers)$/; | ||
| 69 | if (my $code = $req->can($name)) { | ||
| 70 | $code->($req, $value); | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | $req = $c->prepare_request($req); | ||
| 75 | $self->pushback_request($c, $req); | ||
| 76 | } | ||
| 77 | $self->read_done(1) | ||
| 78 | } | ||
| 79 | |||
| 80 | my $requests = $self->requests; | ||
| 81 | $self->requests([]); | ||
| 82 | while (@$requests) { | ||
| 83 | $self->dispatch_request($c, shift @$requests); | ||
| 84 | } | ||
| 85 | |||
| 86 | if (scalar @{ $self->requests } <= 0) { | ||
| 87 | $c->is_running(0); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | |||
| 91 | 1; | ||
| 92 | |||
| 93 | __END__ |