package com.search.supersearch.demo.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

@RestController
@RequestMapping("/hoss")
@Slf4j
public class HelloOss {

    @GetMapping("/getTest")
    public void getTest() {
        String endpoint = "http://oss-cn-anshun-dtcloud-d01-a.ops.dtcloud.spic";
        String accessKeyId = "G4yqKKVMwEVfwDPg";
//        String accessKeyId = "4aPZ5FG22UV0OVbB";
        String accessKeySecret = "rkxHoNWeYJRfgX1NaaB2qjvcU72Spk";
//        String accessKeySecret = "7GnNiqly7aJ7K2nY3YGQ7vT3SrGteO";
        String bucketName = "dsj-sjxt-testbucket01";
//        String bucketName = "dsjsjxt-kffwq01-10-104-32-30";
        String filename = "a/untitled.png";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //InputStream is = new ByteArrayInputStream("Hello OSS".getBytes());
            String file = "C:\\Users\\dsjsj17\\Downloads\\" + filename;
            FileInputStream fileInputStream = new FileInputStream(new File(file));
            ossClient.putObject(bucketName, filename, fileInputStream);
            System.out.println("Object：" + filename + "存入OSS成功。");
            OSSObject ossObject = ossClient.getObject(bucketName, filename);
            InputStream inputStream = ossObject.getObjectContent();
            StringBuilder objectContent = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                objectContent.append(line);
            }
            inputStream.close();
            System.out.println("Object：" + filename + "的内容是：" + objectContent);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
        }
    }
}