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.RetrofitError;
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 InputStream downloadArtifact(Artifact artifact) throws IOException {
    Response response =
        retrySupport.retry(() -> clouddriverService.fetchArtifact(artifact), 5, 1000, true);
    if (response.getBody() == null) {
      throw new IOException("Failure to fetch artifact: empty response");
    }
    return response.getBody().in();
  }

  public void downloadArtifactToFile(Artifact artifact, Path targetFile) throws IOException {
    try (OutputStream outputStream = Files.newOutputStream(targetFile)) {
      try (InputStream inputStream = downloadArtifact(artifact)) {
        IOUtils.copy(inputStream, outputStream);
      } catch (IOException e) {
        throw new IOException(
            String.format(
                "Failed to read input stream of downloaded artifact: %s. Error: %s",
                artifact, e.getMessage()),
            e);
      }
    } catch (RetrofitError e) {
      throw new IOException(
          String.format("Failed to download artifact: %s. Error: %s", artifact, e.getMessage()), e);
    }
  }
}

@@ -218,16 +218,76 @@
 ervice;%0A
+import com.netflix.spinnaker.security.AuthenticatedRequest;%0A
 import j
@@ -1073,16 +1073,108 @@
 t.retry(
+%0A            () -%3E%0A                AuthenticatedRequest.allowAnonymous(%0A                    
 () -%3E cl
@@ -1217,18 +1217,55 @@
 act)
-, 5, 1000,
+),%0A            5,%0A            1000,%0A           
  tru

allow anonymous clouddriver artifact fetching (#748)