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

hazendaz / httpunit / 656

06 Dec 2025 09:11PM UTC coverage: 80.452% (+0.02%) from 80.435%
656

push

github

hazendaz
[maven-release-plugin] prepare for next development iteration

3213 of 4105 branches covered (78.27%)

Branch coverage included in aggregate %.

8245 of 10137 relevant lines covered (81.34%)

0.81 hits per line

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

82.64
/src/main/java/com/meterware/servletunit/ServletUnitHttpRequest.java
1
/*
2
 * MIT License
3
 *
4
 * Copyright 2011-2025 Russell Gold
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
7
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
8
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
9
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
 *
11
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions
12
 * of the Software.
13
 *
14
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
15
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
17
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18
 * DEALINGS IN THE SOFTWARE.
19
 */
20
package com.meterware.servletunit;
21

22
import com.meterware.httpunit.HttpUnitUtils;
23
import com.meterware.httpunit.WebClient;
24
import com.meterware.httpunit.WebRequest;
25

26
import java.io.BufferedReader;
27
import java.io.IOException;
28
import java.io.InputStreamReader;
29
import java.net.MalformedURLException;
30
import java.nio.charset.Charset;
31
import java.nio.charset.StandardCharsets;
32
import java.util.ArrayList;
33
import java.util.Base64;
34
import java.util.Collection;
35
import java.util.Collections;
36
import java.util.Date;
37
import java.util.Dictionary;
38
import java.util.Enumeration;
39
import java.util.Hashtable;
40
import java.util.Iterator;
41
import java.util.List;
42
import java.util.Locale;
43
import java.util.Map;
44
import java.util.StringTokenizer;
45

46
import javax.servlet.AsyncContext;
47
import javax.servlet.DispatcherType;
48
import javax.servlet.RequestDispatcher;
49
import javax.servlet.ServletContext;
50
import javax.servlet.ServletException;
51
import javax.servlet.ServletInputStream;
52
import javax.servlet.ServletRequest;
53
import javax.servlet.ServletResponse;
54
import javax.servlet.http.Cookie;
55
import javax.servlet.http.HttpServletRequest;
56
import javax.servlet.http.HttpServletResponse;
57
import javax.servlet.http.HttpSession;
58
import javax.servlet.http.HttpUpgradeHandler;
59
import javax.servlet.http.Part;
60

61
/**
62
 * The Class ServletUnitHttpRequest.
63
 */
64
class ServletUnitHttpRequest implements HttpServletRequest {
65

66
    /** The input stream. */
67
    private ServletInputStreamImpl _inputStream;
68

69
    /** The locales. */
70
    private List _locales;
71

72
    /** The protocol. */
73
    private String _protocol;
74

75
    /** The secure. */
76
    private boolean _secure;
77

78
    /** The request context. */
79
    private RequestContext _requestContext;
80

81
    /** The charset. */
82
    private String _charset;
83

84
    /** The got reader. */
85
    private boolean _gotReader;
86

87
    /** The got input stream. */
88
    private boolean _gotInputStream;
89

90
    /** The reader. */
91
    private BufferedReader _reader;
92

93
    /** The server port. */
94
    private int _serverPort;
95

96
    /** The server name. */
97
    private String _serverName;
98

99
    /**
100
     * Constructs a ServletUnitHttpRequest from a WebRequest object.
101
     *
102
     * @param servletRequest
103
     *            the servlet request
104
     * @param request
105
     *            the request
106
     * @param context
107
     *            the context
108
     * @param clientHeaders
109
     *            the client headers
110
     * @param messageBody
111
     *            the message body
112
     *
113
     * @throws MalformedURLException
114
     *             the malformed URL exception
115
     */
116
    ServletUnitHttpRequest(ServletMetaData servletRequest, WebRequest request, ServletUnitContext context,
117
            Dictionary clientHeaders, byte[] messageBody) throws MalformedURLException {
1✔
118
        if (context == null) {
1!
119
            throw new IllegalArgumentException("Context must not be null");
×
120
        }
121

122
        _servletRequest = servletRequest;
1✔
123
        _request = request;
1✔
124
        _context = context;
1✔
125
        _headers = new WebClient.HeaderDictionary();
1✔
126
        _headers.addEntries(clientHeaders);
1✔
127
        _headers.addEntries(request.getHeaders());
1✔
128
        setCookiesFromHeader(_headers);
1✔
129
        _messageBody = messageBody;
1✔
130
        _protocol = request.getURL().getProtocol().toLowerCase(Locale.ENGLISH);
1✔
131
        _secure = _protocol.endsWith("s");
1✔
132
        _serverName = request.getURL().getHost();
1✔
133
        _serverPort = request.getURL().getPort();
1✔
134
        if (_serverPort == -1) {
1✔
135
            _serverPort = request.getURL().getDefaultPort();
1✔
136
        }
137

138
        _requestContext = new RequestContext(request.getURL());
1✔
139
        String contentTypeHeader = (String) _headers.get("Content-Type");
1✔
140
        if (contentTypeHeader != null) {
1✔
141
            String[] res = HttpUnitUtils.parseContentTypeHeader(contentTypeHeader);
1✔
142
            _charset = res[1];
1✔
143
            _requestContext.setMessageEncoding(_charset);
1✔
144
        }
145
        if (_headers.get("Content-Length") == null) {
1!
146
            _headers.put("Content-Length", Integer.toString(messageBody.length));
1✔
147
        }
148

149
        boolean setBody =
1!
150
                // pre [ 1509117 ] getContentType()
151
                // _messageBody != null && (_contentType == null || _contentType.indexOf( "x-www-form-urlencoded" ) >= 0
152
                // );
153
                // patch version:
154
                _messageBody != null
155
                        && (contentTypeHeader == null || contentTypeHeader.indexOf("x-www-form-urlencoded") >= 0);
1✔
156
        if (setBody) {
1✔
157
            _requestContext.setMessageBody(_messageBody);
1✔
158
        }
159
    }
1✔
160

161
    // ----------------------------------------- HttpServletRequest methods --------------------------
162

163
    /**
164
     * Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null
165
     * if the servlet was not protected.
166
     **/
167
    @Override
168
    public String getAuthType() {
169
        return null;
1✔
170
    }
171

172
    /**
173
     * Returns the query string that is contained in the request URL after the path.
174
     **/
175
    @Override
176
    public String getQueryString() {
177
        return _request.getQueryString();
1✔
178
    }
179

180
    /**
181
     * Returns an array containing all of the Cookie objects the client sent with this request. This method returns null
182
     * if no cookies were sent.
183
     **/
184
    @Override
185
    public Cookie[] getCookies() {
186
        if (_cookies.size() == 0) {
1✔
187
            return null;
1✔
188
        }
189
        return _cookies.toArray(new Cookie[0]);
1✔
190
    }
191

192
    /**
193
     * Returns the value of the specified request header as an int. If the request does not have a header of the
194
     * specified name, this method returns -1. If the header cannot be converted to an integer, this method throws a
195
     * NumberFormatException.
196
     **/
197
    @Override
198
    public int getIntHeader(String name) {
199
        return Integer.parseInt(getHeader(name));
1✔
200
    }
201

202
    /**
203
     * Returns the value of the specified request header as a long value that represents a Date object. Use this method
204
     * with headers that contain dates, such as If-Modified-Since. <br>
205
     * The date is returned as the number of milliseconds since January 1, 1970 GMT. The header name is case
206
     * insensitive. If the request did not have a header of the specified name, this method returns -1. If the header
207
     * can't be converted to a date, the method throws an IllegalArgumentException.
208
     **/
209
    @Override
210
    public long getDateHeader(String name) {
211
        try {
212
            String dateString = getHeader(name);
1✔
213
            Date headerDate = new Date(dateString);
1✔
214
            return headerDate.getTime();
1✔
215
        } catch (Exception e) {
1✔
216
            return -1;
1✔
217
        }
218
    }
219

220
    /**
221
     * Returns the value of the specified request header as a String. If the request did not include a header of the
222
     * specified name, this method returns null. The header name is case insensitive. You can use this method with any
223
     * request header.
224
     **/
225
    @Override
226
    public String getHeader(String name) {
227
        return (String) _headers.get(name);
1✔
228
    }
229

230
    /**
231
     * Returns an enumeration of all the header names this request contains. If the request has no headers, this method
232
     * returns an empty enumeration. Some servlet containers do not allow do not allow servlets to access headers using
233
     * this method, in which case this method returns null.
234
     **/
235
    @Override
236
    public Enumeration getHeaderNames() {
237
        return _headers.keys();
1✔
238
    }
239

240
    /**
241
     * Returns the part of this request's URL that calls the servlet. This includes either the servlet name or a path to
242
     * the servlet, but does not include any extra path information or a query string.
243
     **/
244
    @Override
245
    public String getServletPath() {
246
        return _servletRequest.getServletPath();
1✔
247
    }
248

249
    /**
250
     * Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
251
     **/
252
    @Override
253
    public String getMethod() {
254
        return _request.getMethod();
1✔
255
    }
256

257
    /**
258
     * Returns any extra path information associated with the URL the client sent when it made this request. The extra
259
     * path information follows the servlet path but precedes the query string. This method returns null if there was no
260
     * extra path information.
261
     **/
262
    @Override
263
    public String getPathInfo() {
264
        return _servletRequest.getPathInfo();
1✔
265
    }
266

267
    /**
268
     * Returns any extra path information after the servlet name but before the query string, and translates it to a
269
     * real path. If the URL does not have any extra path information, this method returns null.
270
     **/
271
    @Override
272
    public String getPathTranslated() {
273
        return null;
×
274
    }
275

276
    /**
277
     * Checks whether the requested session ID came in as a cookie.
278
     **/
279
    @Override
280
    public boolean isRequestedSessionIdFromCookie() {
281
        return _sessionID != null;
×
282
    }
283

284
    /**
285
     * Returns the login of the user making this request, if the user has been authenticated, or null if the user has
286
     * not been authenticated. Whether the user name is sent with each subsequent request depends on the browser and
287
     * type of authentication.
288
     **/
289
    @Override
290
    public String getRemoteUser() {
291
        return _userName;
1✔
292
    }
293

294
    /**
295
     * Returns the session ID specified by the client. This may not be the same as the ID of the actual session in use.
296
     * For example, if the request specified an old (expired) session ID and the server has started a new session, this
297
     * method gets a new session with a new ID. If the request did not specify a session ID, this method returns null.
298
     **/
299
    @Override
300
    public String getRequestedSessionId() {
301
        return _sessionID;
1✔
302
    }
303

304
    /**
305
     * Returns the part of this request's URL from the protocol name up to the query string in the first line of the
306
     * HTTP request.
307
     **/
308
    @Override
309
    public String getRequestURI() {
310
        return _requestContext.getRequestURI();
1✔
311
    }
312

313
    /**
314
     * Returns the current HttpSession associated with this request or, if there is no current session and create is
315
     * true, returns a new session. <br>
316
     * If create is false and the request has no valid HttpSession, this method returns null.
317
     **/
318
    @Override
319
    public HttpSession getSession(boolean create) {
320
        _session = _context.getValidSession(getRequestedSessionId(), _session, create);
1✔
321
        return _session;
1✔
322
    }
323

324
    /**
325
     * Returns the current session associated with this request, or if the request does not have a session, creates one.
326
     **/
327
    @Override
328
    public HttpSession getSession() {
329
        return getSession(true);
1✔
330
    }
331

332
    /**
333
     * Checks whether the requested session ID is still valid.
334
     **/
335
    @Override
336
    public boolean isRequestedSessionIdValid() {
337
        return false;
×
338
    }
339

340
    /**
341
     * Checks whether the requested session ID came in as part of the request URL.
342
     **/
343
    @Override
344
    public boolean isRequestedSessionIdFromURL() {
345
        return false;
×
346
    }
347

348
    /**
349
     * @deprecated use #isRequestedSessionIdFromURL
350
     **/
351
    @Deprecated
352
    @Override
353
    public boolean isRequestedSessionIdFromUrl() {
354
        return isRequestedSessionIdFromURL();
×
355
    }
356

357
    // --------------------------------- ServletRequest methods ----------------------------------------------------
358

359
    /**
360
     * Returns the length, in bytes, of the content contained in the request and sent by way of the input stream or -1
361
     * if the length is not known.
362
     **/
363
    @Override
364
    public int getContentLength() {
365
        return getIntHeader("Content-length");
1✔
366
    }
367

368
    /**
369
     * Returns the value of the named attribute as an <code>Object</code>. This method allows the servlet engine to give
370
     * the servlet custom information about a request. This method returns <code>null</code> if no attribute of the
371
     * given name exists.
372
     **/
373
    @Override
374
    public Object getAttribute(String name) {
375
        return _attributes.get(name);
1✔
376
    }
377

378
    /**
379
     * Returns an <code>Enumeration</code> containing the names of the attributes available to this request. This method
380
     * returns an empty <code>Enumeration</code> if the request has no attributes available to it.
381
     **/
382
    @Override
383
    public Enumeration getAttributeNames() {
384
        return _attributes.keys();
1✔
385
    }
386

387
    /**
388
     * Retrieves binary data from the body of the request as a {@link ServletInputStream}, which gives you the ability
389
     * to read one line at a time.
390
     *
391
     * @return a {@link ServletInputStream} object containing the body of the request
392
     *
393
     * @exception IllegalStateException
394
     *                if the {@link #getReader} method has already been called for this request
395
     * @exception IOException
396
     *                if an input or output exception occurred
397
     */
398
    @Override
399
    public ServletInputStream getInputStream() throws IOException {
400
        if (_gotReader) {
1✔
401
            throw new IllegalStateException("getReader() has already been called for this request");
1✔
402
        }
403
        initializeInputStream();
1✔
404
        _gotInputStream = true;
1✔
405
        return _inputStream;
1✔
406
    }
407

408
    /**
409
     * initialize the inputStream.
410
     */
411
    private void initializeInputStream() {
412
        if (_inputStream == null) {
1✔
413
            _inputStream = new ServletInputStreamImpl(_messageBody);
1✔
414
        }
415
    }
1✔
416

417
    /**
418
     * Returns the name of the character encoding style used in this request. This method returns <code>null</code> if
419
     * the request does not use character encoding.
420
     **/
421
    @Override
422
    public String getCharacterEncoding() {
423
        return _charset;
1✔
424
    }
425

426
    /**
427
     * Returns an <code>Enumeration</code> of <code>String</code> objects containing the names of the parameters
428
     * contained in this request. If the request has no parameters or if the input stream is empty, returns an empty
429
     * <code>Enumeration</code>. The input stream is empty when all the data returned by {@link #getInputStream} has
430
     * been read.
431
     **/
432
    @Override
433
    public Enumeration getParameterNames() {
434
        return _requestContext.getParameterNames();
×
435
    }
436

437
    /**
438
     * Returns the MIME type of the content of the request, or <code>null</code> if the type is not known. Same as the
439
     * value of the CGI variable CONTENT_TYPE.
440
     **/
441
    @Override
442
    public String getContentType() {
443
        return this.getHeader("Content-Type");
1✔
444
    }
445

446
    /**
447
     * Returns the value of a request parameter as a <code>String</code>, or <code>null</code> if the parameter does not
448
     * exist. Request parameters are extra information sent with the request.
449
     **/
450
    @Override
451
    public String getParameter(String name) {
452
        String[] parameters = getParameterValues(name);
1✔
453
        return parameters == null ? null : parameters[0];
1✔
454
    }
455

456
    /**
457
     * Returns an array of <code>String</code> objects containing all of the values the given request parameter has, or
458
     * <code>null</code> if the parameter does not exist. For example, in an HTTP servlet, this method returns an array
459
     * of <code>String</code> objects containing the values of a query string or posted form.
460
     **/
461
    @Override
462
    public String[] getParameterValues(String name) {
463
        return _requestContext.getParameterValues(name);
1✔
464
    }
465

466
    /**
467
     * Returns the name and version of the protocol the request uses in the form
468
     * <i>protocol/majorVersion.minorVersion</i>, for example, HTTP/1.1.
469
     **/
470
    @Override
471
    public String getProtocol() {
472
        return "HTTP/1.1";
×
473
    }
474

475
    /**
476
     * Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or
477
     * <code>ftp</code>. Different schemes have different rules for constructing URLs, as noted in RFC 1738.
478
     **/
479
    @Override
480
    public String getScheme() {
481
        return _protocol;
1✔
482
    }
483

484
    /**
485
     * Returns the fully qualified name of the client that sent the request.
486
     **/
487
    @Override
488
    public String getRemoteHost() {
489
        return "localhost";
×
490
    }
491

492
    /**
493
     * Returns the host name of the server that received the request.
494
     **/
495
    @Override
496
    public String getServerName() {
497
        return _serverName;
1✔
498
    }
499

500
    /**
501
     * Returns the port number on which this request was received.
502
     **/
503
    @Override
504
    public int getServerPort() {
505
        return _serverPort;
1✔
506
    }
507

508
    /**
509
     * @deprecated As of Version 2.1 of the Java Servlet API, use {@link javax.servlet.ServletContext#getRealPath}
510
     *             instead.
511
     */
512
    @Deprecated
513
    @Override
514
    public String getRealPath(String path) {
515
        throwNotImplementedYet();
×
516
        return "";
×
517
    }
518

519
    /**
520
     * Returns the body of the request as a <code>BufferedReader</code> that translates character set encodings.
521
     *
522
     * @return the reader
523
     **/
524
    @Override
525
    public BufferedReader getReader() throws IOException {
526
        if (_gotInputStream) {
1✔
527
            throw new IllegalStateException("getInputStream() has already been called on this request");
1✔
528
        }
529
        if (_reader == null) {
1✔
530
            initializeInputStream();
1✔
531
            String encoding = getCharacterEncoding();
1✔
532
            if (encoding == null) {
1!
533
                encoding = StandardCharsets.ISO_8859_1.name();
1✔
534
            }
535
            _reader = new BufferedReader(new InputStreamReader(_inputStream, Charset.forName(encoding)));
1✔
536
            _gotReader = true;
1✔
537
        }
538
        return _reader;
1✔
539
    }
540

541
    /**
542
     * Returns the Internet Protocol (IP) address of the client that sent the request.
543
     **/
544
    @Override
545
    public String getRemoteAddr() {
546
        return LOOPBACK_ADDRESS;
×
547
    }
548

549
    /**
550
     * Stores an attribute in the context of this request. Attributes are reset between requests.
551
     **/
552
    @Override
553
    public void setAttribute(String key, Object o) {
554
        if (o == null) {
1✔
555
            _attributes.remove(key);
1✔
556
        } else {
557
            _attributes.put(key, o);
1✔
558
        }
559
    }
1✔
560

561
    // --------------------------------- methods added to ServletRequest in Servlet API 2.2
562
    // ------------------------------------------------
563

564
    /**
565
     * Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
566
     **/
567
    @Override
568
    public boolean isSecure() {
569
        return _secure;
1✔
570
    }
571

572
    /**
573
     * Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. If the
574
     * client request doesn't provide an Accept-Language header, this method returns the default locale for the server.
575
     **/
576
    @Override
577
    public Locale getLocale() {
578
        return (Locale) getPreferredLocales().get(0);
1✔
579
    }
580

581
    /**
582
     * Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the
583
     * locales that are acceptable to the client based on the Accept-Language header. If the client request doesn't
584
     * provide an Accept-Language header, this method returns an Enumeration containing one Locale, the default locale
585
     * for the server.
586
     **/
587
    @Override
588
    public java.util.Enumeration getLocales() {
589
        return Collections.enumeration(getPreferredLocales());
1✔
590
    }
591

592
    /**
593
     * Parses the accept-language header to obtain a list of preferred locales.
594
     *
595
     * @return the preferred locales, sorted by qvalue
596
     */
597
    private List getPreferredLocales() {
598
        if (_locales == null) {
1✔
599
            _locales = new ArrayList<>();
1✔
600
            String languages = getHeader("accept-language");
1✔
601
            if (languages == null) {
1✔
602
                _locales.add(Locale.getDefault());
1✔
603
            } else {
604
                StringTokenizer st = new StringTokenizer(languages, ",");
1✔
605
                ArrayList al = new ArrayList<>();
1✔
606
                while (st.hasMoreTokens()) {
1✔
607
                    String token = st.nextToken();
1✔
608
                    al.add(new PrioritizedLocale(token));
1✔
609
                }
1✔
610
                Collections.sort(al);
1✔
611
                for (Iterator iterator = al.iterator(); iterator.hasNext();) {
1✔
612
                    _locales.add(((PrioritizedLocale) iterator.next()).getLocale());
1✔
613
                }
614
            }
615
        }
616
        return _locales;
1✔
617
    }
618

619
    /**
620
     * Removes an attribute from this request. This method is not generally needed as attributes only persist as long as
621
     * the request is being handled.
622
     **/
623
    @Override
624
    public void removeAttribute(String name) {
625
        _attributes.remove(name);
×
626
    }
×
627

628
    /**
629
     * Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A
630
     * RequestDispatcher object can be used to forward a request to the resource or to include the resource in a
631
     * response. The resource can be dynamic or static. The pathname specified may be relative, although it cannot
632
     * extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the
633
     * current context root. This method returns null if the servlet container cannot return a RequestDispatcher. The
634
     * difference between this method and ServletContext.getRequestDispatcher(java.lang.String) is that this method can
635
     * take a relative path.
636
     **/
637
    @Override
638
    public RequestDispatcher getRequestDispatcher(String path) {
639
        try {
640
            if (!path.startsWith("/")) {
1✔
641
                path = combinedPath(getServletPath(), path);
1✔
642
            }
643
            return _servletRequest.getServlet().getServletConfig().getServletContext().getRequestDispatcher(path);
1✔
644
        } catch (ServletException e) {
×
645
            return null;
×
646
        }
647
    }
648

649
    /**
650
     * Combined path.
651
     *
652
     * @param basePath
653
     *            the base path
654
     * @param relativePath
655
     *            the relative path
656
     *
657
     * @return the string
658
     */
659
    private String combinedPath(String basePath, String relativePath) {
660
        if (basePath.indexOf('/') < 0) {
1!
661
            return relativePath;
×
662
        }
663
        return basePath.substring(0, basePath.lastIndexOf('/')) + '/' + relativePath;
1✔
664
    }
665

666
    // --------------------------------- methods added to HttpServletRequest in Servlet API 2.2
667
    // ------------------------------------------------
668

669
    /**
670
     * Returns a java.security.Principal object containing the name of the current authenticated user. If the user has
671
     * not been authenticated, the method returns null.
672
     **/
673
    @Override
674
    public java.security.Principal getUserPrincipal() {
675
        return null;
×
676
    }
677

678
    /**
679
     * Returns a boolean indicating whether the authenticated user is included in the specified logical "role". Roles
680
     * and role membership can be defined using deployment descriptors. If the user has not been authenticated, the
681
     * method returns false.
682
     **/
683
    @Override
684
    public boolean isUserInRole(String role) {
685
        if (_roles == null) {
1✔
686
            return false;
1✔
687
        }
688
        for (String _role : _roles) {
1✔
689
            if (role.equals(_role)) {
1✔
690
                return true;
1✔
691
            }
692
        }
693
        return false;
1✔
694
    }
695

696
    /**
697
     * Returns all the values of the specified request header as an Enumeration of String objects.
698
     **/
699
    @Override
700
    public java.util.Enumeration getHeaders(String name) {
701
        List list = new ArrayList<>();
1✔
702
        if (_headers.containsKey(name)) {
1!
703
            list.add(_headers.get(name));
1✔
704
        }
705
        return Collections.enumeration(list);
1✔
706
    }
707

708
    /**
709
     * Returns the portion of the request URI that indicates the context of the request. The context path always comes
710
     * first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets
711
     * in the default (root) context, this method returns "".
712
     **/
713
    @Override
714
    public String getContextPath() {
715
        return _context.getContextPath();
1✔
716
    }
717

718
    // --------------------------------------- methods added to ServletRequest in Servlet API 2.3
719
    // ----------------------------
720

721
    /**
722
     * Returns a java.util.Map of the parameters of this request. Request parameters are extra information sent with the
723
     * request. For HTTP servlets, parameters are contained in the query string or posted form data.
724
     **/
725
    @Override
726
    public Map getParameterMap() {
727
        return _requestContext.getParameterMap();
1✔
728
    }
729

730
    /**
731
     * Overrides the name of the character encoding used in the body of this request. This method must be called prior
732
     * to reading request parameters or reading input using getReader().
733
     **/
734
    @Override
735
    public void setCharacterEncoding(String charset) {
736
        _charset = charset;
1✔
737
        _requestContext.setMessageEncoding(charset);
1✔
738
    }
1✔
739

740
    // --------------------------------------- methods added to HttpServletRequest in Servlet API 2.3
741
    // ----------------------------
742

743
    /**
744
     * Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port
745
     * number, and server path, but it does not include query string parameters. Because this method returns a
746
     * StringBuffer, not a string, you can modify the URL easily, for example, to append query parameters. This method
747
     * is useful for creating redirect messages and for reporting errors.
748
     */
749
    @Override
750
    public StringBuffer getRequestURL() {
751
        StringBuilder url = new StringBuilder();
1✔
752
        try {
753
            url.append(_request.getURL().getProtocol()).append("://");
1✔
754
            url.append(_request.getURL().getHost());
1✔
755
            String portPortion = _request.getURL().getPort() == -1 ? "" : ":" + _request.getURL().getPort();
1✔
756
            url.append(portPortion);
1✔
757
            url.append(_request.getURL().getPath());
1✔
758
        } catch (MalformedURLException e) {
×
759
            throw new RuntimeException("unable to read URL from request: " + _request);
×
760
        }
1✔
761
        return new StringBuffer(url);
1✔
762
    }
763

764
    // --------------------------------------- methods added to ServletRequest in Servlet API 2.4
765
    // ----------------------------
766

767
    @Override
768
    public int getRemotePort() {
769
        return 0; // To change body of implemented methods use File | Settings | File Templates.
×
770
    }
771

772
    @Override
773
    public String getLocalName() {
774
        return "localhost";
×
775
    }
776

777
    @Override
778
    public String getLocalAddr() {
779
        return "127.0.0.1";
×
780
    }
781

782
    @Override
783
    public int getLocalPort() {
784
        return 0; // To change body of implemented methods use File | Settings | File Templates.
×
785
    }
786

787
    // --------------------------------------------- package members ----------------------------------------------
788

789
    /**
790
     * Adds the cookie.
791
     *
792
     * @param cookie
793
     *            the cookie
794
     */
795
    private void addCookie(Cookie cookie) {
796
        _cookies.add(cookie);
1✔
797
        if (cookie.getName().equalsIgnoreCase(ServletUnitHttpSession.SESSION_COOKIE_NAME)) {
1✔
798
            _sessionID = cookie.getValue();
1✔
799
        }
800
    }
1✔
801

802
    /**
803
     * Gets the servlet session.
804
     *
805
     * @return the servlet session
806
     */
807
    private ServletUnitHttpSession getServletSession() {
808
        return (ServletUnitHttpSession) getSession();
1✔
809
    }
810

811
    /**
812
     * Read form authentication.
813
     */
814
    void readFormAuthentication() {
815
        if (getSession( /* create */ false) != null) {
1✔
816
            recordAuthenticationInfo(getServletSession().getUserName(), getServletSession().getRoles());
1✔
817
        }
818
    }
1✔
819

820
    /**
821
     * Read basic authentication.
822
     */
823
    void readBasicAuthentication() {
824
        String authorizationHeader = (String) _headers.get("Authorization");
1✔
825

826
        if (authorizationHeader != null) {
1✔
827
            String userAndPassword = new String(Base64.getDecoder().decode(authorizationHeader
1✔
828
                    .substring(authorizationHeader.indexOf(' ') + 1).getBytes(StandardCharsets.UTF_8)),
1✔
829
                    StandardCharsets.UTF_8);
830
            int colonPos = userAndPassword.indexOf(':');
1✔
831
            recordAuthenticationInfo(userAndPassword.substring(0, colonPos),
1✔
832
                    toArray(userAndPassword.substring(colonPos + 1)));
1✔
833
        }
834
    }
1✔
835

836
    /**
837
     * To array.
838
     *
839
     * @param roleList
840
     *            the role list
841
     *
842
     * @return the string[]
843
     */
844
    static String[] toArray(String roleList) {
845
        StringTokenizer st = new StringTokenizer(roleList, ",");
1✔
846
        String[] result = new String[st.countTokens()];
1✔
847
        for (int i = 0; i < result.length; i++) {
1✔
848
            result[i] = st.nextToken();
1✔
849
        }
850
        return result;
1✔
851
    }
852

853
    /**
854
     * Record authentication info.
855
     *
856
     * @param userName
857
     *            the user name
858
     * @param roles
859
     *            the roles
860
     */
861
    void recordAuthenticationInfo(String userName, String[] roles) {
862
        _userName = userName;
1✔
863
        _roles = roles;
1✔
864
    }
1✔
865

866
    // --------------------------------------------- private members ----------------------------------------------
867

868
    /** The Constant LOOPBACK_ADDRESS. */
869
    private static final String LOOPBACK_ADDRESS = "127.0.0.1";
870

871
    /** The request. */
872
    private WebRequest _request;
873

874
    /** The servlet request. */
875
    private ServletMetaData _servletRequest;
876

877
    /** The headers. */
878
    private WebClient.HeaderDictionary _headers;
879

880
    /** The context. */
881
    private ServletUnitContext _context;
882

883
    /** The session. */
884
    private ServletUnitHttpSession _session;
885

886
    /** The attributes. */
887
    private Hashtable _attributes = new Hashtable<>();
1✔
888

889
    /** The cookies. */
890
    private List<Cookie> _cookies = new ArrayList<>();
1✔
891

892
    /** The session ID. */
893
    private String _sessionID;
894

895
    /** The message body. */
896
    private byte[] _messageBody;
897

898
    /** The user name. */
899
    private String _userName;
900

901
    /** The roles. */
902
    private String[] _roles;
903

904
    /**
905
     * Throw not implemented yet.
906
     */
907
    private void throwNotImplementedYet() {
908
        throw new RuntimeException("Not implemented yet");
×
909
    }
910

911
    /**
912
     * Sets the cookies from header.
913
     *
914
     * @param clientHeaders
915
     *            the new cookies from header
916
     */
917
    private void setCookiesFromHeader(Dictionary clientHeaders) {
918
        String cookieHeader = (String) clientHeaders.get("Cookie");
1✔
919
        if (cookieHeader == null) {
1✔
920
            return;
1✔
921
        }
922

923
        StringTokenizer st = new StringTokenizer(cookieHeader, ",;=", true);
1✔
924
        String lastToken = st.nextToken();
1✔
925
        while (st.hasMoreTokens()) {
1✔
926
            String token = st.nextToken();
1✔
927
            if (token.equals("=") && st.hasMoreTokens()) {
1!
928
                addCookie(new Cookie(lastToken.trim(), st.nextToken().trim()));
1✔
929
            }
930
            lastToken = token;
1✔
931
        }
1✔
932
    }
1✔
933

934
    /**
935
     * The Class PrioritizedLocale.
936
     */
937
    static class PrioritizedLocale implements Comparable {
938

939
        /** The locale. */
940
        private Locale _locale;
941

942
        /** The priority. */
943
        private float _priority;
944

945
        /**
946
         * Instantiates a new prioritized locale.
947
         *
948
         * @param languageSpec
949
         *            the language spec
950
         */
951
        PrioritizedLocale(String languageSpec) {
1✔
952
            int semiIndex = languageSpec.indexOf(';');
1✔
953
            if (semiIndex < 0) {
1✔
954
                _priority = 1;
1✔
955
                _locale = parseLocale(languageSpec);
1✔
956
            } else {
957
                _priority = Float.parseFloat(languageSpec.substring(languageSpec.indexOf('=', semiIndex) + 1));
1✔
958
                _locale = parseLocale(languageSpec.substring(0, semiIndex));
1✔
959
            }
960
        }
1✔
961

962
        /**
963
         * Parses the locale.
964
         *
965
         * @param range
966
         *            the range
967
         *
968
         * @return the locale
969
         */
970
        private Locale parseLocale(String range) {
971
            range = range.trim();
1✔
972
            int dashIndex = range.indexOf('-');
1✔
973
            if (dashIndex < 0) {
1✔
974
                return new Locale(range, "");
1✔
975
            }
976
            return new Locale(range.substring(0, dashIndex), range.substring(dashIndex + 1));
1✔
977
        }
978

979
        /**
980
         * Gets the locale.
981
         *
982
         * @return the locale
983
         */
984
        public Locale getLocale() {
985
            return _locale;
1✔
986
        }
987

988
        @Override
989
        public int compareTo(Object o) {
990
            if (!(o instanceof PrioritizedLocale)) {
1!
991
                throw new IllegalArgumentException("may only combine with other prioritized locales");
×
992
            }
993
            PrioritizedLocale other = (PrioritizedLocale) o;
1✔
994
            return _priority == other._priority ? _locale.getLanguage().compareTo(other._locale.getLanguage())
1!
995
                    : _priority < other._priority ? +1 : -1;
1✔
996
        }
997

998
    }
999

1000
    @Override
1001
    public ServletContext getServletContext() {
1002
        try {
1003
            return _servletRequest.getServlet().getServletConfig().getServletContext();
×
1004
        } catch (ServletException e) {
×
1005
            return null;
×
1006
        }
1007
    }
1008

1009
    @Override
1010
    public AsyncContext startAsync() throws IllegalStateException {
1011
        // TODO Auto-generated method stub
1012
        return null;
×
1013
    }
1014

1015
    @Override
1016
    public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
1017
            throws IllegalStateException {
1018
        // TODO Auto-generated method stub
1019
        return null;
×
1020
    }
1021

1022
    @Override
1023
    public boolean isAsyncStarted() {
1024
        // TODO Auto-generated method stub
1025
        return false;
×
1026
    }
1027

1028
    @Override
1029
    public boolean isAsyncSupported() {
1030
        // TODO Auto-generated method stub
1031
        return false;
×
1032
    }
1033

1034
    @Override
1035
    public AsyncContext getAsyncContext() {
1036
        // TODO Auto-generated method stub
1037
        return null;
×
1038
    }
1039

1040
    @Override
1041
    public DispatcherType getDispatcherType() {
1042
        // TODO Auto-generated method stub
1043
        return null;
×
1044
    }
1045

1046
    @Override
1047
    public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
1048
        // TODO Auto-generated method stub
1049
        return false;
×
1050
    }
1051

1052
    @Override
1053
    public void login(String username, String password) throws ServletException {
1054
        // TODO Auto-generated method stub
1055

1056
    }
×
1057

1058
    @Override
1059
    public void logout() throws ServletException {
1060
        // TODO Auto-generated method stub
1061

1062
    }
×
1063

1064
    @Override
1065
    public Collection<Part> getParts() throws IOException, ServletException {
1066
        // TODO Auto-generated method stub
1067
        return null;
×
1068
    }
1069

1070
    @Override
1071
    public Part getPart(String name) throws IOException, ServletException {
1072
        // TODO Auto-generated method stub
1073
        return null;
×
1074
    }
1075

1076
    @Override
1077
    public long getContentLengthLong() {
1078
        // TODO Auto-generated method stub
1079
        return 0;
×
1080
    }
1081

1082
    @Override
1083
    public String changeSessionId() {
1084
        // TODO Auto-generated method stub
1085
        return null;
×
1086
    }
1087

1088
    @Override
1089
    public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException {
1090
        // TODO Auto-generated method stub
1091
        return null;
×
1092
    }
1093

1094
}
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