All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rt.web.util.io.GCSUtil Maven / Gradle / Ivy

The newest version!
package com.rt.web.util.io;

import com.google.auth.oauth2.ComputeEngineCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.WriteChannel;
import com.google.cloud.storage.*;
import com.google.common.collect.Lists;
import com.rt.core.constant.RTConst;
import com.rt.core.log.Log;
import com.rt.core.util.RTUtil;
import com.rt.web.beans.IOItem;
import com.rt.web.util.WebConst;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * web帮助类
 */
public class GCSUtil implements IOFace {

    protected static Log log = Log.getLog(GCSUtil.class);

    private Storage storage;
    private final static List ACLS = new ArrayList<>();
    private static String credentialsValue;
    private final static String GPATH = "https://www.googleapis.com/auth/cloud-platform";

    static {
        ACLS.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
    }

    public static void setCredentials(String value) {
        credentialsValue = value;
    }

    private Storage getStorage() {
        if (storage == null) {
            if (RTUtil.isEmpty(credentialsValue)) {
                // gae实例读取资深权限.
                GoogleCredentials credentials = ComputeEngineCredentials.create();
                storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
            } else {
                try {
                    // 读取指定权限
                    GoogleCredentials credentials = GoogleCredentials.fromStream(RTUtil.toInputStream(credentialsValue)).createScoped(Lists.newArrayList(GPATH));
                    storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
                } catch (Exception e) {
                    log.error("init storage credentials error: ", e);
                }
            }
        }
        return storage;
    }

    public String generateGetSignedUrl(String bucketName, String name, long minutes) {
        // Define resource
        BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(bucketName, name)).build();

        /**
         * Signing a URL requires Credentials which implement ServiceAccountSigner. These can be set
         * explicitly using the Storage.SignUrlOption.signWith(ServiceAccountSigner) option. If you
         * don't, you could also pass a service account signer to StorageOptions, i.e.
         * StorageOptions().newBuilder().setCredentials(ServiceAccountSignerCredentials). In this
         * example, neither of these options are used, which means the following code only works when
         * the credentials are defined via the environment variable GOOGLE_APPLICATION_CREDENTIALS, and
         * those credentials are authorized to sign a URL. See the documentation for Storage.signUrl for
         * more details.
         */
//        java.net.URL url =
//                getStorage().signUrl(blobInfo, minutes,
//                        java.util.concurrent.TimeUnit.MINUTES,
//                        Storage.SignUrlOption.withV4Signature());

//        System.out.println("Generated GET signed URL:");
//        System.out.println(url);
//        System.out.println("You can use this URL with any user agent, for example:");
//        System.out.println("curl '" + url + "'");
//        return url.toString();
        return "";
    }

    @Override
    public final IOItem get(String bucketName, String name) {
        if (RTUtil.isEmpty(bucketName) || RTUtil.isEmpty(name)) {
            return null;
        }
        Blob blob = getStorage().get(BlobInfo.newBuilder(bucketName, fixName(bucketName, name)).setAcl(ACLS).build().getBlobId());
        if (blob == null) {
            return null;
        }
        IOItem item = new IOItem();
        try {
            item.setLastModified(blob.getCreateTime());
            item.setLength(blob.getSize());
            item.setEtag(blob.getEtag());
            item.setCacheControl(blob.getCacheControl());
            item.setContentType(blob.getContentType());
            item.setByteArray(blob.getContent());
            return item;
        } catch (Exception e) {
            log.error(e);
            return null;
        }
    }

    @Override
    public final String save(String bucketName, String name,
                             String contentType, byte[] fileByteArray)
            throws Exception {
        if (RTUtil.isEmpty(bucketName) || RTUtil.isEmpty(name)
                || fileByteArray == null || fileByteArray.length == 0) {
            throw new NullPointerException();
        }
        name = fixName(bucketName, name);
        BlobInfo.Builder blobInfoBuilder = BlobInfo.newBuilder(bucketName, name);
        blobInfoBuilder.setAcl(ACLS);
        blobInfoBuilder.setContentType(fixContentType(contentType,
                RTUtil.substringAfterLast(name, RTConst.DOT)));
        getStorage().create(blobInfoBuilder.build(), fileByteArray);
        return RTConst.ROOT_PATH + bucketName + RTConst.ROOT_PATH + name;
    }

    public final boolean writer(String bucketName, String name, int offset, byte[] fileByteArray) {
        if (RTUtil.isEmpty(bucketName) || RTUtil.isEmpty(name)
                || fileByteArray == null || fileByteArray.length == 0) {
            throw new NullPointerException();
        }
        if (RTUtil.isEmpty(bucketName) || RTUtil.isEmpty(name)) {
            return false;
        }
        BlobId blobId = BlobId.of(bucketName, fixName(bucketName, name));

        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
        try (WriteChannel writer = getStorage().writer(blobInfo)) {
            writer.write(ByteBuffer.wrap(fileByteArray, offset, fileByteArray.length));
        } catch (Exception e) {
            log.error(e);
            return false;
        }
        return true;
    }

    @Override
    public final boolean delete(String bucketName, String name) {
        if (RTUtil.isEmpty(bucketName) || RTUtil.isEmpty(name)) {
            return false;
        }
        try {
            return getStorage().delete(BlobInfo.newBuilder(bucketName, fixName(bucketName, name)).build().getBlobId());
        } catch (Exception e) {
            log.error(e);
            return false;
        }
    }

    private String fixName(String bucketName, String name) {
        if (RTUtil.startsWith(name, RTConst.ROOT_PATH)) {
            name = RTUtil.removeStart(name, RTConst.ROOT_PATH);
        }
        String bp = bucketName + RTConst.ROOT_PATH;
        if (RTUtil.startsWith(name, bp)) {
            name = RTUtil.removeStart(name, bp);
        }
        return name;
    }

    public static String fixContentType(String type, String extName) {
        // 类型为空
        if (RTUtil.isEmpty(type)
                // 类型为流
                || RTUtil.equalsIgnoreCase(WebConst.CONTENT_TYPE_APPLICATION_OCTETSTREAM, type)
                // 类型与扩展名不符
                || RTUtil.containsIgnoreCase(type, extName) == false
                ) {
            // 通过扩展名查找一种更接近的类型.
            String newType = WebConst.getContentType(extName);
            return newType == null ? type : newType;
        } else {
            return type;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy