liuxiaolong
2019-05-06 a7bed6b4cfecd61ec153818945f982c5bb796b98
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
package com.cloud.attendance.filter;
 
import com.alibaba.fastjson.JSONObject;
import com.cloud.attendance.utils.EnumStr;
import com.cloud.model.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
@Slf4j
@Component
@WebFilter(urlPatterns = "/*", filterName = "loginFilter")
public class LoginDataFilter implements Filter {
 
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private EnumStr enumStr;
 
    private static final Pattern QUERY_PARAM_PATTREN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String url = req.getRequestURI();
 
        if (url.startsWith("/loginData")) {
            Map<String, String[]> parMap = req.getParameterMap();
 
            Enumeration<String> names1 = req.getParameterNames();
 
            Set<String> set = parMap.keySet();
            MultiValueMap<String, String> mulMap = new LinkedMultiValueMap<>();
            for (String key : parMap.keySet()) {
                String[] names = parMap.get(key);
                for (int i = 0; i < names.length; i++) {
                    mulMap.add(key, names[i]);
                }
            }
            log.info(mulMap + "mulMap");
            String method = req.getMethod();
            log.info(method + "请求方式");
            HttpHeaders headers = new HttpHeaders();
            String body = null;
            String auth = req.getHeader("Authorization");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//            headers.add("content-type", req.getHeader("content-type"));
            if (auth != null) {
                mulMap.add("access_token", auth.substring(7));
                headers.add("Authorization", auth);
            }
//            url = "http://"+ req.getServerName() +":"+enumStr.getUserHTTP_PORT()+"/data"+ url.substring(10) ;
            url = "http://" + enumStr.getUserHOSTNAME() + ":" + enumStr.getUserHTTP_PORT() + "/data" + url.substring(10);
            log.info(url + "查询url");
            HttpEntity<MultiValueMap> reqEntity = new HttpEntity<MultiValueMap>(mulMap, headers);
            if ("get".equalsIgnoreCase(method)) {
                body = restTemplate.getForObject(expandURL(url, mulMap), String.class, mulMap);
//               body =restTemplate.exchange(url, HttpMethod.GET, reqEntity,String.class).getBody();
            } else if ("post".equalsIgnoreCase(method)) {
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                body = restTemplate.postForEntity(url, reqEntity, String.class).getBody();
            } else if ("put".equalsIgnoreCase(method)) {
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                ServletInputStream inputStream = req.getInputStream();
                String str = IOUtils.toString(inputStream);
               log.info("put inputstream获取发送数据:"+str);
                StringBuilder sb = new StringBuilder();
                if (StringUtils.isBlank(str)){
                    for (String key : mulMap.keySet()) {
                        List<String> values = mulMap.get(key);
                        for (String value : values){
                          sb.append("&"+key+"="+value);
                        }
                    }
                   if (sb.length() > 0)str = sb.substring(1);
                }
                log.info("put request getParamer获取发送数据:"+str);
                HttpEntity<String> entity = new HttpEntity<>(str, headers);
                ResponseEntity<String> resultEntity = null;
                try {
                    resultEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);
                    body = resultEntity.getBody();
                } catch (HttpClientErrorException e) {
                    String responseBodyAsString = e.getResponseBodyAsString();
                    body = responseBodyAsString;
//                    e.printStackTrace();
                }catch (HttpServerErrorException e) {
                    String responseBodyAsString = e.getResponseBodyAsString();
                    body = responseBodyAsString;
//                    e.printStackTrace();
                }catch (Exception e){
                    body = JSONObject.toJSONString(Result.error(e));
                    e.printStackTrace();
                }
//               log.info("put返回数据:"+body);
            }
            log.info(body + "返回内容");
            if (body != null) {
                resp.setContentType("application/json;charset=utf-8");
                resp.setStatus(200);
                PrintWriter pw = resp.getWriter();
                pw.write(body);
                pw.close();
            }
        } else if (url.startsWith("/httpImage")) {
            log.info(url + "图片 跳转");
            log.info(enumStr.getHttpImgUrl() + url.substring(11) + "图片 装换 跳转");
            resp.sendRedirect(enumStr.getHttpImgUrl() + url.substring(11));
            resp.setHeader("Access-Control-Allow-Origin", "*");
            return;
        } else {
            log.info(url + "其他url 跳转");
            fc.doFilter(request, response);
        }
    }
 
    // 添加url
    private static String expandURL(String url, MultiValueMap<String, String> map) {
        Matcher mc = QUERY_PARAM_PATTREN.matcher(url);
        StringBuilder sb = new StringBuilder(url);
        if (!mc.find()) {
            sb.append("&");
        } else {
            sb.append("?");
        }
        Set<String> keys = map.keySet();
        for (String key : keys) {
            List<String> value = map.get(key);
            for (String val : value) {
                sb.append(key).append("=").append(val).append("&");  // .append("}")
            }
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
 
    @Override
    public void destroy() {
 
    }
}