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

hazendaz / httpunit / 636

05 Dec 2025 03:27AM UTC coverage: 80.509%. Remained the same
636

push

github

hazendaz
Cleanup more old since tags

you guessed it, at this point going to jautodoc the rest so the warnings on builds go away ;)

3213 of 4105 branches covered (78.27%)

Branch coverage included in aggregate %.

8249 of 10132 relevant lines covered (81.42%)

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.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.IOException;
30
import java.io.PrintStream;
31
import java.net.MalformedURLException;
32
import java.net.URL;
33
import java.net.URLConnection;
34
import java.util.Enumeration;
35
import java.util.EventListener;
36
import java.util.Hashtable;
37
import java.util.Map;
38
import java.util.Set;
39

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

45
    private PrintStream _logStream = System.out;
1✔
46

47
    ServletUnitServletContext(WebApplication application) {
1✔
48
        _application = application;
1✔
49
    }
1✔
50

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

65
    /**
66
     * Returns the major version of the Java Servlet API that this servlet container supports. All implementations that
67
     * comply with Version 2.4 must have this method return the integer 2.
68
     **/
69
    @Override
70
    public int getMajorVersion() {
71
        return 4;
×
72
    }
73

74
    /**
75
     * Returns the minor version of the Servlet API that this servlet container supports. All implementations that
76
     * comply with Version 2.4 must have this method return the integer 4.
77
     **/
78
    @Override
79
    public int getMinorVersion() {
80
        return 0;
×
81
    }
82

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

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

121
            return resourceFile == null || !resourceFile.exists() ? null : resourceFile.toURI().toURL();
1!
122
        } catch (MalformedURLException e) {
×
123
            return null;
×
124
        }
125
    }
126

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

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

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

179
        Servlet tempServlet;
180
        Exception tempException;
181

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

190
        final Servlet servlet = tempServlet;
×
191

192
        final Exception instantiationException = tempException;
×
193

194
        return new jakarta.servlet.RequestDispatcher() {
×
195

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

199
                if (instantiationException != null) {
×
200

201
                    if (instantiationException instanceof ServletException) {
×
202
                        throw (ServletException) instantiationException;
×
203

204
                    }
205
                    ServletException e = new ServletException(instantiationException.getMessage());
×
206

207
                    e.initCause(instantiationException);
×
208

209
                    throw e;
×
210

211
                }
212

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

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

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

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

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

273
    public static final String DEFAULT_SERVER_INFO = "ServletUnit test framework";
274

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

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

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

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

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

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

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

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

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

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

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

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

385
    // ------------------------------------------- package members
386
    // ----------------------------------------------------
387

388
    void setInitParameter(String name, Object initParameter) {
389
        getContextParams().put(name, initParameter);
×
390
    }
×
391

392
    void removeInitParameter(String name) {
393
        getContextParams().remove(name);
×
394
    }
×
395

396
    // ------------------------------------------- private members
397
    // ----------------------------------------------------
398

399
    private Hashtable _attributes = new Hashtable<>();
1✔
400

401
    private WebApplication _application;
402

403
    private Hashtable getContextParams() {
404
        return _application.getContextParameters();
1✔
405
    }
406

407
    /**
408
     * Allows the test to determine where the log messages should be written. Defaults to {@link System#out}
409
     *
410
     * @param logStream
411
     *            where to write the log messages
412
     *
413
     * @see #log(String)
414
     */
415
    public void setLogStream(PrintStream logStream) {
416
        this._logStream = logStream;
×
417
    }
×
418

419
    @Override
420
    public int getEffectiveMajorVersion() {
421
        // TODO Auto-generated method stub
422
        return 0;
×
423
    }
424

425
    @Override
426
    public int getEffectiveMinorVersion() {
427
        // TODO Auto-generated method stub
428
        return 0;
×
429
    }
430

431
    @Override
432
    public boolean setInitParameter(String name, String value) {
433
        getContextParams().put(name, value);
×
434
        return true;
×
435
    }
436

437
    @Override
438
    public Dynamic addServlet(String servletName, String className) {
439
        return null;
×
440
    }
441

442
    @Override
443
    public Dynamic addServlet(String servletName, Servlet servlet) {
444
        return null;
×
445
    }
446

447
    @Override
448
    public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
449
        return null;
×
450
    }
451

452
    @Override
453
    public <T extends Servlet> T createServlet(Class<T> clazz) throws ServletException {
454
        return null;
×
455
    }
456

457
    @Override
458
    public ServletRegistration getServletRegistration(String servletName) {
459
        return null;
×
460
    }
461

462
    @Override
463
    public Map<String, ? extends ServletRegistration> getServletRegistrations() {
464
        return null;
×
465
    }
466

467
    @Override
468
    public FilterRegistration.Dynamic addFilter(String filterName, String className) {
469
        return null;
×
470
    }
471

472
    @Override
473
    public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
474
        return null;
×
475
    }
476

477
    @Override
478
    public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
479
        return null;
×
480
    }
481

482
    @Override
483
    public <T extends Filter> T createFilter(Class<T> clazz) throws ServletException {
484
        return null;
×
485
    }
486

487
    @Override
488
    public FilterRegistration getFilterRegistration(String filterName) {
489
        return null;
×
490
    }
491

492
    @Override
493
    public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
494
        return null;
×
495
    }
496

497
    @Override
498
    public SessionCookieConfig getSessionCookieConfig() {
499
        return null;
×
500
    }
501

502
    @Override
503
    public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) {
504

505
    }
×
506

507
    @Override
508
    public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
509
        return null;
×
510
    }
511

512
    @Override
513
    public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
514
        return null;
×
515
    }
516

517
    @Override
518
    public void addListener(String className) {
519

520
    }
×
521

522
    @Override
523
    public <T extends EventListener> void addListener(T t) {
524

525
    }
×
526

527
    @Override
528
    public void addListener(Class<? extends EventListener> listenerClass) {
529

530
    }
×
531

532
    @Override
533
    public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
534
        return null;
×
535
    }
536

537
    @Override
538
    public JspConfigDescriptor getJspConfigDescriptor() {
539
        return null;
×
540
    }
541

542
    @Override
543
    public ClassLoader getClassLoader() {
544
        return ServletUnitServletContext.class.getClassLoader();
×
545
    }
546

547
    @Override
548
    public void declareRoles(String... roleNames) {
549

550
    }
×
551

552
    @Override
553
    public String getVirtualServerName() {
554
        return null;
×
555
    }
556

557
    @Override
558
    public Dynamic addJspFile(String servletName, String jspFile) {
559
        return null;
×
560
    }
561

562
    @Override
563
    public int getSessionTimeout() {
564
        return 0;
×
565
    }
566

567
    @Override
568
    public void setSessionTimeout(int sessionTimeout) {
569

570
    }
×
571

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

577
    @Override
578
    public void setRequestCharacterEncoding(String encoding) {
579

580
    }
×
581

582
    @Override
583
    public String getResponseCharacterEncoding() {
584
        return null;
×
585
    }
586

587
    @Override
588
    public void setResponseCharacterEncoding(String encoding) {
589

590
    }
×
591
}
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