1
13693261870
2022-09-16 fee60c3e25fac0982f3b8cb8feea7225c4ed22f8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package com.terra.proxy.controller;
 
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.terra.proxy.bean.*;
import com.terra.proxy.config.SysTemPropertyConfig;
import com.terra.proxy.intercepter.ServiceExcelListener;
import com.terra.proxy.mapper.LogMapper;
import com.terra.proxy.properties.TerraProperties;
import com.terra.proxy.service.Impl.ServerRegisterServiceImpl;
import com.terra.proxy.util.JedisUtils;
import com.terra.proxy.util.JwtUtils;
import com.terra.proxy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
 
@RestController
@RequestMapping("/excel")
public class ExcelController {
    @Autowired
    private SysTemPropertyConfig sys;
 
    @Autowired
    private ServerRegisterServiceImpl serverRegisterService;
 
    @Autowired
    private TerraProperties properties;
 
    @Autowired
    private JwtUtils JwtUtils;
 
    @Autowired
    private LogMapper logMapper;
 
    private static String fileName = "服务注册模板Excel.xlsx";
 
    private static String fileResultName = "服务注册结果.xlsx";
    @Value("${sys.jwt.expire}")
    private Long expireSeconds;
 
    /*
     * 获取注册服务的Excel模板
     *
     * */
    @GetMapping("getExcelModle")
    public ResponseEntity getExcelModle() {
        String uploadPath = sys.getUploadPath();
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdir();
        }
        ArrayList<ServerExcelApplyEntity> userEntities = new ArrayList<>();
        userEntities.add(new ServerExcelApplyEntity());
        EasyExcel.write(uploadPath + File.separator + fileName, ServerExcelApplyEntity.class).sheet("服务注册表").doWrite(userEntities);
        return ResponseEntity.ok().body(null);
    }
 
    /*
     * 获取注册服务的Excel文件
     *
     * */
    @GetMapping("getExcel")
    public ResponseEntity getExcel(HttpServletResponse response) throws IOException {
        String uploadPath = sys.getUploadPath();
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        File file = new File(uploadPath + File.separator + fileName);
        if (file.exists() && file.canRead()) {
            fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        }
        if (null != fileInputStream) {
            fileInputStream.close();
        }
        if (null != outputStream) {
            outputStream.flush();
            outputStream.close();
        }
        return ResponseEntity.ok().body(null);
    }
 
    /*
     * 导入注册服务的Excel文件
     *
     * */
    @PostMapping("importExcel")
    public String importExcel(@RequestPart("file") MultipartFile file, HttpServletRequest req) {
        InputStream inputStream;
        List<ServerExcelApplyEntity> serverExcelEntityList;
        List<ServerExcelResultEntity> excelEntities = new ArrayList<>();
        Jedis jedis = JedisUtils.getJedis();
        try {
            inputStream = file.getInputStream();
            serverExcelEntityList = EasyExcel.read(inputStream, ServerExcelApplyEntity.class, new ServiceExcelListener()).doReadAllSync();
            //注册服务 申请token
            serverExcelEntityList.stream().forEach(ServerExcelApplyEntity -> excelEntities.add(addArcGisServer(req, ServerExcelApplyEntity, jedis)));
            returnExcel(excelEntities);
            return JSON.toJSONString(Result.ok().put("msg", "").put("data", ""));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != jedis) {
                JedisUtils.close(jedis);
            }
        }
        return "";
    }
 
    /*
     * 获取注册服务结果的Excel文件
     *
     * */
    @GetMapping("getExcelResult")
    public ResponseEntity getExcelResult(HttpServletResponse response) throws IOException {
        String uploadPath = sys.getUploadPath();
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileResultName, "utf-8"));
        File file = new File(uploadPath + File.separator + fileResultName);
        if (file.exists() && file.canRead()) {
            fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        }
        if (null != fileInputStream) {
            fileInputStream.close();
        }
        if (null != outputStream) {
            outputStream.flush();
            outputStream.close();
        }
        return ResponseEntity.ok().body(null);
    }
 
 
    private void returnExcel(List serverExcelEntityList) throws IOException {
        File file = new File(sys.getUploadPath() + File.separator + fileResultName);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        EasyExcel.write(fileOutputStream, ServerExcelResultEntity.class).sheet("服务注册结果").doWrite(serverExcelEntityList);
        fileOutputStream.close();
    }
 
    private String genToken(HttpServletRequest req, ServerExcelApplyEntity serverExcelEntity, Jedis jedis) {
        String identyinfo = serverExcelEntity.getApplySys();
        String resourceid = serverExcelEntity.getZyId().toString();
        Long expiration = serverExcelEntity.getTime();
        try {
            CustomerToken cutToken = new CustomerToken();
            cutToken.setResourceId(resourceid);
            cutToken.setUserid("0");
            cutToken.setAppUrl("");
            cutToken.setAppId("");
            cutToken.setClientIp(req.getRemoteHost());
            cutToken.setRemark(identyinfo == null ? "" : identyinfo);
            String token = expiration != null ? JwtUtils.generateToken(cutToken.toString(), expiration) : JwtUtils.generateToken(cutToken.toString(), expireSeconds);
            TokenRecord record = new TokenRecord();
            record.setApplytime(new Date());
            record.setExpiration(expiration != null ? expiration.intValue() : expireSeconds.intValue());
            record.setIdentyinfo(identyinfo);
            record.setTokeninfo(cutToken.toString());
            if (!StringUtils.isEmpty(resourceid)) {
                record.setResourceid(Integer.valueOf(resourceid));
            }
            record.setToken(token);
            record.setTokenapplyer(req.getRemoteHost());
            logMapper.saveTokenRecord(record);
            expiration = expiration != null ? expiration : expireSeconds;
            jedis.setex("zytoken:" + token, expiration.intValue(), expiration.toString());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    private ServerExcelResultEntity addArcGisServer(HttpServletRequest req, ServerExcelApplyEntity serverExcelApplyEntity, Jedis jedis) {
        if (StringUtils.isEmpty(serverExcelApplyEntity.getPubliceIs())) {
            serverExcelApplyEntity.setPubliceIs("0");
        }
        Integer isPublic = Integer.valueOf(serverExcelApplyEntity.getPubliceIs());
        ServerRgBean serverRgBean = new ServerRgBean();
        serverRgBean.setEnable(1);
        serverRgBean.setIspublic(isPublic);
        serverRgBean.setFromsys("HYJGPT");
        serverRgBean.setResourceid(serverExcelApplyEntity.getZyId());
        serverRgBean.setUrlid(null);
        serverRgBean.setContextpath(null);
        serverRgBean.setSuffix(null);
        serverRgBean.setServername(serverExcelApplyEntity.getServerName());
        serverRgBean.setServerurl(serverExcelApplyEntity.getServerUrl());
        String servername = judgeServerType(serverExcelApplyEntity.getServerUrl());
        serverRegisterService.addServer(serverRgBean);
        ServerExcelResultEntity serverExcelEntity = getServerExcelResultEntity(serverExcelApplyEntity);
        String proxyurl = new StringBuilder(properties.getProxy().getHost()).append("/arcgis/rest/services/").append(serverExcelApplyEntity.getZyId()).append("/").append(servername).toString();
        serverExcelEntity.setProxyurl(proxyurl);
        String useToken = serverExcelApplyEntity.getUseToken();
        String autoToken = serverExcelApplyEntity.getAutoToken();
        if (Objects.equals("0", useToken)) {
            return serverExcelEntity;
        }
        //生成token genToken
        String token = genToken(req, serverExcelApplyEntity, jedis);
        serverExcelEntity.setToken(token);
        //加入redis中完成自动续约
        if (Objects.equals(autoToken, "1")) {
            jedis.sadd("autoToken", token);
        }
        return serverExcelEntity;
    }
 
    private ServerExcelResultEntity getServerExcelResultEntity(ServerExcelApplyEntity serverExcelApplyEntity) {
        ServerExcelResultEntity resultEntity = new ServerExcelResultEntity();
        BeanUtil.copyProperties(serverExcelApplyEntity, resultEntity);
        return resultEntity;
    }
 
    public static String judgeServerType(String serverUrl) {
        String type = null;
        try {
            URI uri = new URI(serverUrl);
            String path = uri.getPath();
            String[] t = path.split("/");
            if (isdigit(t[t.length - 1])) {
                type = t[t.length - 2];
            } else {
                type = t[t.length - 1];
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return type;
    }
 
    public static boolean isdigit(String str) {
        return str.matches("[0-9]+");
    }
 
 
}