编程语言
首页 > 编程语言> > java protobuffer post

java protobuffer post

作者:互联网

postUtil

package com.yung.ad.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ProtoUtils {
    protected final static Logger logger = LoggerFactory.getLogger(ProtoUtils.class);

    private static PoolingHttpClientConnectionManager cm=new PoolingHttpClientConnectionManager();

    static{
        //设置最大连接数不超过200
        cm.setMaxTotal(200);
        //每个路由默认的连接数20
        cm.setDefaultMaxPerRoute(20);
        //路由最大连接数不超过50

        HttpHost locaHost=new HttpHost("localhost",80, "http://");
        HttpRoute route=new HttpRoute(locaHost);
        cm.setMaxPerRoute(route, 50);
    }

    public static byte[] post(String url, byte[] date){
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "x-protobuf;charset=UTF-8");
        try {
            HttpEntity httpEntity = post(url, null, headers, new ByteArrayEntity(date));
            return EntityUtils.toByteArray(httpEntity);
        } catch (Exception e) {
            logger.error("Http post protobuf failed:"+url, e);
        }
        return date;
    }

    public static HttpEntity post(String url, Map<String, String> paraments, Map<String, String> headers, HttpEntity entity){
        RequestBuilder requestBuilder = RequestBuilder.post().setUri(url);
        if(headers != null){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.setHeader(entry.getKey(), entry.getValue());
            }
        }
        if(paraments != null){
            for (Map.Entry<String, String> entry : paraments.entrySet()) {
                requestBuilder.addParameter(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        if(entity != null){
            requestBuilder.setEntity(entity);
        }
        HttpUriRequest  httpUriRequset = requestBuilder.build();
        try {
            return execute(url, httpUriRequset);
        } catch (Exception e) {
            httpUriRequset.abort();
            logger.error("Http post protobuf failed:"+url, e);
        }
        return null;
    }
    
    private static HttpEntity execute(String url, HttpUriRequest httpUriRequset) throws ClientProtocolException, IOException{

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        CloseableHttpResponse httpResponse = httpClient.execute(httpUriRequset);
        StatusLine httpStatus = httpResponse.getStatusLine();
        if(httpStatus.getStatusCode() != 200){
            if(httpResponse != null){
                EntityUtils.consume(httpResponse.getEntity());
                httpResponse.close();
            }
        }
        return httpResponse.getEntity();
    }
    
}

客户端

package com.yung.ad.work;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.protobuf.ByteString;
import com.yung.ad.baidu.proto.Ad;
import com.yung.ad.baidu.proto.Device;
import com.yung.ad.baidu.proto.MaterialMeta;
import com.yung.ad.baidu.proto.Network;
import com.yung.ad.baidu.proto.Network.ConnectionType;
import com.yung.ad.baidu.proto.Network.OperatorType;
import com.yung.ad.baidu.proto.OsType;
import com.yung.ad.baidu.proto.Size;
import com.yung.ad.baidu.proto.SlotInfo;
import com.yung.ad.baidu.proto.TsApiRequest;
import com.yung.ad.baidu.proto.TsApiResponse;
import com.yung.ad.baidu.proto.UdId;
import com.yung.ad.baidu.proto.UdIdType;
import com.yung.ad.baidu.proto.Version;
import com.yung.ad.biz.service.BaiduPolyPanelOrderService;
import com.yung.ad.biz.service.DeviceAdDetailService;
import com.yung.ad.biz.service.DeviceAdService;
import com.yung.ad.biz.service.DeviceAdSiteWhiteService;
import com.yung.ad.biz.service.DeviceResourceService;
import com.yung.ad.biz.service.LocationContrastService;
import com.yung.ad.biz.service.SiteEquipmentService;
import com.yung.ad.common.emums.IsValidEnum;
import com.yung.ad.common.emums.OrderStatusEnum;
import com.yung.ad.common.emums.ResourceTypeEnum;
import com.yung.ad.common.emums.SourceTypeEnum;
import com.yung.ad.integration.dto.BaiduPolyPanelDeviceDTO;
import com.yung.ad.integration.dto.BaiduPolyPanelOrder;
import com.yung.ad.integration.dto.DeviceAd;
import com.yung.ad.integration.dto.DeviceAdDetail;
import com.yung.ad.integration.dto.DeviceResource;
import com.yung.ad.integration.dto.LocationContrast;
import com.yung.ad.integration.dto.SiteEquipment;
import com.yung.ad.util.AppConstants;
import com.yung.ad.util.DateUtil;
import com.yung.ad.util.ErrorStatus;
import com.yung.ad.util.FileUpload;
import com.yung.ad.util.ProtoUtils;

/**
 * 请求百度聚屏接口
 */

@Component
public class BaiduPolyPanelWorker{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private DeviceAdSiteWhiteService deviceAdSiteWhiteService;
    @Autowired
    private SiteEquipmentService siteEquipmentService;
    @Autowired
    private BaiduPolyPanelOrderService baiduPolyPanelOrderService;
    @Autowired
    private LocationContrastService locationContrastService;
    @Autowired
    private DeviceResourceService deviceResourceService;
    @Autowired
    private DeviceAdService deviceAdService;
    @Autowired
    private DeviceAdDetailService deviceAdDetailService;
    
    @Value("${baidu.locationId}")
    private String baiduLocationId;
    @Value("${baiduPolyPanel.appad.file.path}")
    private String fileRoute;
    @Value("${opmp.appad.file.view.path}")
    private String ygcorePath;
    @Value("${baidu}")
    private String baidu;
    
    //网点设备参数id
    private final static Long siteEquipmentId = 1L;
    
    public BaiduPolyPanelDeviceDTO getBaiduDevice(Integer siteId, Long locationId, String businessNumber){
        BaiduPolyPanelDeviceDTO deviceDTO = null;
        try {
            //查询坑位是否是合作坑位
            if(!baiduLocationId.contains(locationId.toString())){
                logger.error("不在合作广告刊位中,坑位id:{}", locationId);
                return null;
            }
            /* 1.查询是否是网点白名单 */
            boolean matcherSiteWhite = deviceAdSiteWhiteService.isMatcherSiteWhite(siteId);
            if(!matcherSiteWhite){
                logger.error("不在网点白名单中,网点id:{}", siteId);
                return null;
            }
            /* 2.查询网点设备参数表数据 */
            SiteEquipment siteEquipment = siteEquipmentService.querySiteEquipment(siteEquipmentId);
            if(null == siteEquipment){
                logger.error("requestBaiduPolyPane SiteEquipment is null !");
                return null;
            }
            BaiduPolyPanelOrder order = null;
            //查询是否有该订单
            order = baiduPolyPanelOrderService.selectByBusinessNumber(businessNumber);
            if(null == order){
                /* 
                 * 3.拼装参数请求百度聚屏 
                 */
                //资源方 id(根据这个id去查location_contrast表取external_location)
                LocationContrast LocationContrast = locationContrastService.selectByLocation(locationId);
                //广告位ID
                String adslotId = LocationContrast.getExternalLocation();
                //资源 ID
                String appId = AppConstants.BAIDUPOLYPANEL_APPID;
                //protobuf 对象设置
                TsApiRequest tsApiBean = requsetInterface(siteEquipment, siteId, appId, adslotId);    
                //protobuf序列化请求百度聚屏接口返回
                TsApiResponse tsApiResponse = requestBaiduPolyPanel(tsApiBean);
                /* 
                 * 4.生成百度聚屏订单
                 */
                //设置订单Bean
                order = assignmentBaiduPolyPanelOrder(siteId, siteEquipment.getId(), businessNumber, appId, adslotId, tsApiResponse);
                //生成订单
                Integer baiduPolyPanelOrder = baiduPolyPanelOrderService.createBaiduPolyPanelOrder(order);
                if(baiduPolyPanelOrder <0){
                    logger.error("requestBaiduPolyPane generate order fail !");
                    return null;
                }
            }
            /* 
             * 5.根据返回的MD5值查询素材,无素材上传素材
             */
            DeviceResource deviceResource = deviceResourceService.selectByMd5(order.getMaterialMd5());
            if(null == deviceResource){
                //下载资产,上传到服务器(重试两次,如果再失败,返回无广告),***现只下载广告图片***
                String imageSrc = order.getImageSrc();
                if(StringUtils.isBlank(imageSrc)){
                    logger.error("requestBaiduPolyPane imageSrc is null !");
                    return null;
                }
                String fileName = FileDownloadUpload(imageSrc);
                if(StringUtils.isBlank(fileName)){
                    logger.error("requestBaiduPolyPane pictureUrl is fail !");
                    return null;
                }
                deviceResource = assignmentResource(order, fileName);
                //插入终端素材
                deviceResourceService.insertSelective(deviceResource);
            }
            /* 
             * 6.插入终端广告和终端广告详情表
             */
            Long detailID = createDeviceAdAndDetail(order, siteId, deviceResource.getId(), locationId);
            /* 
             * 7.返回 终端获取百度聚屏(TCP:0x4B)对象
             */
            deviceDTO = assignmentResultDevice(detailID, locationId, deviceResource);
        } catch (Exception e) {
            logger.error(ErrorStatus.SERVICE_ERROR.getErrorMsg() + ":" + ExceptionUtils.getStackTrace(e));
        }
        return deviceDTO;
    }

    //设置百度聚屏返回给终端接口
    private BaiduPolyPanelDeviceDTO assignmentResultDevice(Long detailID, Long locationId, DeviceResource deviceResource){
        DeviceAdDetail deviceAdDetail = deviceAdDetailService.selectByPrimaryKey(detailID);
        if(null == deviceAdDetail){
            logger.error("requestBaiduPolyPane deviceAdDetail is null, detailID:{}",detailID);
        }
        DeviceAd deviceAd = deviceAdService.selectByPrimaryKey(deviceAdDetail.getDeviceAdId());
        BaiduPolyPanelDeviceDTO deviceDTO = new BaiduPolyPanelDeviceDTO();
        deviceDTO.setDetailId(detailID);
        deviceDTO.setLocation(locationId);
        deviceDTO.setResourceType(0);
        deviceDTO.setResourceName(deviceResource.getName());
        deviceDTO.setDownloadPath1(ygcorePath+baidu+deviceResource.getName());
        deviceDTO.setMd51(deviceResource.getMd5());
        deviceDTO.setSize1(Long.parseLong(deviceResource.getSize())*1024+"");
        deviceDTO.setDownloadPath2("");
        deviceDTO.setMd52("");
        deviceDTO.setSize2("0");
        deviceDTO.setStartTime(deviceAd.getStartTime().getTime()+"");
        deviceDTO.setEndTime(deviceAd.getEndTime().getTime()+"");
        deviceDTO.setPlayNum(AppConstants.BAIDUPOLYPANEL_PLAYNUM);
        deviceDTO.setPlayDuration(AppConstants.BAIDUPOLYPANEL_PLAYDURATION);
        return deviceDTO;
    }
    
    
    //protobuf 对象设置
    private TsApiRequest requsetInterface(SiteEquipment siteEquipment, Integer siteId, String appId, String adslotId){
        Long t = System.currentTimeMillis();
        //request
        TsApiRequest.Builder request = TsApiRequest.newBuilder();
        request.setRequestId(ByteString.copyFromUtf8(DateUtil.getOrderNo(siteId+"")));
        //资源方 id
        request.setAppId(ByteString.copyFromUtf8(appId));
        ////版本号 api_version
        Version.Builder apiVersion = Version.newBuilder();
        apiVersion.setMajor(AppConstants.BAIDUPOLYPANEL_API_VERSION);
        request.setApiVersion(apiVersion);
        //广告位参数slot
        SlotInfo.Builder slot = SlotInfo.newBuilder();
        //广告位 ID
        slot.setAdslotId(ByteString.copyFromUtf8(adslotId));
        request.setSlot(slot);
        //device
        Device.Builder device = Device.newBuilder();
        //os_type OsType.IOS 
        device.setOsType(OsType.valueOf(Integer.parseInt(siteEquipment.getOsType())));    //操作系统
        device.setVendor(ByteString.copyFromUtf8(siteEquipment.getVendor()));            //设备厂商
        device.setModel(ByteString.copyFromUtf8(siteEquipment.getModel()));                //机型
        //设备参数udid
        UdId.Builder udid = UdId.newBuilder();
        //id_type UdIdType.MEDIA_ID
        udid.setIdType(UdIdType.valueOf(AppConstants.BAIDUPOLYPANEL_UDIDTYPE));    //设备 类型    
        //设备id, "0010010028"     
        udid.setId(ByteString.copyFromUtf8(siteId+""));    //设备id(网点id)
        device.setUdid(udid);
        //操作系统版本os_version
        Version.Builder osVersion = Version.newBuilder();
        osVersion.setMajor(AppConstants.BAIDUPOLYPANEL_OSVERSION);
        device.setOsVersion(osVersion);
        //设备屏幕尺寸screen_size
        Size.Builder screenSize = Size.newBuilder();
        screenSize.setWidth(AppConstants.BAIDUPOLYPANEL_SCREEN_WIDTH);
        screenSize.setHeight(AppConstants.BAIDUPOLYPANEL_SCREEN_HEIGHT);
        device.setScreenSize(screenSize);
        request.setDevice(device);
        
        //移动网络参数network
        Network.Builder network = Network.newBuilder();
        network.setConnectionType(ConnectionType.valueOf(AppConstants.BAIDUPOLYPANEL_CONNECTIONTYPE));        //网络类型
        network.setOperatorType(OperatorType.valueOf(AppConstants.BAIDUPOLYPANEL_OPERATORTYPE));            //运营商ID
        network.setIpv4(ByteString.copyFromUtf8(siteEquipment.getIpv4()));                                    //IPv4 地址
        request.setNetwork(network);
        logger.info("BaiduPolyPanel 拼装参数耗时={}",System.currentTimeMillis()-t +"ms");
        return request.build();
    }
    
    //protobuf序列化请求百度聚屏接口
    private TsApiResponse requestBaiduPolyPanel(TsApiRequest tsApiRequest) throws Exception{
        Long t1 = System.currentTimeMillis();
        //序列化
        byte[] response = ProtoUtils.post(AppConstants.BAIDUPOLYPANEL_URL, tsApiRequest.toByteArray());
        logger.info("请求百度聚屏接口耗时={}",System.currentTimeMillis()-t1 +"ms");
        if(response.length <= 0){
            logger.error("response failed, content is empty !");
            return null;
        }
        //反序列化
        TsApiResponse apiResponse = TsApiResponse.parseFrom(response);
        return apiResponse;
    }
    
    //设置百度聚屏订单
    private BaiduPolyPanelOrder assignmentBaiduPolyPanelOrder(Integer siteId, Long siteEquipmentId, String businessNumber, String appId, String adslotId, TsApiResponse tsApiResponse){
        BaiduPolyPanelOrder dto = new BaiduPolyPanelOrder();
        Date date = new Date();
        dto.setSiteId(siteId);                                            //网点id,关联网点基础表
        dto.setSiteEquipmentId(siteEquipmentId.intValue());                //网点设备参数主键Id,关联网点设备参数表
        dto.setOrderStatus(OrderStatusEnum.PLACE_AN_ORDER.getStatus());    //订单状态(0:下单中,  1: 订单完成,2:订单异常)
        dto.setBusinessNumber(businessNumber);                            //业务流水,防止重复插入
        dto.setRequestId(tsApiResponse.getRequestId().toStringUtf8());         //广告请求Id    51244d5d88246936ccdf69a65e84b929
        dto.setErrorCode(tsApiResponse.getErrorCode()+"");                //错误码
        dto.setApiVersion(AppConstants.BAIDUPOLYPANEL_API_VERSION+"");    //接口版本 (初始版本为 6.0.0)
        dto.setAppId(appId);                                            //资源方 id    b45f78ff
        dto.setAdslotId(adslotId);                                        //广告位 ID    4744335
        Integer expirationTime = tsApiResponse.getExpirationTime();
        dto.setExpirationTime(DateUtil.getDateByLong(expirationTime.longValue()));                //广告清单过期时间戳(单位秒。清单过期后展现无效)
        dto.setSearchKey(tsApiResponse.getSearchKey().toStringUtf8());                             //广告请求 ID(百度)(当次请求百度生成的唯一标识 ID)
        dto.setJpAdtext(tsApiResponse.getJpAdtext().toStringUtf8());                            //(广告)图标
        dto.setJpAdlogo(tsApiResponse.getJpAdlogo().toStringUtf8());                            //(熊掌)图标
        //AdsList.get(0)
        Ad ad = tsApiResponse.getAdsList().get(0);
        dto.setAds(ad.toString());                                              //应答广告清单
        dto.setAdKey(ad.getAdKey().toStringUtf8());                                 //广告签名(广告创意的唯一标识)
        dto.setWinNoticeUrl(ad.getWinNoticeUrl(0).toStringUtf8());                 //展现日志 URL 列表(get 方法请求此 url,进行上报要求在 15min 内)
        dto.setThirdMonitorUrl(ad.getThirdMonitorUrl(0).toStringUtf8());        //第三方监控地址(get 方法请求此 url,进行上报要求在 15min 内)
        //getMaterialMetas(0)
        MaterialMeta materialMetas = ad.getMaterialMetas(0);
        dto.setMaterialMetas(materialMetas.toString());                         //广告元数据组
        dto.setMaterialType(materialMetas.getMaterialType().name());        //创意类型(物料类型 图片,视频)
        dto.setImageSrc(materialMetas.getImageSrc(0) == null ? "" : materialMetas.getImageSrc(0).toStringUtf8());    //广告图片地址
//        dto.setVideoUrl(materialMetas.getVideoUrl().toStringUtf8());        //广告视频物料地址 :http://jpaccess.baidu.com/material/e3fa9a2847602611513671827.mp4
//        dto.setVideoDuration(materialMetas.getVideoDuration()+"");            //广告视频物料时长
        dto.setMaterialWidth(materialMetas.getMaterialWidth()+"");            //物料的宽度
        dto.setMaterialHeight(materialMetas.getMaterialHeight()+"");        //物料的高度
        dto.setMaterialSize(materialMetas.getMaterialSize()*1024+"");            //物料文件大小
        dto.setMaterialMd5(materialMetas.getMaterialMd5().toStringUtf8());    //物料 md5
        dto.setSubmitTime(date);                                            //提交时间
        dto.setIsValid(IsValidEnum.VALID.getStatusCode());                    //是否删除(1 有效 0 无效)
        dto.setCreateUser(AppConstants.SYSTEM_USER);                        //创建人
        dto.setCreateTime(date);                                            //创建时间
        dto.setUpdateUser(AppConstants.SYSTEM_USER);                        //修改人
        return dto;
    }
    
    //下载资产,上传到服务器(重试两次,如果再失败,返回无广告)
    private String FileDownloadUpload(String pictureUrl){
        int i = 2;
        String[] split = pictureUrl.split("\\.");
        String format = split[split.length-1];
        while (i > 0) {
            try {
                //fileRoute
//                File c = new File("D:/data/");
                String fileName = DateUtil.getRandomFileName()+"."+format;    //文件名+.文件格式 , 例:a.jpg
                String htmlPicture = FileUpload.getHtmlPicture(pictureUrl, fileRoute, fileName);
                if(StringUtils.isNotBlank(htmlPicture)){
                    return fileName;
                }
            } catch (Exception e) {
                logger.info("FileUpload is error, pictureUrl={}", pictureUrl, e);
            }
        }
        return null;
    }
    
    //设置终端素材表
    private DeviceResource assignmentResource(BaiduPolyPanelOrder order, String fileName){
        DeviceResource deviceResource = new DeviceResource();
        deviceResource.setType(ResourceTypeEnum.PICTURE.getType());
        deviceResource.setTag(SourceTypeEnum.BAIDU_POLY_PANEL.getMsg());
        deviceResource.setSize(order.getMaterialSize());
        deviceResource.setSource(SourceTypeEnum.BAIDU_POLY_PANEL.getType());
        deviceResource.setName(fileName);
        deviceResource.setResolution(order.getMaterialWidth()+"*"+order.getMaterialHeight());
        deviceResource.setMd5(order.getMaterialMd5());
//        deviceResource.setResourceUrl(ygcorePath+deviceAdDir+fileName);
        deviceResource.setResourceUrl(fileRoute+fileName);
        deviceResource.setSubmitTime(new Date());
        deviceResource.setIsValid(IsValidEnum.VALID.getStatusCode());
        deviceResource.setCreateUser(AppConstants.SYSTEM_USER);
        deviceResource.setUpdateUser(AppConstants.SYSTEM_USER);
        return deviceResource;
    }
    
    //插入终端广告主表和终端广告详情表
    @Transactional
    private Long createDeviceAdAndDetail(BaiduPolyPanelOrder order, Integer siteId, Long deviceResourceId, Long locationId){
        DeviceAd deviceAd = assignmentDeviceAd(order);
        deviceAdService.insertSelective(deviceAd);
        DeviceAdDetail deviceAdDetail = assignmentDeviceAdDetail(siteId, deviceAd.getId(), deviceResourceId, locationId);
        deviceAdDetailService.insertSelective(deviceAdDetail);
        return deviceAdDetail.getId();
    }
    //设置终端广告表
    private DeviceAd assignmentDeviceAd(BaiduPolyPanelOrder order){
        DeviceAd deviceAd = new DeviceAd();
        deviceAd.setRequestId(order.getRequestId());
        deviceAd.setName(SourceTypeEnum.BAIDU_POLY_PANEL.getMsg());
        deviceAd.setType(ResourceTypeEnum.PICTURE.getType());
        deviceAd.setSource(SourceTypeEnum.BAIDU_POLY_PANEL.getType());
        deviceAd.setStartTime(order.getSubmitTime());
        deviceAd.setEndTime(order.getExpirationTime());
        deviceAd.setStatus(1);    //广告状态:1:上刊中,2:下刊中
        deviceAd.setSubmitTime(new Date());
        deviceAd.setIsValid(IsValidEnum.VALID.getStatusCode());
        deviceAd.setCreateUser(AppConstants.SYSTEM_USER);
        deviceAd.setUpdateUser(AppConstants.SYSTEM_USER);
        return deviceAd;
    }
    //设置终端广告详情表
    private DeviceAdDetail assignmentDeviceAdDetail(Integer siteId, Long deviceAdId, Long deviceResourceId, Long locationId){
        DeviceAdDetail detail = new DeviceAdDetail();
        detail.setDeviceAdId(deviceAdId);        //终端广告id,终端广告
        detail.setSiteId(siteId.longValue());
        detail.setDeviceResourceId(deviceResourceId);    //终端素材id,关联终端素材表
        detail.setDeviceAdLocationId(locationId);        //坑位id,关联终端广告坑位表
        detail.setIsValid(IsValidEnum.VALID.getStatusCode());
        detail.setCreateUser(AppConstants.SYSTEM_USER);
        detail.setUpdateUser(AppConstants.SYSTEM_USER);
        return detail;
    }
    
}

 

标签:java,ad,protobuffer,private,org,import,post,com,yung
来源: https://www.cnblogs.com/zfzf1/p/10599106.html