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

hazendaz / httpunit / 755

14 Feb 2026 07:14PM UTC coverage: 80.526%. Remained the same
755

push

github

hazendaz
[ci] Fix badge

3213 of 4105 branches covered (78.27%)

Branch coverage included in aggregate %.

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
 * SPDX-License-Identifier: MIT
3
 * See LICENSE file for details.
4
 *
5
 * Copyright 2000-2026 Russell Gold
6
 * Copyright 2021-2000 hazendaz
7
 */
8
package com.meterware.servletunit;
9

10
import jakarta.servlet.*;
11
import jakarta.servlet.ServletRegistration.Dynamic;
12
import jakarta.servlet.descriptor.JspConfigDescriptor;
13

14
import java.io.File;
15
import java.io.IOException;
16
import java.io.PrintStream;
17
import java.net.MalformedURLException;
18
import java.net.URL;
19
import java.net.URLConnection;
20
import java.nio.file.Files;
21
import java.util.Enumeration;
22
import java.util.EventListener;
23
import java.util.Hashtable;
24
import java.util.Map;
25
import java.util.Set;
26

27
/**
28
 * This class is a private implementation of the ServletContext class.
29
 **/
30
public class ServletUnitServletContext implements ServletContext {
31

32
    /** The log stream. */
33
    private PrintStream _logStream = System.out;
1✔
34

35
    /**
36
     * Instantiates a new servlet unit servlet context.
37
     *
38
     * @param application
39
     *            the application
40
     */
41
    ServletUnitServletContext(WebApplication application) {
1✔
42
        _application = application;
1✔
43
    }
1✔
44

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

59
    /**
60
     * Returns the major version of the Java Servlet API that this servlet container supports. All implementations that
61
     * comply with Version 2.4 must have this method return the integer 2.
62
     **/
63
    @Override
64
    public int getMajorVersion() {
65
        return 4;
×
66
    }
67

68
    /**
69
     * Returns the minor version of the Servlet API that this servlet container supports. All implementations that
70
     * comply with Version 2.4 must have this method return the integer 4.
71
     **/
72
    @Override
73
    public int getMinorVersion() {
74
        return 0;
×
75
    }
76

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

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

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

132
    /**
133
     * Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A
134
     * RequestDispatcher object can be used to forward a request to the resource or to include the resource in a
135
     * response. The resource can be dynamic or static. The pathname must begin with a "/" and is interpreted as
136
     * relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign
137
     * contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.
138
     **/
139
    @Override
140
    public jakarta.servlet.RequestDispatcher getRequestDispatcher(String path) {
141
        try {
142
            URL url = new URL("http", "localhost", _application.getContextPath() + path);
1✔
143
            return new RequestDispatcherImpl(_application, url);
1✔
144
        } catch (ServletException | MalformedURLException e) {
×
145
            return null;
×
146
        }
147
    }
148

149
    /**
150
     * Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Servlets (and JSP pages also)
151
     * may be given names via server administration or via a web application deployment descriptor. A servlet instance
152
     * can determine its name using ServletConfig.getServletName(). This method returns null if the ServletContext
153
     * cannot return a RequestDispatcher for any reason. patch by Izzy Alanis
154
     *
155
     * @param servletName
156
     *            - the name of the dispatcher to get
157
     **/
158
    @Override
159
    public jakarta.servlet.RequestDispatcher getNamedDispatcher(java.lang.String servletName) {
160
        final WebApplication.ServletConfiguration servletConfig = _application.getServletByName(servletName);
1✔
161
        if (servletConfig == null) {
1!
162
            return null;
1✔
163
        }
164

165
        Servlet tempServlet;
166
        Exception tempException;
167

168
        try {
169
            tempServlet = servletConfig.getServlet();
×
170
            tempException = null;
×
171
        } catch (Exception e) {
×
172
            tempServlet = null;
×
173
            tempException = e;
×
174
        }
×
175

176
        final Servlet servlet = tempServlet;
×
177

178
        final Exception instantiationException = tempException;
×
179

180
        return new jakarta.servlet.RequestDispatcher() {
×
181

182
            @Override
183
            public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
184

185
                if (instantiationException != null) {
×
186

187
                    if (instantiationException instanceof ServletException) {
×
188
                        throw (ServletException) instantiationException;
×
189

190
                    }
191
                    ServletException e = new ServletException(instantiationException.getMessage());
×
192

193
                    e.initCause(instantiationException);
×
194

195
                    throw e;
×
196

197
                }
198

199
                if (servletConfig.getJspFile() != null) {
×
200
                    request.setAttribute("org.apache.catalina.jsp_file", servletConfig.getJspFile());
×
201
                }
202
                response.reset();
×
203
                servlet.service(request, response);
×
204
            }
×
205

206
            @Override
207
            public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
208
                if (instantiationException != null) {
×
209
                    if (instantiationException instanceof ServletException) {
×
210
                        throw (ServletException) instantiationException;
×
211
                    }
212
                    ServletException e = new ServletException(instantiationException.getMessage());
×
213
                    e.initCause(instantiationException);
×
214
                    throw e;
×
215
                }
216
                if (servletConfig.getJspFile() != null) {
×
217
                    request.setAttribute("org.apache.catalina.jsp_file", servletConfig.getJspFile());
×
218
                }
219
                servlet.service(request, response);
×
220
            }
×
221
        };
222
    }
223

224
    /**
225
     * Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log
226
     * file is specific to the servlet container.
227
     **/
228
    @Override
229
    public void log(String message) {
230
        _logStream.println(message);
×
231
    }
×
232

233
    /**
234
     * Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. The name
235
     * and type of the servlet log file is specific to the servlet container, usually an event log.
236
     **/
237
    @Override
238
    public void log(String message, Throwable t) {
239
        _logStream.print(message);
×
240
        _logStream.print(":");
×
241
        if (t != null) {
×
242
            t.printStackTrace(_logStream);
×
243
        }
244
    }
×
245

246
    /**
247
     * Returns a String containing the real path for a given virtual path. For example, the virtual path "/index.html"
248
     * has a real path of whatever file on the server's filesystem would be served by a request for "/index.html". The
249
     * real path returned will be in a form appropriate to the computer and operating system on which the servlet
250
     * container is running, including the proper path separators. This method returns null if the servlet container
251
     * cannot translate the virtual path to a real path for any reason (such as when the content is being made available
252
     * from a .war archive).
253
     **/
254
    @Override
255
    public String getRealPath(String path) {
256
        return _application.getResourceFile(path).getAbsolutePath();
1✔
257
    }
258

259
    /** The Constant DEFAULT_SERVER_INFO. */
260
    public static final String DEFAULT_SERVER_INFO = "ServletUnit test framework";
261

262
    /**
263
     * Returns the name and version of the servlet container on which the servlet is running. The form of the returned
264
     * string is servername/versionnumber. For example, the JavaServer Web Development Kit may return the string
265
     * JavaServer Web Dev Kit/1.0. The servlet container may return other optional information after the primary string
266
     * in parentheses, for example, JavaServer Web Dev Kit/1.0 (JDK 1.1.6; Windows NT 4.0 x86).
267
     **/
268
    @Override
269
    public String getServerInfo() {
270
        return DEFAULT_SERVER_INFO;
×
271
    }
272

273
    /**
274
     * Returns a String containing the value of the named context-wide initialization parameter, or null if the
275
     * parameter does not exist. This method can make available configuration information useful to an entire "web
276
     * application". For example, it can provide a webmaster's email address or the name of a system that holds critical
277
     * data.
278
     **/
279
    @Override
280
    public String getInitParameter(String name) {
281
        return (String) getContextParams().get(name);
1✔
282
    }
283

284
    /**
285
     * Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty
286
     * Enumeration if the context has no initialization parameters.
287
     **/
288
    @Override
289
    public Enumeration<String> getInitParameterNames() {
290
        return getContextParams().keys();
×
291
    }
292

293
    /**
294
     * Returns the servlet container attribute with the given name, or null if there is no attribute by that name. An
295
     * attribute allows a servlet container to give the servlet additional information not already provided by this
296
     * interface. See your server documentation for information about its attributes. A list of supported attributes can
297
     * be retrieved using getAttributeNames.
298
     **/
299
    @Override
300
    public Object getAttribute(String name) {
301
        return _attributes.get(name);
1✔
302
    }
303

304
    @Override
305
    public Enumeration<String> getAttributeNames() {
306
        return _attributes.keys();
×
307
    }
308

309
    @Override
310
    public void setAttribute(String name, Object attribute) {
311
        if (!_attributes.containsKey(name)) {
1✔
312
            _attributes.put(name, attribute);
1✔
313
            _application.sendAttributeAdded(name, attribute);
1✔
314
        } else {
315
            Object oldValue = _attributes.get(name);
1✔
316
            _attributes.put(name, attribute);
1✔
317
            _application.sendAttributeReplaced(name, oldValue);
1✔
318
        }
319
    }
1✔
320

321
    @Override
322
    public void removeAttribute(String name) {
323
        Object oldValue = _attributes.get(name);
1✔
324
        _attributes.remove(name);
1✔
325
        _application.sendAttributeRemoved(name, oldValue);
1✔
326
    }
1✔
327

328
    // ----------------------------- methods added to ServletContext in JSDK 2.3
329
    // --------------------------------------
330

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

353
    /**
354
     * Returns the name of this web application correponding to this ServletContext as specified in the deployment
355
     * descriptor for this web application by the display-name element.
356
     *
357
     * @return The name of the web application or null if no name has been declared in the deployment descriptor
358
     */
359
    @Override
360
    public String getServletContextName() {
361
        return _application.getDisplayName();
1✔
362
    }
363

364
    // -------------------------------------- servlet-api 2.5 additions
365
    // -----------------------------------------------
366

367
    @Override
368
    public String getContextPath() {
369
        return null;
×
370
    }
371

372
    // ------------------------------------------- package members
373
    // ----------------------------------------------------
374

375
    /**
376
     * Sets the init parameter.
377
     *
378
     * @param name
379
     *            the name
380
     * @param initParameter
381
     *            the init parameter
382
     */
383
    void setInitParameter(String name, Object initParameter) {
384
        getContextParams().put(name, initParameter);
×
385
    }
×
386

387
    /**
388
     * Removes the init parameter.
389
     *
390
     * @param name
391
     *            the name
392
     */
393
    void removeInitParameter(String name) {
394
        getContextParams().remove(name);
×
395
    }
×
396

397
    // ------------------------------------------- private members
398
    // ----------------------------------------------------
399

400
    /** The attributes. */
401
    private Hashtable _attributes = new Hashtable<>();
1✔
402

403
    /** The application. */
404
    private WebApplication _application;
405

406
    /**
407
     * Gets the context params.
408
     *
409
     * @return the context params
410
     */
411
    private Hashtable getContextParams() {
412
        return _application.getContextParameters();
1✔
413
    }
414

415
    /**
416
     * Allows the test to determine where the log messages should be written. Defaults to {@link System#out}
417
     *
418
     * @param logStream
419
     *            where to write the log messages
420
     *
421
     * @see #log(String)
422
     */
423
    public void setLogStream(PrintStream logStream) {
424
        this._logStream = logStream;
×
425
    }
×
426

427
    @Override
428
    public int getEffectiveMajorVersion() {
429
        // TODO Auto-generated method stub
430
        return 0;
×
431
    }
432

433
    @Override
434
    public int getEffectiveMinorVersion() {
435
        // TODO Auto-generated method stub
436
        return 0;
×
437
    }
438

439
    @Override
440
    public boolean setInitParameter(String name, String value) {
441
        getContextParams().put(name, value);
×
442
        return true;
×
443
    }
444

445
    @Override
446
    public Dynamic addServlet(String servletName, String className) {
447
        return null;
×
448
    }
449

450
    @Override
451
    public Dynamic addServlet(String servletName, Servlet servlet) {
452
        return null;
×
453
    }
454

455
    @Override
456
    public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
457
        return null;
×
458
    }
459

460
    @Override
461
    public <T extends Servlet> T createServlet(Class<T> clazz) throws ServletException {
462
        return null;
×
463
    }
464

465
    @Override
466
    public ServletRegistration getServletRegistration(String servletName) {
467
        return null;
×
468
    }
469

470
    @Override
471
    public Map<String, ? extends ServletRegistration> getServletRegistrations() {
472
        return null;
×
473
    }
474

475
    @Override
476
    public FilterRegistration.Dynamic addFilter(String filterName, String className) {
477
        return null;
×
478
    }
479

480
    @Override
481
    public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
482
        return null;
×
483
    }
484

485
    @Override
486
    public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
487
        return null;
×
488
    }
489

490
    @Override
491
    public <T extends Filter> T createFilter(Class<T> clazz) throws ServletException {
492
        return null;
×
493
    }
494

495
    @Override
496
    public FilterRegistration getFilterRegistration(String filterName) {
497
        return null;
×
498
    }
499

500
    @Override
501
    public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
502
        return null;
×
503
    }
504

505
    @Override
506
    public SessionCookieConfig getSessionCookieConfig() {
507
        return null;
×
508
    }
509

510
    @Override
511
    public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) {
512

513
    }
×
514

515
    @Override
516
    public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
517
        return null;
×
518
    }
519

520
    @Override
521
    public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
522
        return null;
×
523
    }
524

525
    @Override
526
    public void addListener(String className) {
527

528
    }
×
529

530
    @Override
531
    public <T extends EventListener> void addListener(T t) {
532

533
    }
×
534

535
    @Override
536
    public void addListener(Class<? extends EventListener> listenerClass) {
537

538
    }
×
539

540
    @Override
541
    public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
542
        return null;
×
543
    }
544

545
    @Override
546
    public JspConfigDescriptor getJspConfigDescriptor() {
547
        return null;
×
548
    }
549

550
    @Override
551
    public ClassLoader getClassLoader() {
552
        return ServletUnitServletContext.class.getClassLoader();
×
553
    }
554

555
    @Override
556
    public void declareRoles(String... roleNames) {
557

558
    }
×
559

560
    @Override
561
    public String getVirtualServerName() {
562
        return null;
×
563
    }
564

565
    @Override
566
    public Dynamic addJspFile(String servletName, String jspFile) {
567
        return null;
×
568
    }
569

570
    @Override
571
    public int getSessionTimeout() {
572
        return 0;
×
573
    }
574

575
    @Override
576
    public void setSessionTimeout(int sessionTimeout) {
577

578
    }
×
579

580
    @Override
581
    public String getRequestCharacterEncoding() {
582
        return null;
×
583
    }
584

585
    @Override
586
    public void setRequestCharacterEncoding(String encoding) {
587

588
    }
×
589

590
    @Override
591
    public String getResponseCharacterEncoding() {
592
        return null;
×
593
    }
594

595
    @Override
596
    public void setResponseCharacterEncoding(String encoding) {
597

598
    }
×
599
}
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