package com.jeeplus.common.oss;

import com.aliyun.oss.common.utils.BinaryUtil;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yushuting on 16/4/17.
 */
public class OssUploadPart {

    private String postFileName = "F:\\code\\jeeplus_maven\\target\\jeeplus.war";  // 确保运行代码的路径中有该文件
    private String ossEndpoint = "http://oss-cn-hangzhou.aliyuncs.com";  // 如: http://oss-cn-shanghai.aliyuncs.com
    private String ossAccessId = "LTAIi7VuxcgfJR2x";  // 你的访问AK信息
    private String ossAccessKey = "Q9xF9V7tcnCI28ttUsP8H4GyAhZta7";  // 你的访问AK信息
    private String objectName = "app-data/appfiles/"+System.currentTimeMillis()+"/classes.rar";  // 你上传文件之后的object名称
    private String bucket = "gangwan-app";  // 你之前创建的bucket，确保这个bucket已经创建

    private void PostObject() throws Exception {

        String filepath=postFileName;
        String urlStr = ossEndpoint.replace("http://", "http://"+bucket+".")+"/"+objectName; // 提交表单的URL为bucket域名
        LinkedHashMap<String, String> textMap = new LinkedHashMap<String, String>();
        // key
        String objectName = this.objectName;
        textMap.put("key", objectName);
        // Content-Disposition
        textMap.put("Content-Disposition", "attachment;filename="+filepath);
        // OSSAccessKeyId
        textMap.put("OSSAccessKeyId", ossAccessId);
        // policy
        String policy = "{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}";
        System.out.println("policy:"+policy);
        String encodePolicy = BinaryUtil.toBase64String(policy.getBytes());
        textMap.put("policy", encodePolicy);
        System.out.println("encodePolicy:"+encodePolicy);
        // Signature
        String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(ossAccessKey, encodePolicy);
        textMap.put("Authorization", signaturecom);

        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("file", filepath);

        String ret = formUpload(urlStr, textMap, fileMap);
        System.out.println("[" + bucket + "]  put_object:" + objectName);
        System.out.println("put reponse:" + ret);
    }

    private String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) throws Exception {
        String res = "";
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Length","344606");
            conn.setRequestProperty("x-oss-server-side-encryption","AES256");
            conn.setRequestProperty("x-oss-object-acl","public-read-write");
            conn.setRequestProperty("x-oss-date",new Date()+"");
            conn.setRequestProperty("content-encoding","utf-8");
            conn.setRequestProperty("content-disposition","attachment;filename="+objectName);

            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                int i = 0;
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    if (i == 0) {
                        strBuf.append(inputValue);
                    } else {
                        strBuf.append(inputValue);
                    }

                    i++;
                }
                out.write(strBuf.toString().getBytes());
            }

            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String contentType = new MimetypesFileTypeMap().getContentType(file);
                    if (contentType == null || contentType.equals("")) {
                        contentType = "application/octet-stream";
                    }

                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("Content-Type: " + contentType + "\r\n\r\n");

                    out.write(strBuf.toString().getBytes());

                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
                StringBuffer strBuf = new StringBuffer();
                out.write(strBuf.toString().getBytes());
            }
            out.flush();
            out.close();

            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    conn.getInputStream());

            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.err.println("发送POST请求出错: " + urlStr);
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }

    public static void main(String[] args) throws Exception {
        OssUploadPart ossPostObject = new OssUploadPart();
        ossPostObject.PostObject();
    }

}
