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

com.dahuatech.icc.multiinone.oss.OssSDK Maven / Gradle / Ivy

There is a newer version: 1.0.13.7
Show newest version
package com.dahuatech.icc.multiinone.oss;

import com.dahuatech.hutool.http.ssl.TrustAnyHostnameVerifier;
import com.dahuatech.hutool.json.JSONObject;
import com.dahuatech.hutool.log.Log;
import com.dahuatech.hutool.log.LogFactory;
import com.dahuatech.icc.common.ParamValidEnum;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.multiinone.Constants;
import com.dahuatech.icc.multiinone.exception.BusinessException;
import com.dahuatech.icc.multiinone.oss.enums.PictureSplicingFormatEnums;
import com.dahuatech.icc.multiinone.oss.vo.DownloadPicRequest;
import com.dahuatech.icc.multiinone.oss.vo.DownloadPicResponse;
import com.dahuatech.icc.multiinone.oss.vo.ShowPicRequest;
import com.dahuatech.icc.multiinone.oss.vo.ShowPicResponse;
import com.dahuatech.icc.oauth.http.IccClient;
import com.dahuatech.icc.oauth.model.v202010.OauthConfigBaseInfo;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.X509Certificate;

/**
 * Oss图片拼接访问和下载SDK封装
 * **/
public class OssSDK {

    /**
     * Oss图片拼接token访问
     * **/
    protected final Log logger = LogFactory.get();

    public ShowPicResponse showPic(ShowPicRequest request){
        logger.info("OssSDK,showPic,param:{}.",new JSONObject(request).toJSONString(0));
        ShowPicResponse showPicResponse = new ShowPicResponse();
        try{
            request.valid();
            showPicResponse.setPicUrl(showPicUrl(request.getPicUri(),request.getOauthConfigBaseInfo(),request.getType()));
        }catch (BusinessException businessException){
            logger.error("OSS service splicing token fail,errorMsg:{}.",businessException,businessException.getMessage());
            showPicResponse.setCode(businessException.code);
            showPicResponse.setErrMsg(businessException.msg);
        }catch (Exception e){
            logger.error("OSS service splicing token fail,errorMsg:{}.",e,e.getMessage());
            showPicResponse.setErrMsg(Constants.SYSTEMERROR_MSG);
            showPicResponse.setCode(Constants.SYSTEMERROR_CODE);
        }
        return showPicResponse;
    }

    /**
     * Oss图片下载
     * **/
    public  DownloadPicResponse downloadPic(DownloadPicRequest request){
        DownloadPicResponse downloadPicResponse = new DownloadPicResponse();
        try{
            request.valid();
            String picUrl = showPicUrl(request.getPicUri(),request.getOauthConfigBaseInfo(),request.getType());
            downloadPicResponse.setByteArrayOutputStream(download(picUrl));
        }catch (BusinessException businessException){
            logger.error("OSS service download image fail,errorMsg:{}.",businessException,businessException.getMessage());
            downloadPicResponse.setCode(businessException.code);
            downloadPicResponse.setErrMsg(businessException.msg);
            return downloadPicResponse;
        }catch (Exception e){
            logger.error("OSS service download image fail,errorMsg:{}.",e,e.getMessage());
            downloadPicResponse.setErrMsg(Constants.SYSTEMERROR_MSG);
            downloadPicResponse.setCode(Constants.SYSTEMERROR_CODE);
            return downloadPicResponse;
        }
        if(downloadPicResponse.getByteArrayOutputStream()==null){
            downloadPicResponse.setCode(ParamValidEnum.PARAM_FORMAT_ERROR.getCode());
            downloadPicResponse.setErrMsg("OSS service download image fail,errorMsg.");
        }else {
            downloadPicResponse.setCode(Constants.SUCESS_CODE);
            downloadPicResponse.setErrMsg(Constants.SUCCESS_MSG);
        }
        return downloadPicResponse;
    }

    private ByteArrayOutputStream download(String picUrl){
        ByteArrayOutputStream os = null;
        InputStream is = null;
        try {
            // 构造URL
            URL url = new URL(picUrl);
            trustAllHosts();
            // 打开连接
            HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
            con.setHostnameVerifier(new TrustAnyHostnameVerifier());
            // 设置请求超时为5s
            con.setConnectTimeout(5 * 1000);
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            os = new ByteArrayOutputStream();
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            return os;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 完毕,关闭所有链接
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param picUri
     * @param oauthConfigBaseInfo
     * @param type
     * @return 图片访问地址拼接
     * @throws ClientException
     */
    private static String showPicUrl(String picUri, OauthConfigBaseInfo oauthConfigBaseInfo, int type) throws ClientException, BusinessException {
        IccClient iccClient = new IccClient(oauthConfigBaseInfo);
        String prefixUrl = oauthConfigBaseInfo.getHttpConfigInfo().getPrefixUrl();

        if(type== PictureSplicingFormatEnums.OssPictureSplicingFormat.type) {
            //oss访问方式
            return prefixUrl + "/evo-apigw/evo-oss/" + picUri + "?token=" + iccClient.getAccessToken().getAccess_token();
        }else if(type==PictureSplicingFormatEnums.ParkingLotPictureSplicingFormat.type){
            //停车场方式
            return prefixUrl+"/evo-apigw/ipms/imageConvert/originalImage?fileUrl="+picUri;
        }else if(type==PictureSplicingFormatEnums.BayonetPictureSplicingFormat.type){
            //交通卡口方式
            int index=prefixUrl.lastIndexOf(":");
            return prefixUrl.substring(0,index) +"/evo-apigw/evo-oss/"+picUri;
        }else{
            throw new BusinessException(ParamValidEnum.PARAM_FORMAT_ERROR.getCode(),"Access way input error.");
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy