月球大数据地理空间分析展示平台-【后端】-月球后台服务
13693261870
2023-09-11 0230f23fcdeecfe14da0ade61fb3afa2822740cf
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package com.moon.server.helper;
 
import com.alibaba.fastjson.JSON;
import com.moon.server.entity.all.HttpStatus;
import com.moon.server.entity.all.ResponseMsg;
import com.moon.server.entity.all.SettingData;
import com.moon.server.entity.all.StaticData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;
 
/**
 * Web帮助类
 * @author WWW
 */
public class WebHelper {
    private final static String UNKNOWN = "unknown";
 
    private final static String COMMA = ",";
 
    private final static Log log = LogFactory.getLog(WebHelper.class);
 
    /**
     * 保留小数位
     */
    public static double round(double val, double size) {
        double power = Math.pow(10.0, size);
 
        return Math.round(val * power) / power;
    }
 
    /**
     * 获取GUID
     */
    public static String getGuid() {
        return UUID.randomUUID().toString();
    }
 
    /**
     * 获取用户ip
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_VIA");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("REMOTE_ADDR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(COMMA)) {
            return ip.split(",")[0];
        }
 
        return ip;
    }
 
    /**
     * 获取当前时间的Timestamp
     */
    public static Timestamp getCurrentTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }
 
    /**
     * 获取当前时间指定分钟数后的Timestamp
     */
    public static Timestamp getTimestamp(int min) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, min);
 
        return new Timestamp(now.getTimeInMillis());
    }
 
    /**
     * 从Cookie中获取token
     */
    public static String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
 
        for (Cookie cookie : cookies) {
            switch (cookie.getName()) {
                case StaticData.TOKEN_COOKIE_KEY:
                    return cookie.getValue();
                default:
                    break;
            }
        }
 
        return null;
    }
 
    /**
     * 向Cookie中添加token
     */
    public static void saveToken2Cookie(String token, HttpServletRequest request, HttpServletResponse response) {
        // 先删除
        deleteCookies(request, response);
 
        // 再保存
        saveCookie(StaticData.TOKEN_COOKIE_KEY, token, response);
    }
 
    /**
     * 保存Cookie
     */
    public static void saveCookie(String key, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        // 设置cookie失效时间,单位为秒
        cookie.setMaxAge(SettingData.COOKIE_MAX_AGE);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        //cookie.setDomain("*")
 
        response.setHeader("P3P", "CP=CAO PSA OUR");
        response.addCookie(cookie);
    }
 
    /**
     * 删除cookie中的值
     */
    public static void deleteCookie(String cookieKey, HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (cookieKey.equalsIgnoreCase(c.getName())) {
                    c.setMaxAge(0);
                    c.setPath("/");
                    response.addCookie(c);
                }
            }
        }
    }
 
    /**
     * 删除所有Cookie
     */
    public static void deleteCookies(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                c.setMaxAge(0);
                c.setPath("/");
                response.addCookie(c);
            }
        }
    }
 
    /**
     * 根据键获取Cookie值
     */
    public static String getCookieByKey(String key, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
 
        for (Cookie c : cookies) {
            if (key.equals(c.getName())) {
                return c.getValue();
            }
        }
 
        return null;
    }
 
    /**
     * 获取Token
     */
    public static String getToken(HttpServletRequest request) {
        // 1.从url参数中,获取token
        String token = request.getParameter(StaticData.TOKEN_KEY);
 
        // 2.为空,则从header里获取
        if (token == null) {
            token = request.getHeader(StaticData.TOKEN_KEY);
        }
 
        // 3.还为空,则从cookie里获取
        if (token == null) {
            token = getTokenFromCookie(request);
        }
 
        return token;
    }
 
    /**
     * 获取Request
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 
        return servletRequestAttributes.getRequest();
    }
 
    /**
     * 获取Response
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 
        return servletRequestAttributes.getResponse();
    }
 
    /**
     * 获取Session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }
 
    /**
     * 获取真实路径
     */
    public static String getRealPath(String path) {
        HttpServletRequest req = getRequest();
        ServletContext ctx = req.getSession().getServletContext();
 
        return ctx.getRealPath("/" + path);
    }
 
    /**
     * 输出str至前端
     */
    public static boolean writeStr2Page(HttpServletResponse res, String str) {
        try {
            res.setContentType("application/json;charset=UTF-8");
            res.setHeader("Cache-Control", "no-cache");
            res.setHeader("Pragma", "No-cache");
            res.setDateHeader("Expires", 0);
 
            PrintWriter out = res.getWriter();
            out.print(str);
 
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
 
        return false;
    }
 
    /**
     * 输出json至前端
     */
    public static void writeJson2Page(HttpServletResponse res, String str) {
        String json = JSON.toJSONString(new ResponseMsg<>(HttpStatus.ERROR, str));
        writeStr2Page(res, json);
    }
 
    /**
     * 获取错误JSON
     */
    public static String getErrJson(HttpStatus status, String msg) {
        return JSON.toJSONString(new ResponseMsg<String>(status, msg));
    }
 
    /**
     * 写响应信息
     */
    public static void writeInfo(HttpStatus status, String info, HttpServletResponse res) {
        WebHelper.writeStr2Page(res, WebHelper.getErrJson(status, info));
    }
 
    /**
     * 获取随机整数
     */
    public static int getRandomInt(int min, int max) {
        return new Random().nextInt(max) % (max - min + 1) + min;
    }
 
    /**
     * 下载文件
     */
    public static void download(String file, String fileName, HttpServletResponse res) throws Exception {
        download(file, fileName, false, res);
    }
 
    /**
     * 下载文件
     *
     * @param file     文件
     * @param fileName 文件名
     * @param res      响应
     * @throws Exception 异常
     */
    public static void download(String file, String fileName, boolean inline, HttpServletResponse res) throws Exception {
        if (StringHelper.isEmpty(fileName)) {
            fileName = StringHelper.YMDHMS2_FORMAT.format(new Date());
        }
        fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        String dispose = inline ? "inline" : "attachment";
 
        // 设置响应头中文件的下载方式为附件方式,以及设置文件名
        res.setHeader("Content-Disposition", dispose + "; filename*=UTF-8''" + fileName);
        // 设置响应头的编码格式为 UTF-8
        res.setCharacterEncoding("UTF-8");
 
        // 通过response对象设置响应数据格式(如:"text/plain; charset=utf-8")
        String ext = FileHelper.getExtension(file);
        String mime = FileHelper.getMime(ext);
        res.setContentType(mime);
 
        // 通过response对象,获取到输出流
        ServletOutputStream outputStream = res.getOutputStream();
        // 定义输入流,通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(file);
 
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            // 通过输入流读取文件数据,然后通过上述的输出流写回浏览器
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
 
        // 关闭资源
        fileInputStream.close();
        outputStream.close();
    }
 
    /**
     * 执行命令
     *
     * @param cmd 命令
     */
    public static void exec(String cmd) {
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
 
    /**
     * 获取请求的参数值
     *
     * @param req 请求
     * @param key 参数名
     * @return 参数值
     */
    public static String getReqParamVal(HttpServletRequest req, String key) {
        Map<String, String[]> maps = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : maps.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(key)) {
                return null == entry.getValue() || 0 == entry.getValue().length ? null : entry.getValue()[0];
            }
        }
 
        return null;
    }
 
    /**
     * 获取请求的参数值
     *
     * @param req 请求
     * @param key 参数名
     * @return 参数值
     */
    public static String[] getReqParamVals(HttpServletRequest req, String key) {
        Map<String, String[]> maps = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : maps.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(key)) {
                return entry.getValue();
            }
        }
 
        return null;
    }
}