Bio-EnsEMBL

 view release on metacpan or  search on metacpan

lib/Bio/EnsEMBL/Utils/Net.pm  view on Meta::CPAN


  Arg [1]     : string $uri
  Arg [2]     : int; $total_attempts The number of times to try the URI 
                before throwing an exception
  Arg [3]     : number; $sleep Amount of time to sleep between attempts. 
                Delegates onto Time::HiRes so floating point numbers are 
                supported
  Description : Performs a FTP fetch using a non-authenticated connection (
                however some servers will allow you to encode this in the URI).
  Returntype  : Boolean true if download was successful.
  Example     : my $contents = do_GET('http://www.google.co.uk/');
  Exceptions  : If we could not retrieve the resource after the specified 
                number of attempts.
  Status      : Stable

=cut

sub do_FTP_to_file {
  my ($url, $total_attempts, $sleep, $filename) = @_;
  return _retry_sleep(sub {
    return _get_lwp_to_file($url, $filename);
  }, $total_attempts, $sleep);
}

sub _retry_sleep {
  my ($callback, $total_attempts, $sleep) = @_;
  $total_attempts ||= 1;
  $sleep ||= 0;
  my $response;
  my $retries = 0;
  my $fail = 1;
  while($retries <= $total_attempts) {
    $response = $callback->();
    if(defined $response) {
      $fail = 0;
      last;
    }
    $retries++;
    Time::HiRes::sleep($sleep);
  }
  if($fail) {
    throw "Could not request remote resource after $total_attempts attempts";
  }
  return $response;
}

sub _get_http_tiny {
  my ($url) = @_;
  my $response = HTTP::Tiny->new->get($url);
  return unless $response->{success};
  return $response->{content} if length $response->{content};
  return;
}

sub _get_lwp {
  my ($url) = @_;
  throw "Cannot perform action as LWP::UserAgent is not available" unless $LWP;
  my $ua = LWP::UserAgent->new();
  $ua->env_proxy;
  my $response = $ua->get($url);
  return $response->decoded_content if $response->is_success;
  return;
}

sub _get_lwp_to_file {
  my ($url, $filename) = @_;
  throw "Cannot perform action as LWP::UserAgent is not available" unless $LWP;
  throw "Filename required for download to proceed." unless $filename;
  my $ua = LWP::UserAgent->new();
  $ua->env_proxy;
  my $response = $ua->get($url, ":content_file" => $filename);
  print 'UA Response: '.$response->is_success."\n";
  if ($response->is_success) {return 1}
  throw $response->status_line;
}

1;



( run in 0.821 second using v1.01-cache-2.11-cpan-39bf76dae61 )