• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

trydofor / professional-wings / #133

28 Jan 2025 03:45AM UTC coverage: 63.721% (+0.2%) from 63.497%
#133

push

trydofor
🐍 happy lunar snake year #308

14 of 14 new or added lines in 2 files covered. (100.0%)

129 existing lines in 8 files now uncovered.

12973 of 20359 relevant lines covered (63.72%)

0.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

14.53
/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/servlet/request/RequestHelper.java
1
package pro.fessional.wings.slardar.servlet.request;
2

3
import jakarta.servlet.RequestDispatcher;
4
import jakarta.servlet.ServletRequest;
5
import jakarta.servlet.http.Cookie;
6
import jakarta.servlet.http.HttpServletRequest;
7
import lombok.SneakyThrows;
8
import org.apache.commons.lang3.StringUtils;
9
import org.jetbrains.annotations.Contract;
10
import org.jetbrains.annotations.NotNull;
11
import org.jetbrains.annotations.Nullable;
12
import org.springframework.context.i18n.LocaleContext;
13
import org.springframework.context.i18n.LocaleContextHolder;
14
import org.springframework.context.i18n.TimeZoneAwareLocaleContext;
15
import pro.fessional.mirana.cast.TypedCastUtil;
16
import pro.fessional.mirana.data.Null;
17
import pro.fessional.mirana.text.Wildcard;
18
import pro.fessional.wings.slardar.context.TerminalContext;
19
import pro.fessional.wings.slardar.servlet.stream.ReuseStreamRequestWrapper;
20

21
import java.io.BufferedReader;
22
import java.io.InputStream;
23
import java.util.ArrayList;
24
import java.util.Arrays;
25
import java.util.Collections;
26
import java.util.Enumeration;
27
import java.util.HashMap;
28
import java.util.LinkedHashSet;
29
import java.util.Locale;
30
import java.util.Map;
31
import java.util.Set;
32
import java.util.TimeZone;
33

34
import static pro.fessional.wings.slardar.constants.SlardarServletConst.AttrI18nContext;
35

36
/**
37
 * Type-safe to get the value in the request.
38
 *
39
 * @author trydofor
40
 * @since 2019-07-03
41
 */
UNCOV
42
public class RequestHelper {
×
43

44
    @Contract("_,true->!null")
45
    public static Locale getLocale(@NotNull HttpServletRequest request, boolean nonnull) {
46
        Locale locale = null;
1✔
47
        Object obj = request.getAttribute(AttrI18nContext.value);
1✔
48
        if (obj instanceof LocaleContext alc) {
1✔
49
            locale = alc.getLocale();
1✔
50
        }
51
        if (locale == null && nonnull) {
1✔
UNCOV
52
            locale = LocaleContextHolder.getLocale();
×
53
//            locale = TerminalContext.defaultLocale();
54
        }
55
        return locale;
1✔
56
    }
57

58
    @Contract("_,true->!null")
59
    public static TimeZone getTimeZone(@NotNull HttpServletRequest request, boolean nonnull) {
UNCOV
60
        TimeZone timeZone = null;
×
UNCOV
61
        Object obj = request.getAttribute(AttrI18nContext.value);
×
UNCOV
62
        if (obj instanceof TimeZoneAwareLocaleContext alc) {
×
UNCOV
63
            timeZone = alc.getTimeZone();
×
64
        }
65
        if (timeZone == null && nonnull) {
×
UNCOV
66
            timeZone = TerminalContext.defaultTimeZone();
×
67
        }
UNCOV
68
        return timeZone;
×
69
    }
70

71
    @Nullable
72
    public static String getCookieValue(@NotNull HttpServletRequest request, String name) {
73
        final Cookie[] cookies = request.getCookies();
1✔
74
        if (cookies == null) return null;
1✔
75
        for (Cookie ck : cookies) {
1✔
76
            if (ck.getName().equals(name)) return ck.getValue();
1✔
77
        }
UNCOV
78
        return null;
×
79
    }
80

81
    @NotNull
82
    public static Map<String, String> mapCookieValue(@NotNull HttpServletRequest request) {
83
        final Cookie[] cookies = request.getCookies();
×
84
        if (cookies == null || cookies.length == 0) return Collections.emptyMap();
×
85
        HashMap<String, String> map = new HashMap<>();
×
86
        for (Cookie ck : cookies) {
×
UNCOV
87
            map.put(ck.getName(), ck.getValue());
×
88
        }
UNCOV
89
        return map;
×
90
    }
91

92
    @NotNull
93
    public static Map<String, Set<String>> allCookieValue(@NotNull HttpServletRequest request) {
94
        final Cookie[] cookies = request.getCookies();
×
UNCOV
95
        if (cookies == null || cookies.length == 0) return Collections.emptyMap();
×
UNCOV
96
        HashMap<String, Set<String>> map = new HashMap<>();
×
UNCOV
97
        for (Cookie ck : cookies) {
×
UNCOV
98
            final Set<String> set = map.computeIfAbsent(ck.getName(), k -> new LinkedHashSet<>());
×
99
            set.add(ck.getValue());
×
100
        }
UNCOV
101
        return map;
×
102
    }
103

104
    @Nullable
105
    public static <T> T getAttribute(@NotNull HttpServletRequest request, String name, Class<T> claz) {
UNCOV
106
        Object obj = request.getAttribute(name);
×
UNCOV
107
        return TypedCastUtil.castObject(obj, claz);
×
108
    }
109

110
    @Nullable
111
    public static <T> T getAttribute(@NotNull HttpServletRequest request, String name) {
112
        Object obj = request.getAttribute(name);
×
113
        return TypedCastUtil.castObject(obj, null);
×
114
    }
115

116
    @Nullable
117
    public static <T> T getAttributeIgnoreCase(HttpServletRequest request, String name) {
UNCOV
118
        return getAttributeIgnoreCase(request, name, null);
×
119
    }
120

121
    @Nullable
122
    public static <T> T getAttributeIgnoreCase(HttpServletRequest request, String name, Class<T> claz) {
UNCOV
123
        if (request == null || name == null) return null;
×
124

UNCOV
125
        Enumeration<String> names = request.getAttributeNames();
×
UNCOV
126
        while (names != null && names.hasMoreElements()) {
×
127
            String s = names.nextElement();
×
128
            if (name.equalsIgnoreCase(s)) {
×
129
                name = s;
×
130
                break;
×
131
            }
UNCOV
132
        }
×
133

UNCOV
134
        Object obj = request.getAttribute(name);
×
UNCOV
135
        return TypedCastUtil.castObject(obj, claz);
×
136
    }
137

138
    @NotNull
139
    public static String getRemoteIp(@NotNull HttpServletRequest request, String... header) {
UNCOV
140
        if (header != null) {
×
UNCOV
141
            for (String h : header) {
×
UNCOV
142
                String ip = request.getHeader(h);
×
UNCOV
143
                if (ip != null) return ip;
×
144
            }
145
        }
146
        return request.getRemoteAddr();
×
147
    }
148

149
    /**
150
     * Case-insensitive matching of URI with path, support for wildcard
151
     *
152
     * @param req  the request
153
     * @param path path pattern, return false if null or empty
154
     * @return whether matches
155
     */
156
    public static boolean matchIgnoreCase(@NotNull HttpServletRequest req, String path) {
UNCOV
157
        if (path == null || path.isEmpty()) return false;
×
158

UNCOV
159
        String uri = req.getRequestURI();
×
UNCOV
160
        int idx = uri.indexOf(';');
×
UNCOV
161
        if (idx > 0) {
×
UNCOV
162
            uri = uri.substring(0, idx);
×
163
        }
164

165
        return Wildcard.match(true, uri, req.getContextPath(), path);
×
166
    }
167

168
    /**
169
     * Case-insensitive matching of URI with any of path, support for wildcard
170
     *
171
     * @param req  the request
172
     * @param path path patterns, return false if null or empty
173
     * @return whether matches any
174
     */
175
    public static boolean matchIgnoreCase(@NotNull HttpServletRequest req, String... path) {
UNCOV
176
        if (path == null) return false;
×
177

178
        String uri = req.getRequestURI();
×
UNCOV
179
        int idx = uri.indexOf(';');
×
UNCOV
180
        if (idx > 0) {
×
UNCOV
181
            uri = uri.substring(0, idx);
×
182
        }
183

184
        for (String s : path) {
×
UNCOV
185
            if (s == null) continue;
×
UNCOV
186
            if (Wildcard.match(true, uri, req.getContextPath(), s)) {
×
UNCOV
187
                return true;
×
188
            }
189
        }
190

191
        return false;
×
192
    }
193

194
    @Nullable
195
    public static String getParameter(Map<String, String[]> param, String name) {
196
        String[] vals = param.get(name);
×
UNCOV
197
        return (vals == null || vals.length == 0) ? null : vals[0];
×
198
    }
199

200
    @NotNull
201
    public static String[] getParameters(Map<String, String[]> param, String name) {
202
        final String[] arr = param.get(name);
1✔
203
        if (arr == null) {
1✔
UNCOV
204
            final ArrayList<String> list = new ArrayList<>();
×
UNCOV
205
            final String prefix = name + '[';
×
UNCOV
206
            for (Map.Entry<String, String[]> en : param.entrySet()) {
×
UNCOV
207
                final String n = en.getKey();
×
UNCOV
208
                if (n.startsWith(prefix) && n.endsWith("]")) {
×
209
                    list.addAll(Arrays.asList(en.getValue()));
×
210
                }
211
            }
×
212
            return list.toArray(Null.StrArr);
×
213
        }
214
        else {
215
            return arr;
1✔
216
        }
217
    }
218

219
    @NotNull
220
    public static Map<String, String> getParameter(Map<String, String[]> param) {
221

UNCOV
222
        if (param == null) return Collections.emptyMap();
×
223

UNCOV
224
        HashMap<String, String> rst = new HashMap<>(param.size());
×
UNCOV
225
        for (Map.Entry<String, String[]> entry : param.entrySet()) {
×
UNCOV
226
            String[] vs = entry.getValue();
×
UNCOV
227
            if (vs != null && vs.length > 0) {
×
UNCOV
228
                rst.put(entry.getKey(), vs[0]);
×
229
            }
230
        }
×
231

232
        return rst;
×
233
    }
234

235
    /**
236
     * First get `Bearer` in Header, if not found, then get `access_token` in Parameter
237
     * `Bearer` and `access_token` are case-insensitive,
238
     * if there is more than one token, take the last one.
239
     */
240
    @Nullable
241
    public static String getAccessToken(@NotNull HttpServletRequest request) {
242
        String auth = request.getHeader("Authorization");
×
243
        String token = null;
×
244
        if (auth != null) {
×
245
            String bearer = "bearer";
×
246
            int p = StringUtils.indexOfIgnoreCase(auth, bearer);
×
UNCOV
247
            if (p >= 0) {
×
248
                token = auth.substring(p + bearer.length()).trim();
×
249
            }
250
        }
251
        if (token == null) {
×
UNCOV
252
            token = request.getParameter("access_token");
×
253
        }
254

UNCOV
255
        if (token != null) {
×
UNCOV
256
            int pos = token.indexOf(",");
×
UNCOV
257
            if (pos > 0) {
×
258
                String[] tks = token.split(",");
×
UNCOV
259
                token = tks[tks.length - 1];
×
260
            }
UNCOV
261
            token = token.trim();
×
262
        }
263

264
        return token;
×
265
    }
266

267
    public static boolean isForwarding(@NotNull HttpServletRequest request) {
268
        return request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI) != null;
1✔
269
    }
270

271
    @SneakyThrows
×
272
    public static InputStream tryCircleInputStream(@NotNull ServletRequest request) {
273
        final ReuseStreamRequestWrapper inf = ReuseStreamRequestWrapper.infer(request);
1✔
274
        if (inf != null && inf.circleInputStream(true)) {
1✔
275
            return inf.getInputStream();
1✔
276
        }
UNCOV
277
        return null;
×
278
    }
279

UNCOV
280
    @SneakyThrows
×
281
    public static BufferedReader tryCircleBufferedReader(@NotNull ServletRequest request) {
UNCOV
282
        final ReuseStreamRequestWrapper inf = ReuseStreamRequestWrapper.infer(request);
×
UNCOV
283
        if (inf != null && inf.circleInputStream(true)) {
×
UNCOV
284
            return inf.getReader();
×
285
        }
UNCOV
286
        return null;
×
287
    }
288
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc