• 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

26.32
/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 java.io.File;
23
import java.io.IOException;
24
import java.io.PrintStream;
25
import java.net.MalformedURLException;
26
import java.net.URL;
27
import java.net.URLConnection;
28
import java.nio.file.Files;
29
import java.util.Collections;
30
import java.util.Enumeration;
31
import java.util.EventListener;
32
import java.util.Hashtable;
33
import java.util.Map;
34
import java.util.Set;
35

36
import javax.servlet.Filter;
37
import javax.servlet.FilterRegistration;
38
import javax.servlet.Servlet;
39
import javax.servlet.ServletContext;
40
import javax.servlet.ServletException;
41
import javax.servlet.ServletRegistration;
42
import javax.servlet.ServletRegistration.Dynamic;
43
import javax.servlet.ServletRequest;
44
import javax.servlet.ServletResponse;
45
import javax.servlet.SessionCookieConfig;
46
import javax.servlet.SessionTrackingMode;
47
import javax.servlet.descriptor.JspConfigDescriptor;
48

49
/**
50
 * This class is a private implementation of the ServletContext class.
51
 **/
52
public class ServletUnitServletContext implements ServletContext {
53

54
    /** The log stream. */
55
    private PrintStream _logStream = System.out;
1✔
56

57
    /**
58
     * Instantiates a new servlet unit servlet context.
59
     *
60
     * @param application
61
     *            the application
62
     */
63
    ServletUnitServletContext(WebApplication application) {
1✔
64
        _application = application;
1✔
65
    }
1✔
66

67
    /**
68
     * Returns a ServletContext object that corresponds to a specified URL on the server.
69
     * <p>
70
     * This method allows servlets to gain access to the context for various parts of the server, and as needed obtain
71
     * RequestDispatcher objects from the context. The given path must be absolute (beginning with "/") and is
72
     * interpreted based on the server's document root.
73
     * <p>
74
     * In a security conscious environment, the servlet container may return null for a given URL.
75
     **/
76
    @Override
77
    public javax.servlet.ServletContext getContext(java.lang.String A) {
78
        return null;
×
79
    }
80

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

90
    /**
91
     * Returns the minor version of the Servlet API that this servlet container supports. All implementations that
92
     * comply with Version 2.4 must have this method return the integer 4.
93
     **/
94
    @Override
95
    public int getMinorVersion() {
96
        return 0;
×
97
    }
98

99
    /**
100
     * Returns the MIME type of the specified file, or null if the MIME type is not known. The MIME type is determined
101
     * by the configuration of the servlet container, and may be specified in a web application deployment descriptor.
102
     * Common MIME types are "text/html" and "image/gif".
103
     **/
104
    @Override
105
    public java.lang.String getMimeType(String filePath) {
106
        return URLConnection.getFileNameMap().getContentTypeFor(filePath);
1✔
107
    }
108

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

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

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

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

187
        Servlet tempServlet;
188
        Exception tempException;
189

190
        try {
191
            tempServlet = servletConfig.getServlet();
×
192
            tempException = null;
×
193
        } catch (Exception e) {
×
194
            tempServlet = null;
×
195
            tempException = e;
×
196
        }
×
197

198
        final Servlet servlet = tempServlet;
×
199

200
        final Exception instantiationException = tempException;
×
201

202
        return new javax.servlet.RequestDispatcher() {
×
203

204
            @Override
205
            public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
206

207
                if (instantiationException != null) {
×
208

209
                    if (instantiationException instanceof ServletException) {
×
210
                        throw (ServletException) instantiationException;
×
211

212
                    }
213
                    ServletException e = new ServletException(instantiationException.getMessage());
×
214

215
                    e.initCause(instantiationException);
×
216

217
                    throw e;
×
218

219
                }
220

221
                if (servletConfig.getJspFile() != null) {
×
222
                    request.setAttribute("org.apache.catalina.jsp_file", servletConfig.getJspFile());
×
223
                }
224
                response.reset();
×
225
                servlet.service(request, response);
×
226
            }
×
227

228
            @Override
229
            public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
230
                if (instantiationException != null) {
×
231
                    if (instantiationException instanceof ServletException) {
×
232
                        throw (ServletException) instantiationException;
×
233
                    }
234
                    ServletException e = new ServletException(instantiationException.getMessage());
×
235
                    e.initCause(instantiationException);
×
236
                    throw e;
×
237
                }
238
                if (servletConfig.getJspFile() != null) {
×
239
                    request.setAttribute("org.apache.catalina.jsp_file", servletConfig.getJspFile());
×
240
                }
241
                servlet.service(request, response);
×
242
            }
×
243
        };
244
    }
245

246
    /**
247
     * @deprecated as of Servlet API 2.1
248
     **/
249
    @Deprecated
250
    @Override
251
    public javax.servlet.Servlet getServlet(java.lang.String A) {
252
        return null;
×
253
    }
254

255
    /**
256
     * @deprecated as of Servlet API 2.0
257
     **/
258
    @Deprecated
259
    @Override
260
    public Enumeration<Servlet> getServlets() {
261
        return Collections.emptyEnumeration();
×
262
    }
263

264
    /**
265
     * @deprecated as of Servlet API 2.1
266
     **/
267
    @Deprecated
268
    @Override
269
    public Enumeration<String> getServletNames() {
270
        return Collections.emptyEnumeration();
×
271
    }
272

273
    /**
274
     * Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log
275
     * file is specific to the servlet container.
276
     **/
277
    @Override
278
    public void log(String message) {
279
        _logStream.println(message);
×
280
    }
×
281

282
    /**
283
     * @deprecated use log( String, Throwable )
284
     **/
285
    @Deprecated
286
    @Override
287
    public void log(Exception e, String message) {
288
        log(message, e);
×
289
    }
×
290

291
    /**
292
     * Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. The name
293
     * and type of the servlet log file is specific to the servlet container, usually an event log.
294
     **/
295
    @Override
296
    public void log(String message, Throwable t) {
297
        _logStream.print(message);
×
298
        _logStream.print(":");
×
299
        if (t != null) {
×
300
            t.printStackTrace(_logStream);
×
301
        }
302
    }
×
303

304
    /**
305
     * Returns a String containing the real path for a given virtual path. For example, the virtual path "/index.html"
306
     * has a real path of whatever file on the server's filesystem would be served by a request for "/index.html". The
307
     * real path returned will be in a form appropriate to the computer and operating system on which the servlet
308
     * container is running, including the proper path separators. This method returns null if the servlet container
309
     * cannot translate the virtual path to a real path for any reason (such as when the content is being made available
310
     * from a .war archive).
311
     **/
312
    @Override
313
    public String getRealPath(String path) {
314
        return _application.getResourceFile(path).getAbsolutePath();
1✔
315
    }
316

317
    /** The Constant DEFAULT_SERVER_INFO. */
318
    public static final String DEFAULT_SERVER_INFO = "ServletUnit test framework";
319

320
    /**
321
     * Returns the name and version of the servlet container on which the servlet is running. The form of the returned
322
     * string is servername/versionnumber. For example, the JavaServer Web Development Kit may return the string
323
     * JavaServer Web Dev Kit/1.0. The servlet container may return other optional information after the primary string
324
     * in parentheses, for example, JavaServer Web Dev Kit/1.0 (JDK 1.1.6; Windows NT 4.0 x86).
325
     **/
326
    @Override
327
    public String getServerInfo() {
328
        return DEFAULT_SERVER_INFO;
×
329
    }
330

331
    /**
332
     * Returns a String containing the value of the named context-wide initialization parameter, or null if the
333
     * parameter does not exist. This method can make available configuration information useful to an entire "web
334
     * application". For example, it can provide a webmaster's email address or the name of a system that holds critical
335
     * data.
336
     **/
337
    @Override
338
    public String getInitParameter(String name) {
339
        return (String) getContextParams().get(name);
1✔
340
    }
341

342
    /**
343
     * Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty
344
     * Enumeration if the context has no initialization parameters.
345
     **/
346
    @Override
347
    public Enumeration<String> getInitParameterNames() {
348
        return getContextParams().keys();
×
349
    }
350

351
    /**
352
     * Returns the servlet container attribute with the given name, or null if there is no attribute by that name. An
353
     * attribute allows a servlet container to give the servlet additional information not already provided by this
354
     * interface. See your server documentation for information about its attributes. A list of supported attributes can
355
     * be retrieved using getAttributeNames.
356
     **/
357
    @Override
358
    public Object getAttribute(String name) {
359
        return _attributes.get(name);
1✔
360
    }
361

362
    @Override
363
    public Enumeration<String> getAttributeNames() {
364
        return _attributes.keys();
×
365
    }
366

367
    @Override
368
    public void setAttribute(String name, Object attribute) {
369
        if (!_attributes.containsKey(name)) {
1✔
370
            _attributes.put(name, attribute);
1✔
371
            _application.sendAttributeAdded(name, attribute);
1✔
372
        } else {
373
            Object oldValue = _attributes.get(name);
1✔
374
            _attributes.put(name, attribute);
1✔
375
            _application.sendAttributeReplaced(name, oldValue);
1✔
376
        }
377
    }
1✔
378

379
    @Override
380
    public void removeAttribute(String name) {
381
        Object oldValue = _attributes.get(name);
1✔
382
        _attributes.remove(name);
1✔
383
        _application.sendAttributeRemoved(name, oldValue);
1✔
384
    }
1✔
385

386
    // ----------------------------- methods added to ServletContext in JSDK 2.3
387
    // --------------------------------------
388

389
    /**
390
     * Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path
391
     * matches the supplied path argument. Paths indicating subdirectory paths end with a '/'. The returned paths are
392
     * all relative to the root of the web application and have a leading '/'. For example, for a web application
393
     * containing &lt;p&gt; /welcome.html&lt;br /&gt; /catalog/index.html&lt;br /&gt; &lt;br /&gt;
394
     * /catalog/products.html&lt;br /&gt; /catalog/offers/books.html&lt;br /&gt; /catalog/offers/music.html&lt;br /&gt;
395
     * /customer/login.jsp&lt;br /&gt; /WEB-INF/web.xml&lt;br /&gt; /WEB-INF/classes/com.acme.OrderServlet.class,&lt;br
396
     * /&gt; &lt;br /&gt; getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"}&lt;br
397
     * /&gt; getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html",
398
     * "/catalog/offers/"}.
399
     *
400
     * @param path
401
     *            partial path used to match the resources, which must start with a /
402
     *
403
     * @return a Set containing the directory listing, or null if there are no resources in the web application whose
404
     *         path begins with the supplied path.
405
     */
406
    @Override
407
    public Set<String> getResourcePaths(String path) {
408
        return null;
×
409
    }
410

411
    /**
412
     * Returns the name of this web application correponding to this ServletContext as specified in the deployment
413
     * descriptor for this web application by the display-name element.
414
     *
415
     * @return The name of the web application or null if no name has been declared in the deployment descriptor
416
     */
417
    @Override
418
    public String getServletContextName() {
419
        return _application.getDisplayName();
1✔
420
    }
421

422
    // -------------------------------------- servlet-api 2.5 additions
423
    // -----------------------------------------------
424

425
    @Override
426
    public String getContextPath() {
427
        return null;
×
428
    }
429

430
    // ------------------------------------------- package members
431
    // ----------------------------------------------------
432

433
    /**
434
     * Sets the init parameter.
435
     *
436
     * @param name
437
     *            the name
438
     * @param initParameter
439
     *            the init parameter
440
     */
441
    void setInitParameter(String name, Object initParameter) {
442
        getContextParams().put(name, initParameter);
×
443
    }
×
444

445
    /**
446
     * Removes the init parameter.
447
     *
448
     * @param name
449
     *            the name
450
     */
451
    void removeInitParameter(String name) {
452
        getContextParams().remove(name);
×
453
    }
×
454

455
    // ------------------------------------------- private members
456
    // ----------------------------------------------------
457

458
    /** The attributes. */
459
    private Hashtable _attributes = new Hashtable<>();
1✔
460

461
    /** The application. */
462
    private WebApplication _application;
463

464
    /**
465
     * Gets the context params.
466
     *
467
     * @return the context params
468
     */
469
    private Hashtable getContextParams() {
470
        return _application.getContextParameters();
1✔
471
    }
472

473
    /**
474
     * Allows the test to determine where the log messages should be written. Defaults to {@link System#out}
475
     *
476
     * @param logStream
477
     *            where to write the log messages
478
     *
479
     * @see #log(String)
480
     */
481
    public void setLogStream(PrintStream logStream) {
482
        this._logStream = logStream;
×
483
    }
×
484

485
    @Override
486
    public int getEffectiveMajorVersion() {
487
        // TODO Auto-generated method stub
488
        return 0;
×
489
    }
490

491
    @Override
492
    public int getEffectiveMinorVersion() {
493
        // TODO Auto-generated method stub
494
        return 0;
×
495
    }
496

497
    @Override
498
    public boolean setInitParameter(String name, String value) {
499
        getContextParams().put(name, value);
×
500
        return true;
×
501
    }
502

503
    @Override
504
    public Dynamic addServlet(String servletName, String className) {
505
        return null;
×
506
    }
507

508
    @Override
509
    public Dynamic addServlet(String servletName, Servlet servlet) {
510
        return null;
×
511
    }
512

513
    @Override
514
    public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
515
        return null;
×
516
    }
517

518
    @Override
519
    public <T extends Servlet> T createServlet(Class<T> clazz) throws ServletException {
520
        return null;
×
521
    }
522

523
    @Override
524
    public ServletRegistration getServletRegistration(String servletName) {
525
        return null;
×
526
    }
527

528
    @Override
529
    public Map<String, ? extends ServletRegistration> getServletRegistrations() {
530
        return null;
×
531
    }
532

533
    @Override
534
    public FilterRegistration.Dynamic addFilter(String filterName, String className) {
535
        return null;
×
536
    }
537

538
    @Override
539
    public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
540
        return null;
×
541
    }
542

543
    @Override
544
    public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
545
        return null;
×
546
    }
547

548
    @Override
549
    public <T extends Filter> T createFilter(Class<T> clazz) throws ServletException {
550
        return null;
×
551
    }
552

553
    @Override
554
    public FilterRegistration getFilterRegistration(String filterName) {
555
        return null;
×
556
    }
557

558
    @Override
559
    public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
560
        return null;
×
561
    }
562

563
    @Override
564
    public SessionCookieConfig getSessionCookieConfig() {
565
        return null;
×
566
    }
567

568
    @Override
569
    public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) {
570

571
    }
×
572

573
    @Override
574
    public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
575
        return null;
×
576
    }
577

578
    @Override
579
    public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
580
        return null;
×
581
    }
582

583
    @Override
584
    public void addListener(String className) {
585

586
    }
×
587

588
    @Override
589
    public <T extends EventListener> void addListener(T t) {
590

591
    }
×
592

593
    @Override
594
    public void addListener(Class<? extends EventListener> listenerClass) {
595

596
    }
×
597

598
    @Override
599
    public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
600
        return null;
×
601
    }
602

603
    @Override
604
    public JspConfigDescriptor getJspConfigDescriptor() {
605
        return null;
×
606
    }
607

608
    @Override
609
    public ClassLoader getClassLoader() {
610
        return ServletUnitServletContext.class.getClassLoader();
×
611
    }
612

613
    @Override
614
    public void declareRoles(String... roleNames) {
615

616
    }
×
617

618
    @Override
619
    public String getVirtualServerName() {
620
        return null;
×
621
    }
622

623
    @Override
624
    public Dynamic addJspFile(String servletName, String jspFile) {
625
        return null;
×
626
    }
627

628
    @Override
629
    public int getSessionTimeout() {
630
        return 0;
×
631
    }
632

633
    @Override
634
    public void setSessionTimeout(int sessionTimeout) {
635

636
    }
×
637

638
    @Override
639
    public String getRequestCharacterEncoding() {
640
        return null;
×
641
    }
642

643
    @Override
644
    public void setRequestCharacterEncoding(String encoding) {
645

646
    }
×
647

648
    @Override
649
    public String getResponseCharacterEncoding() {
650
        return null;
×
651
    }
652

653
    @Override
654
    public void setResponseCharacterEncoding(String encoding) {
655

656
    }
×
657
}
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