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

hazendaz / httpunit / 646

06 Dec 2025 08:11PM UTC coverage: 80.526% (+0.02%) from 80.509%
646

push

github

hazendaz
Cleanup array usage

3213 of 4105 branches covered (78.27%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 3 files covered. (100.0%)

532 existing lines in 26 files now uncovered.

8245 of 10124 relevant lines covered (81.44%)

0.81 hits per line

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

27.21
/src/main/java/com/meterware/servletunit/ServletUnitServletContext.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 jakarta.servlet.*;
23
import jakarta.servlet.ServletRegistration.Dynamic;
24
import jakarta.servlet.descriptor.JspConfigDescriptor;
25

26
import java.io.File;
27
import java.io.IOException;
28
import java.io.PrintStream;
29
import java.net.MalformedURLException;
30
import java.net.URL;
31
import java.net.URLConnection;
32
import java.nio.file.Files;
33
import java.util.Enumeration;
34
import java.util.EventListener;
35
import java.util.Hashtable;
36
import java.util.Map;
37
import java.util.Set;
38

39
/**
40
 * This class is a private implementation of the ServletContext class.
41
 **/
42
public class ServletUnitServletContext implements ServletContext {
43

44
    /** The log stream. */
45
    private PrintStream _logStream = System.out;
1✔
46

47
    /**
48
     * Instantiates a new servlet unit servlet context.
49
     *
50
     * @param application
51
     *            the application
52
     */
53
    ServletUnitServletContext(WebApplication application) {
1✔
54
        _application = application;
1✔
55
    }
1✔
56

57
    /**
58
     * Returns a ServletContext object that corresponds to a specified URL on the server.
59
     * <p>
60
     * This method allows servlets to gain access to the context for various parts of the server, and as needed obtain
61
     * RequestDispatcher objects from the context. The given path must be absolute (beginning with "/") and is
62
     * interpreted based on the server's document root.
63
     * <p>
64
     * In a security conscious environment, the servlet container may return null for a given URL.
65
     **/
66
    @Override
67
    public jakarta.servlet.ServletContext getContext(java.lang.String A) {
UNCOV
68
        return null;
×
69
    }
70

71
    /**
72
     * Returns the major version of the Java Servlet API that this servlet container supports. All implementations that
73
     * comply with Version 2.4 must have this method return the integer 2.
74
     **/
75
    @Override
76
    public int getMajorVersion() {
UNCOV
77
        return 4;
×
78
    }
79

80
    /**
81
     * Returns the minor version of the Servlet API that this servlet container supports. All implementations that
82
     * comply with Version 2.4 must have this method return the integer 4.
83
     **/
84
    @Override
85
    public int getMinorVersion() {
UNCOV
86
        return 0;
×
87
    }
88

89
    /**
90
     * Returns the MIME type of the specified file, or null if the MIME type is not known. The MIME type is determined
91
     * by the configuration of the servlet container, and may be specified in a web application deployment descriptor.
92
     * Common MIME types are "text/html" and "image/gif".
93
     **/
94
    @Override
95
    public java.lang.String getMimeType(String filePath) {
96
        return URLConnection.getFileNameMap().getContentTypeFor(filePath);
1✔
97
    }
98

99
    /**
100
     * Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is
101
     * interpreted as relative to the current context root.
102
     * <p>
103
     * This method allows the servlet container to make a resource available to servlets from any source. Resources can
104
     * be located on a local or remote file system, in a database, or in a .war file.
105
     * <p>
106
     * The servlet container must implement the URL handlers and URLConnection objects that are necessary to access the
107
     * resource.
108
     * <p>
109
     * This method returns null if no resource is mapped to the pathname. Some containers may allow writing to the URL
110
     * returned by this method using the methods of the URL class. The resource content is returned directly, so be
111
     * aware that requesting a .jsp page returns the JSP source code. Use a RequestDispatcher instead to include results
112
     * of an execution. This method has a different purpose than java.lang.Class.getResource, which looks up resources
113
     * based on a class loader. This method does not use class loaders.
114
     **/
115
    @Override
116
    public java.net.URL getResource(String path) {
117
        try {
118
            File resourceFile = _application.getResourceFile(path);
1✔
119
            return resourceFile == null || !resourceFile.exists() ? null : resourceFile.toURI().toURL();
1!
UNCOV
120
        } catch (MalformedURLException e) {
×
UNCOV
121
            return null;
×
122
        }
123
    }
124

125
    /**
126
     * Returns the resource located at the named path as an InputStream object. The data in the InputStream can be of
127
     * any type or length. The path must be specified according to the rules given in getResource. This method returns
128
     * null if no resource exists at the specified path. Meta-information such as content length and content type that
129
     * is available via getResource method is lost when using this method. The servlet container must implement the URL
130
     * handlers and URLConnection objects necessary to access the resource. This method is different from
131
     * java.lang.Class.getResourceAsStream, which uses a class loader. This method allows servlet containers to make a
132
     * resource available to a servlet from any location, without using a class loader.
133
     **/
134
    @Override
135
    public java.io.InputStream getResourceAsStream(String path) {
136
        try {
137
            File resourceFile = _application.getResourceFile(path);
1✔
138
            return resourceFile == null ? null : Files.newInputStream(resourceFile.toPath());
1!
139
        } catch (IOException e) {
1✔
140
            return null;
1✔
141
        }
142
    }
143

144
    /**
145
     * Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A
146
     * RequestDispatcher object can be used to forward a request to the resource or to include the resource in a
147
     * response. The resource can be dynamic or static. The pathname must begin with a "/" and is interpreted as
148
     * relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign
149
     * contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.
150
     **/
151
    @Override
152
    public jakarta.servlet.RequestDispatcher getRequestDispatcher(String path) {
153
        try {
154
            URL url = new URL("http", "localhost", _application.getContextPath() + path);
1✔
155
            return new RequestDispatcherImpl(_application, url);
1✔
UNCOV
156
        } catch (ServletException | MalformedURLException e) {
×
UNCOV
157
            return null;
×
158
        }
159
    }
160

161
    /**
162
     * Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Servlets (and JSP pages also)
163
     * may be given names via server administration or via a web application deployment descriptor. A servlet instance
164
     * can determine its name using ServletConfig.getServletName(). This method returns null if the ServletContext
165
     * cannot return a RequestDispatcher for any reason. patch by Izzy Alanis
166
     *
167
     * @param servletName
168
     *            - the name of the dispatcher to get
169
     **/
170
    @Override
171
    public jakarta.servlet.RequestDispatcher getNamedDispatcher(java.lang.String servletName) {
172
        final WebApplication.ServletConfiguration servletConfig = _application.getServletByName(servletName);
1✔
173
        if (servletConfig == null) {
1!
174
            return null;
1✔
175
        }
176

177
        Servlet tempServlet;
178
        Exception tempException;
179

180
        try {
UNCOV
181
            tempServlet = servletConfig.getServlet();
×
UNCOV
182
            tempException = null;
×
UNCOV
183
        } catch (Exception e) {
×
UNCOV
184
            tempServlet = null;
×
UNCOV
185
            tempException = e;
×
UNCOV
186
        }
×
187

UNCOV
188
        final Servlet servlet = tempServlet;
×
189

190
        final Exception instantiationException = tempException;
×
191

192
        return new jakarta.servlet.RequestDispatcher() {
×
193

194
            @Override
195
            public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
196

197
                if (instantiationException != null) {
×
198

199
                    if (instantiationException instanceof ServletException) {
×
UNCOV
200
                        throw (ServletException) instantiationException;
×
201

202
                    }
UNCOV
203
                    ServletException e = new ServletException(instantiationException.getMessage());
×
204

UNCOV
205
                    e.initCause(instantiationException);
×
206

UNCOV
207
                    throw e;
×
208

209
                }
210

UNCOV
211
                if (servletConfig.getJspFile() != null) {
×
212
                    request.setAttribute("org.apache.catalina.jsp_file", servletConfig.getJspFile());
×
213
                }
214
                response.reset();
×
UNCOV
215
                servlet.service(request, response);
×
216
            }
×
217

218
            @Override
219
            public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
220
                if (instantiationException != null) {
×
221
                    if (instantiationException instanceof ServletException) {
×
UNCOV
222
                        throw (ServletException) instantiationException;
×
223
                    }
224
                    ServletException e = new ServletException(instantiationException.getMessage());
×
225
                    e.initCause(instantiationException);
×
UNCOV
226
                    throw e;
×
227
                }
UNCOV
228
                if (servletConfig.getJspFile() != null) {
×
229
                    request.setAttribute("org.apache.catalina.jsp_file", servletConfig.getJspFile());
×
230
                }
231
                servlet.service(request, response);
×
UNCOV
232
            }
×
233
        };
234
    }
235

236
    /**
237
     * Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log
238
     * file is specific to the servlet container.
239
     **/
240
    @Override
241
    public void log(String message) {
UNCOV
242
        _logStream.println(message);
×
UNCOV
243
    }
×
244

245
    /**
246
     * Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. The name
247
     * and type of the servlet log file is specific to the servlet container, usually an event log.
248
     **/
249
    @Override
250
    public void log(String message, Throwable t) {
251
        _logStream.print(message);
×
252
        _logStream.print(":");
×
UNCOV
253
        if (t != null) {
×
UNCOV
254
            t.printStackTrace(_logStream);
×
255
        }
UNCOV
256
    }
×
257

258
    /**
259
     * Returns a String containing the real path for a given virtual path. For example, the virtual path "/index.html"
260
     * has a real path of whatever file on the server's filesystem would be served by a request for "/index.html". The
261
     * real path returned will be in a form appropriate to the computer and operating system on which the servlet
262
     * container is running, including the proper path separators. This method returns null if the servlet container
263
     * cannot translate the virtual path to a real path for any reason (such as when the content is being made available
264
     * from a .war archive).
265
     **/
266
    @Override
267
    public String getRealPath(String path) {
268
        return _application.getResourceFile(path).getAbsolutePath();
1✔
269
    }
270

271
    /** The Constant DEFAULT_SERVER_INFO. */
272
    public static final String DEFAULT_SERVER_INFO = "ServletUnit test framework";
273

274
    /**
275
     * Returns the name and version of the servlet container on which the servlet is running. The form of the returned
276
     * string is servername/versionnumber. For example, the JavaServer Web Development Kit may return the string
277
     * JavaServer Web Dev Kit/1.0. The servlet container may return other optional information after the primary string
278
     * in parentheses, for example, JavaServer Web Dev Kit/1.0 (JDK 1.1.6; Windows NT 4.0 x86).
279
     **/
280
    @Override
281
    public String getServerInfo() {
UNCOV
282
        return DEFAULT_SERVER_INFO;
×
283
    }
284

285
    /**
286
     * Returns a String containing the value of the named context-wide initialization parameter, or null if the
287
     * parameter does not exist. This method can make available configuration information useful to an entire "web
288
     * application". For example, it can provide a webmaster's email address or the name of a system that holds critical
289
     * data.
290
     **/
291
    @Override
292
    public String getInitParameter(String name) {
293
        return (String) getContextParams().get(name);
1✔
294
    }
295

296
    /**
297
     * Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty
298
     * Enumeration if the context has no initialization parameters.
299
     **/
300
    @Override
301
    public Enumeration<String> getInitParameterNames() {
UNCOV
302
        return getContextParams().keys();
×
303
    }
304

305
    /**
306
     * Returns the servlet container attribute with the given name, or null if there is no attribute by that name. An
307
     * attribute allows a servlet container to give the servlet additional information not already provided by this
308
     * interface. See your server documentation for information about its attributes. A list of supported attributes can
309
     * be retrieved using getAttributeNames.
310
     **/
311
    @Override
312
    public Object getAttribute(String name) {
313
        return _attributes.get(name);
1✔
314
    }
315

316
    @Override
317
    public Enumeration<String> getAttributeNames() {
UNCOV
318
        return _attributes.keys();
×
319
    }
320

321
    @Override
322
    public void setAttribute(String name, Object attribute) {
323
        if (!_attributes.containsKey(name)) {
1✔
324
            _attributes.put(name, attribute);
1✔
325
            _application.sendAttributeAdded(name, attribute);
1✔
326
        } else {
327
            Object oldValue = _attributes.get(name);
1✔
328
            _attributes.put(name, attribute);
1✔
329
            _application.sendAttributeReplaced(name, oldValue);
1✔
330
        }
331
    }
1✔
332

333
    @Override
334
    public void removeAttribute(String name) {
335
        Object oldValue = _attributes.get(name);
1✔
336
        _attributes.remove(name);
1✔
337
        _application.sendAttributeRemoved(name, oldValue);
1✔
338
    }
1✔
339

340
    // ----------------------------- methods added to ServletContext in JSDK 2.3
341
    // --------------------------------------
342

343
    /**
344
     * Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path
345
     * matches the supplied path argument. Paths indicating subdirectory paths end with a '/'. The returned paths are
346
     * all relative to the root of the web application and have a leading '/'. For example, for a web application
347
     * containing &lt;p&gt; /welcome.html&lt;br /&gt; /catalog/index.html&lt;br /&gt; &lt;br /&gt;
348
     * /catalog/products.html&lt;br /&gt; /catalog/offers/books.html&lt;br /&gt; /catalog/offers/music.html&lt;br /&gt;
349
     * /customer/login.jsp&lt;br /&gt; /WEB-INF/web.xml&lt;br /&gt; /WEB-INF/classes/com.acme.OrderServlet.class,&lt;br
350
     * /&gt; &lt;br /&gt; getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"}&lt;br
351
     * /&gt; getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html",
352
     * "/catalog/offers/"}.
353
     *
354
     * @param path
355
     *            partial path used to match the resources, which must start with a /
356
     *
357
     * @return a Set containing the directory listing, or null if there are no resources in the web application whose
358
     *         path begins with the supplied path.
359
     */
360
    @Override
361
    public Set<String> getResourcePaths(String path) {
UNCOV
362
        return null;
×
363
    }
364

365
    /**
366
     * Returns the name of this web application correponding to this ServletContext as specified in the deployment
367
     * descriptor for this web application by the display-name element.
368
     *
369
     * @return The name of the web application or null if no name has been declared in the deployment descriptor
370
     */
371
    @Override
372
    public String getServletContextName() {
373
        return _application.getDisplayName();
1✔
374
    }
375

376
    // -------------------------------------- servlet-api 2.5 additions
377
    // -----------------------------------------------
378

379
    @Override
380
    public String getContextPath() {
UNCOV
381
        return null;
×
382
    }
383

384
    // ------------------------------------------- package members
385
    // ----------------------------------------------------
386

387
    /**
388
     * Sets the init parameter.
389
     *
390
     * @param name
391
     *            the name
392
     * @param initParameter
393
     *            the init parameter
394
     */
395
    void setInitParameter(String name, Object initParameter) {
UNCOV
396
        getContextParams().put(name, initParameter);
×
UNCOV
397
    }
×
398

399
    /**
400
     * Removes the init parameter.
401
     *
402
     * @param name
403
     *            the name
404
     */
405
    void removeInitParameter(String name) {
406
        getContextParams().remove(name);
×
UNCOV
407
    }
×
408

409
    // ------------------------------------------- private members
410
    // ----------------------------------------------------
411

412
    /** The attributes. */
413
    private Hashtable _attributes = new Hashtable<>();
1✔
414

415
    /** The application. */
416
    private WebApplication _application;
417

418
    /**
419
     * Gets the context params.
420
     *
421
     * @return the context params
422
     */
423
    private Hashtable getContextParams() {
424
        return _application.getContextParameters();
1✔
425
    }
426

427
    /**
428
     * Allows the test to determine where the log messages should be written. Defaults to {@link System#out}
429
     *
430
     * @param logStream
431
     *            where to write the log messages
432
     *
433
     * @see #log(String)
434
     */
435
    public void setLogStream(PrintStream logStream) {
UNCOV
436
        this._logStream = logStream;
×
UNCOV
437
    }
×
438

439
    @Override
440
    public int getEffectiveMajorVersion() {
441
        // TODO Auto-generated method stub
UNCOV
442
        return 0;
×
443
    }
444

445
    @Override
446
    public int getEffectiveMinorVersion() {
447
        // TODO Auto-generated method stub
UNCOV
448
        return 0;
×
449
    }
450

451
    @Override
452
    public boolean setInitParameter(String name, String value) {
UNCOV
453
        getContextParams().put(name, value);
×
UNCOV
454
        return true;
×
455
    }
456

457
    @Override
458
    public Dynamic addServlet(String servletName, String className) {
UNCOV
459
        return null;
×
460
    }
461

462
    @Override
463
    public Dynamic addServlet(String servletName, Servlet servlet) {
UNCOV
464
        return null;
×
465
    }
466

467
    @Override
468
    public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
UNCOV
469
        return null;
×
470
    }
471

472
    @Override
473
    public <T extends Servlet> T createServlet(Class<T> clazz) throws ServletException {
UNCOV
474
        return null;
×
475
    }
476

477
    @Override
478
    public ServletRegistration getServletRegistration(String servletName) {
UNCOV
479
        return null;
×
480
    }
481

482
    @Override
483
    public Map<String, ? extends ServletRegistration> getServletRegistrations() {
UNCOV
484
        return null;
×
485
    }
486

487
    @Override
488
    public FilterRegistration.Dynamic addFilter(String filterName, String className) {
UNCOV
489
        return null;
×
490
    }
491

492
    @Override
493
    public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
UNCOV
494
        return null;
×
495
    }
496

497
    @Override
498
    public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
UNCOV
499
        return null;
×
500
    }
501

502
    @Override
503
    public <T extends Filter> T createFilter(Class<T> clazz) throws ServletException {
UNCOV
504
        return null;
×
505
    }
506

507
    @Override
508
    public FilterRegistration getFilterRegistration(String filterName) {
UNCOV
509
        return null;
×
510
    }
511

512
    @Override
513
    public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
UNCOV
514
        return null;
×
515
    }
516

517
    @Override
518
    public SessionCookieConfig getSessionCookieConfig() {
UNCOV
519
        return null;
×
520
    }
521

522
    @Override
523
    public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) {
524

UNCOV
525
    }
×
526

527
    @Override
528
    public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
UNCOV
529
        return null;
×
530
    }
531

532
    @Override
533
    public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
534
        return null;
×
535
    }
536

537
    @Override
538
    public void addListener(String className) {
539

UNCOV
540
    }
×
541

542
    @Override
543
    public <T extends EventListener> void addListener(T t) {
544

UNCOV
545
    }
×
546

547
    @Override
548
    public void addListener(Class<? extends EventListener> listenerClass) {
549

UNCOV
550
    }
×
551

552
    @Override
553
    public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
554
        return null;
×
555
    }
556

557
    @Override
558
    public JspConfigDescriptor getJspConfigDescriptor() {
559
        return null;
×
560
    }
561

562
    @Override
563
    public ClassLoader getClassLoader() {
UNCOV
564
        return ServletUnitServletContext.class.getClassLoader();
×
565
    }
566

567
    @Override
568
    public void declareRoles(String... roleNames) {
569

UNCOV
570
    }
×
571

572
    @Override
573
    public String getVirtualServerName() {
UNCOV
574
        return null;
×
575
    }
576

577
    @Override
578
    public Dynamic addJspFile(String servletName, String jspFile) {
579
        return null;
×
580
    }
581

582
    @Override
583
    public int getSessionTimeout() {
UNCOV
584
        return 0;
×
585
    }
586

587
    @Override
588
    public void setSessionTimeout(int sessionTimeout) {
589

UNCOV
590
    }
×
591

592
    @Override
593
    public String getRequestCharacterEncoding() {
UNCOV
594
        return null;
×
595
    }
596

597
    @Override
598
    public void setRequestCharacterEncoding(String encoding) {
599

UNCOV
600
    }
×
601

602
    @Override
603
    public String getResponseCharacterEncoding() {
UNCOV
604
        return null;
×
605
    }
606

607
    @Override
608
    public void setResponseCharacterEncoding(String encoding) {
609

UNCOV
610
    }
×
611
}
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