• java代码在阿里云函数计算中的应用


    分享一个阿里云函数计算的java应用。

    服务的功能是获取OSS中PPT模板,加载OSS中图片文件,合成PPT导出文件后,把文件回传到OSS方便下载的应用。

    移植到函数计算的目的是OSS文件都在阿里云中,服务器迁移到了腾讯云,让代码更靠近数据,方便计算。

    MAVEN配置里的build这块比较重要,把关联jar都会打包到一个jar中,这样才能上传到函数计算服务中。

     1 <build>
     2         <plugins>
     3             <plugin>
     4                 <artifactId>maven-assembly-plugin</artifactId>
     5                 <version>3.1.0</version>
     6                 <configuration>
     7                     <descriptorRefs>
     8                         <descriptorRef>jar-with-dependencies</descriptorRef>
     9                     </descriptorRefs>
    10                     <appendAssemblyId>false</appendAssemblyId> <!-- this is used for not append id to the jar name -->
    11                 </configuration>
    12                 <executions>
    13                     <execution>
    14                         <id>make-assembly</id> <!-- this is used for inheritance merges -->
    15                         <phase>package</phase> <!-- bind to the packaging phase -->
    16                         <goals>
    17                             <goal>single</goal>
    18                         </goals>
    19                     </execution>
    20                 </executions>
    21             </plugin>
    22             <plugin>
    23                 <groupId>org.apache.maven.plugins</groupId>
    24                 <artifactId>maven-compiler-plugin</artifactId>
    25                 <configuration>
    26                     <source>1.8</source>
    27                     <target>1.8</target>
    28                 </configuration>
    29             </plugin>
    30         </plugins>
    31     </build>
      1 package example;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.File;
      5 import java.io.FileInputStream;
      6 import java.io.IOException;
      7 import java.io.InputStream;
      8 import java.io.OutputStream;
      9 import java.net.URLDecoder;
     10 import java.util.List;
     11 import java.util.Map;
     12 
     13 import javax.servlet.ServletException;
     14 import javax.servlet.http.HttpServletRequest;
     15 import javax.servlet.http.HttpServletResponse;
     16 
     17 import org.apache.commons.io.FileUtils;
     18 import org.apache.commons.lang3.StringUtils;
     19 import org.apache.poi.xslf.usermodel.XMLSlideShow;
     20 
     21 import com.alibaba.fastjson.JSON;
     22 import com.alibaba.fastjson.JSONObject;
     23 import com.aliyun.fc.runtime.Context;
     24 import com.aliyun.fc.runtime.FunctionComputeLogger;
     25 import com.aliyun.fc.runtime.HttpRequestHandler;
     26 
     27 public class App2 implements HttpRequestHandler {
     28 
     29     /**
     30      * 模板默认的可变化的起始页,从这页开始插入生成的PPT
     31      */
     32     public static final String FIELD_FLAG = "#";
     33 
     34     private static final Map<String, String> POINT_MAP = BizConstants.getInnerAttributeMap();
     35 
     36     private FunctionComputeLogger logger;
     37 
     38     private String getV(HttpServletRequest request, String key) {
     39         return (String)request.getAttribute(key);
     40     }
     41 
     42     /**
     43      * 获取body中的内容
     44      * 
     45      * @param request
     46      * @return
     47      */
     48     private String getBody(HttpServletRequest request) {
     49         BufferedReader br;
     50         try {
     51             br = request.getReader();
     52             String str, wholeStr = "";
     53             while ((str = br.readLine()) != null) {
     54                 wholeStr += str;
     55             }
     56             wholeStr = URLDecoder.decode(wholeStr, "utf-8");
     57             return wholeStr;
     58         } catch (IOException e) {
     59             e.printStackTrace();
     60         }
     61         return null;
     62     }
     63 
     64     public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context)
     65         throws IOException, ServletException {
     66 
     67         logger = context.getLogger();
     68 
     69         
     70         /**
     71          * 获取客户端提交的BODY部分数据
     72          */
     73         String body = getBody(request);
     74 
     75         logger.info("body=====>" + body);
     76 
     77         /**
     78          * 解析JSON对象
     79          */
     80         JSONObject obj = JSON.parseObject(body);
     81 
     82         Integer pageSize = obj.getInteger("pageSize");
     83         String pptUrl = obj.getString("pptUrl");
     84         String pointsJson = obj.getString("points");
     85         String downloadName = obj.getString("downloadName");
     86         logger.info("pageSize=====>" + pageSize);
     87         logger.info("pptUrl=====>" + pptUrl);
     88         logger.info("downloadName=====>" + downloadName);
     89         List<Point> points = JSON.parseArray(pointsJson, Point.class);
     90         logger.info("points==size===>" + points.size());
     91 
     92         String filePath = saveExportPpt(points, pageSize, pptUrl);
     93 
     94         logger.info("filePath==========>{}" + filePath);
     95 
     96         String url = "";
     97         /**
     98          * 上传生成好的PPT文件到OSS中
     99          * 方便用户下载
    100          */
    101         if (StringUtils.isNotBlank(filePath)) {
    102             url = OssUtils.saveTempFile(filePath, downloadName);
    103         }
    104         logger.info("saveTempFile===url==>" + url);
    105 
    106         response.setStatus(200);
    107         OutputStream out = response.getOutputStream();
    108         out.write(url.getBytes());
    109         out.flush();
    110         out.close();
    111     }
    112 
    113   
    114 
    115     /**
    116      业务代码,生成PPT文件
    117      */
    118     public String saveExportPpt(List<Point> points, Integer pageSize, String pptUrl) {
    119         try {
    120             File file = File.createTempFile(System.nanoTime() + "", ".pptx");
    121             String absolutePath = file.getAbsolutePath();
    122             logger.info("file=====length===>" + file.length());
    123             return absolutePath;
    124         } catch (Exception e) {
    125             logger.info("Exception" + e.toString());
    126         }
    127         return null;
    128     }
    129 
    130     /**
    131      * 从OSS获取PPT模板,生成PPT模板类
    132      * @param pptUrl
    133      * @return
    134      */
    135     private XMLSlideShow getSlideShow(String pptUrl) {
    136         File pptFile = null;
    137         try {
    138             pptFile = File.createTempFile(System.nanoTime() + ".", StringUtils.substringAfterLast(pptUrl, "."));
    139 
    140             /**
    141              * 通过OSS SDK获取模板文件到函数计算服务器
    142              */
    143             OssUtils.getImage(pptUrl, pptFile);
    144 
    145             logger.info("pptFile==getAbsolutePath===>" + pptFile.getAbsolutePath());
    146             logger.info("pptFile==exists===>" + pptFile.exists());
    147             logger.info("pptFile==length===>" + pptFile.length());
    148 
    149         } catch (Exception e) {
    150             e.printStackTrace();
    151         }
    152         if (pptFile == null || !pptFile.exists()) {
    153             return null;
    154         }
    155         try {
    156             InputStream is = new FileInputStream(pptFile);
    157             XMLSlideShow slideShow = new XMLSlideShow(is);
    158             is.close();
    159             return slideShow;
    160         } catch (Exception e1) {
    161 
    162         }
    163         return null;
    164     }
    165 
    166     /**
    167      * 通过OSS SDK获取PPT中需要添加的图片到函数计算服务器本地
    168      */
    169     private byte[] getImage(String imageUrl) {
    170         try {
    171             File destFile = File.createTempFile("temp", "." + StringUtils.substringAfterLast(imageUrl, "."));
    172             OssUtils.getImage(imageUrl, destFile);
    173             byte[] pictureData = FileUtils.readFileToByteArray(destFile);
    174             destFile.deleteOnExit();
    175             return pictureData;
    176         } catch (Exception e) {
    177             return null;
    178         }
    179     }
    180 
    181 }
  • 相关阅读:
    【KVM系列 virt-v2v】virt-v2v过程中的报错
    大机与超级计算机的区别
    多路径 on linux
    ansible 管控 windows
    Linux启动盘
    RHCA 环境命令
    Xshell 4 连接 Ubuntu/Kali 报错 "找不到匹配的key exchange算法"
    security group & ACL
    windows powercfg
    OKD
  • 原文地址:https://www.cnblogs.com/nanahome/p/15566095.html
Copyright © 2020-2023  润新知