/*
 * Copyright 2019 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thoughtworks.go.domain;

import com.thoughtworks.go.util.FileUtil;
import com.thoughtworks.go.validation.ChecksumValidator;
import com.thoughtworks.go.work.GoPublisher;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;

import static com.thoughtworks.go.util.CachedDigestUtils.md5Hex;
import static java.lang.String.format;

public class FileHandler implements FetchHandler {

    private final File artifact;
    private final String srcFile;
    private static final Logger LOG = LoggerFactory.getLogger(FileHandler.class);
    private ArtifactMd5Checksums artifactMd5Checksums;
    private ChecksumValidationPublisher checksumValidationPublisher;

    public FileHandler(File artifact, String srcFile) {
        this.artifact = artifact;
        this.srcFile = srcFile;
        checksumValidationPublisher = new ChecksumValidationPublisher();
    }

    @Override
    public String url(String remoteHost, String workingUrl) throws IOException {
        boolean fileExist = artifact.exists();
        LOG.debug("Requesting the file [{}], exist? [{}]", artifact.getAbsolutePath(), fileExist);
        if (fileExist && artifact.isFile()) {
            String sha1 = FileUtil.sha1Digest(artifact);
            return format("%s/%s/%s/%s?sha1=%s", remoteHost, "remoting", "files", workingUrl,
                    URLEncoder.encode(sha1, "UTF-8"));
        } else {
            return format("%s/%s/%s/%s", remoteHost, "remoting", "files", workingUrl);
        }
    }

    @Override
    public void handle(InputStream stream) throws IOException {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = FileUtils.openOutputStream(artifact);
            LOG.info("[Artifact File Download] [{}] Download of artifact {} started", new Date(), artifact.getName());
            IOUtils.copyLarge(stream, fileOutputStream);
            LOG.info("[Artifact File Download] [{}] Download of artifact {} ended", new Date(), artifact.getName());
        } finally {
            IOUtils.closeQuietly(fileOutputStream);
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(artifact);
            LOG.info("[Artifact File Download] [{}] Checksum computation of artifact {} started", new Date(), artifact.getName());
            String artifactMD5 = md5Hex(inputStream);
            new ChecksumValidator(artifactMd5Checksums).validate(srcFile, artifactMD5, checksumValidationPublisher);
            LOG.info("[Artifact File Download] [{}] Checksum computation of artifact {} ended", new Date(), artifact.getName());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    @Override
    public boolean handleResult(int httpCode, GoPublisher goPublisher) {
        checksumValidationPublisher.publish(httpCode, artifact, goPublisher);

        return httpCode < HttpServletResponse.SC_BAD_REQUEST;
    }

    @Override
    public void useArtifactMd5Checksums(ArtifactMd5Checksums artifactMd5Checksums) {
        this.artifactMd5Checksums = artifactMd5Checksums;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof FileHandler)) {
            return false;
        }

        FileHandler that = (FileHandler) o;

        if (artifact != null ? !artifact.equals(that.artifact) : that.artifact != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return artifact != null ? artifact.hashCode() : 0;
    }
}

@@ -806,20 +806,24 @@
 ons.
-io.FileUtils
+codec.binary.Hex
 ;%0Aim
@@ -849,18 +849,20 @@
 mons.io.
-IO
+File
 Utils;%0Ai
@@ -980,17 +980,76 @@
 java.io.
-*
+File;%0Aimport java.io.IOException;%0Aimport java.io.InputStream
 ;%0Aimport
@@ -1086,84 +1086,142 @@
 ava.
-util.Date
+security.DigestInputStream
 ;%0A
-%0A
 import 
-static com.thoughtworks.go.util.CachedDigestUtils.md5Hex;
+java.security.MessageDigest;%0Aimport java.security.NoSuchAlgorithmException;%0Aimport java.util.Date;%0A
 %0Aimp
@@ -2489,132 +2489,132 @@
     
-FileOutputStream fileOutputStream = null;%0A        try %7B%0A            fileOutputStream = FileUtils.openOutputStream(artifact);
+MessageDigest digest = getMd5();%0A        try (DigestInputStream digestInputStream = new DigestInputStream(stream, digest)) %7B
 %0A   
@@ -2737,26 +2737,28 @@
             
-IO
+File
 Utils.copyLa
@@ -2759,38 +2759,53 @@
 copy
-Large(stream, fileOutputStream
+InputStreamToFile(digestInputStream, artifact
 );%0A 
@@ -2933,385 +2933,77 @@
    %7D
- finally %7B%0A            IOUtils.closeQuietly(fileOutputStream);%0A        %7D%0A        FileInputStream inputStream = null;%0A        try %7B%0A            inputStream = new FileInputStream(artifact);%0A            LOG.info(%22%5BArtifact File Download%5D %5B%7B%7D%5D Checksum computation of artifact %7B%7D started%22, new Date(), artifact.getName());%0A            String artifactMD5 = md5Hex(inputStream);%0A    
+%0A%0A        String artifactMD5 = Hex.encodeHexString(digest.digest());%0A
     
@@ -3119,197 +3119,202 @@
     
-   
+%7D%0A%0A
     
- LOG.info(%22%5BArtifact File Download%5D %5B%7B%7D%5D Checksum computation of artifact %7B%7D ended%22, new Date(), artifact.getName());%0A        %7D finally %7B%0A            IOUtils.closeQuietly(inputStream
+private MessageDigest getMd5() %7B%0A        try %7B%0A            return MessageDigest.getInstance(%22MD5%22);%0A        %7D catch (NoSuchAlgorithmException e) %7B%0A            throw new RuntimeException(e
 );%0A 

Improve performance of artifact download+digesting.