package hudson.plugins.s3;

import hudson.FilePath;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;

import org.kohsuke.stapler.DataBoundConstructor;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;

public class S3Profile {
    private String name;
    private String accessKey;
    private String secretKey;
    private static final AtomicReference<AmazonS3Client> client = new AtomicReference<AmazonS3Client>(null);

    public S3Profile() {
    }

    @DataBoundConstructor
    public S3Profile(String name, String accessKey, String secretKey) {
        this.name = name;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        client.set(new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey)));
    }

    public final String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public final String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public final String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public AmazonS3Client getClient() {
        if (client.get() == null) {
            client.set(new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey)));
        }
        return client.get();
    }

    public void check() throws Exception {
        getClient().listBuckets();
    }
    
    
   
    public void upload(String bucketName, FilePath filePath) throws IOException, InterruptedException {
        if (filePath.isDirectory()) {
            throw new IOException(filePath + " is a directory");
        }
        
        final Destination dest = new Destination(bucketName,filePath.getName());
        
        try {
            getClient().putObject(dest.bucketName, dest.objectName, filePath.read(), /*metadata=*/null);
        } catch (Exception e) {
            throw new IOException("put " + dest + ": " + e);
        }
    }
    
 
    
}

@@ -272,16 +272,124 @@
 3Client;
+%0Aimport com.amazonaws.services.s3.model.ObjectMetadata;%0Aimport com.amazonaws.services.s3.internal.Mimetypes;
 %0A%0Apublic
@@ -2016,32 +2016,195 @@
 me());%0A        %0A
+        ObjectMetadata metadata = new ObjectMetadata();%0A        metadata.setContentType(Mimetypes.getInstance().getMimetype(filePath.getName()));%0A                %0A
         try %7B%0A  
@@ -2290,18 +2290,16 @@
 (), 
-/*
 metadata
 =*/n
@@ -2298,15 +2298,8 @@
 data
-=*/null
 );%0A 
@@ -2404,24 +2404,12 @@
   %7D%0A
+
     %7D%0A
-    %0A %0A    %0A
 %7D%0A

Use AWS MimeType library to determine the Content-Type of the file (based on filename) before uploading. This prevents issues where all files are set as application/octet-stream.