package com.netflix.spinnaker.rosco.manifests;

import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import com.netflix.spinnaker.kork.core.RetrySupport;
import com.netflix.spinnaker.rosco.services.ClouddriverService;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import retrofit.client.Response;

@Component
@Slf4j
public final class ArtifactDownloaderImpl implements ArtifactDownloader {
  private final ClouddriverService clouddriverService;
  private final RetrySupport retrySupport = new RetrySupport();

  public ArtifactDownloaderImpl(ClouddriverService clouddriverService) {
    this.clouddriverService = clouddriverService;
  }

  public void downloadArtifact(Artifact artifact, Path targetFile) throws IOException {
    try (OutputStream outputStream = Files.newOutputStream(targetFile)) {
      Response response =
          retrySupport.retry(() -> clouddriverService.fetchArtifact(artifact), 5, 1000, true);
      if (response.getBody() != null) {
        try (InputStream inputStream = response.getBody().in()) {
          IOUtils.copy(inputStream, outputStream);
        }
      }
    }
  }
}

@@ -479,16 +479,47 @@
 ponent;%0A
+import retrofit.RetrofitError;%0A
 import r
@@ -1337,16 +1337,404 @@
    %7D
-%0A      %7D
+ catch (IOException e) %7B%0A          throw new IOException(%0A              String.format(%0A                  %22Failed to read input stream of downloaded artifact: %25s. Error: %25s%22,%0A                  artifact, e.getMessage()));%0A        %7D%0A      %7D%0A    %7D catch (RetrofitError e) %7B%0A      throw new IOException(%0A          String.format(%22Failed to download artifact: %25s. Error: %25s%22, artifact, e.getMessage()));
 %0A   

improve error messaging for failed artifact downl… (#453)