001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.microservice.jetty;
018
019import static org.apache.juneau.commons.reflect.ReflectionUtils.*;
020import static org.apache.juneau.commons.utils.IoUtils.*;
021import static org.apache.juneau.commons.utils.ObjectUtils.*;
022import static org.apache.juneau.commons.utils.Shorts.*;
023import static org.apache.juneau.commons.utils.StringUtils.*;
024import static org.apache.juneau.commons.utils.ThrowableUtils.*;
025import static org.apache.juneau.marshall.collections.JsonMap.*;
026
027import java.io.*;
028import java.net.*;
029import java.nio.file.*;
030import java.nio.file.attribute.*;
031import java.time.*;
032import java.util.*;
033import java.util.concurrent.atomic.*;
034import java.util.logging.*;
035
036import org.apache.juneau.commons.inject.*;
037import org.apache.juneau.commons.reflect.*;
038import org.apache.juneau.config.event.*;
039import org.apache.juneau.marshall.cp.*;
040import org.apache.juneau.microservice.*;
041import org.apache.juneau.rest.server.*;
042import org.apache.juneau.rest.server.health.*;
043import org.apache.juneau.rest.server.servlet.*;
044import org.eclipse.jetty.ee11.servlet.*;
045import org.eclipse.jetty.server.*;
046
047import jakarta.servlet.*;
048
049/**
050 * Drives the Jetty server lifecycle on behalf of the microservice via the {@link MicroserviceListener} fan-out.
051 *
052 * <p>
053 * Contributed by {@link JettyConfiguration} as a <c>@Bean</c>.  The microservice's {@link Microservice#start()}
054 * call invokes {@link #onStart(Microservice)}, which:
055 * <ol>
056 *    <li>Picks the first available port from the resolved {@link JettySettings#getPorts() ports} (falling back to
057 *       <c>Jetty/port</c> config, then <c>Jetty-Port</c> manifest, then <c>8000</c>).
058 *    <li>Resolves the Jetty {@link Server} — preferring an externally-supplied <c>@Bean Server</c>, otherwise
059 *       building one from <c>jetty.xml</c> via the {@link JettyServerFactory}.
060 *    <li>Mounts servlets from {@code Jetty/servlets}, {@code Jetty/servletMap}, {@code Jetty/servletAttributes}
061 *       config sections, plus auto-mounts every {@code @Bean Servlet} whose runtime class is annotated with
062 *       {@link Rest @Rest} (at {@link Rest#path()}, or <c>"/"</c> when no path is set).
063 *    <li>Mounts every <c>@Bean</c> {@link ServletFilterRegistration} (and the <c>@Bean</c> <c>AuthFilterChain</c>, at
064 *       <c>/*</c>, unless a registration already wraps it) in {@link ServletFilterRegistration#getOrder() order}.
065 *    <li>Starts the server and publishes the bound port via the {@code availablePort} / {@code juneau.serverPort}
066 *       system properties.
067 * </ol>
068 *
069 * <p>
070 * {@link #onStop(Microservice)} performs the inverse: stops the server gracefully in a worker thread.
071 *
072 * <p>
073 * External callers reach this component via
074 * {@code Microservice.getInstance().getBeanStore().getBean(JettyServerComponent.class).orElseThrow()}.
075 *
076 * <h2 class='section'>See Also:</h2><ul>
077 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauMicroserviceJetty">juneau-microservice-jetty</a>
078 * </ul>
079 *
080 * @since 10.0.0
081 */
082@SuppressWarnings({
083   "java:S115", // Constants use UPPER_snakeCase convention (e.g., KEY_SERVLET_CONTEXT_HANDLER)
084   "java:S3878", // Array wrapper required to dispatch to varargs overload; without it the call recurses infinitely back to this single-String overload.
085   "resource" // ms.getBeanStore() is owned by the microservice lifecycle; do not close here.
086})
087public class JettyServerComponent implements MicroserviceListener {
088
089   private static final String KEY_SERVLET_CONTEXT_HANDLER = "ServletContextHandler";
090
091   @SuppressWarnings({
092      "java:S2245" // Used only to pick a benign ephemeral listen port (non security-sensitive); SecureRandom is unnecessary.
093   })
094   private static final Random RANDOM = new Random();
095
096   /** Default bounded graceful-shutdown drain timeout applied to the Jetty server when none is configured. */
097   static final Duration DEFAULT_STOP_TIMEOUT = Duration.ofSeconds(30);
098
099   private final Messages messages = Messages.of(JettyServerComponent.class);
100   private final AtomicReference<Server> server = new AtomicReference<>();
101   private final AtomicReference<Microservice> microservice = new AtomicReference<>();
102   private final AtomicReference<Duration> shutdownSettleDelay = new AtomicReference<>(Duration.ZERO);
103
104   /**
105    * Env-driven sentinel for {@code availablePort}; {@link Optional#empty()} when unset (in which case
106    * {@link #onStart(Microservice)} publishes the bound port back as the {@code availablePort} system property).
107    */
108   @Value("${availablePort}")
109   Optional<String> availablePortEnv = oe();
110
111   /**
112    * Env-driven sentinel for {@code juneau.serverPort}; {@link Optional#empty()} when unset (in which case
113    * {@link #onStart(Microservice)} publishes the bound port back as the {@code juneau.serverPort} system property).
114    */
115   @Value("${juneau.serverPort}")
116   Optional<String> serverPortEnv = oe();
117
118   /**
119    * Creates the directory the bundled <c>jetty.xml</c>'s request log writes into, so a fresh working directory starts.
120    *
121    * <p>
122    * A newly created directory is readable only by its owner, where the file system supports POSIX permissions.
123    * A failure is logged rather than thrown; Jetty reports the unusable directory when the request log starts.
124    *
125    * @param dir The log directory (<c>Logging/logDir</c>).
126    * @param logger The logger to report a failure to.
127    */
128   static void createLogDir(String dir, Logger logger) {
129      try {
130         var p = Path.of(dir);
131         var created = ! Files.exists(p);
132         Files.createDirectories(p);
133         // A directory this method created is private to the process owner where the file system supports POSIX permissions.
134         if (created && p.getFileSystem().supportedFileAttributeViews().contains("posix"))
135            Files.setPosixFilePermissions(p, PosixFilePermissions.fromString("rwx------"));
136      } catch (IOException | InvalidPathException e) {
137         logger.warning("Could not create log directory '" + dir + "': " + e);
138      }
139   }
140
141   private static int[] parseIntArray(String csv) {
142      if (ie(csv))
143         return new int[0];
144      var parts = csv.split(",");
145      var out = new int[parts.length];
146      for (var i = 0; i < parts.length; i++)
147         out[i] = Integer.parseInt(parts[i].trim());
148      return out;
149   }
150
151   private static int findOpenPort(int[] ports) {
152      for (var port : ports) {
153         if (port == 0)
154            port = RANDOM.nextInt(32767 - ports[0] + 1) + ports[0];
155         try (var ss = new ServerSocket(port)) {
156            return port;
157         } catch (@SuppressWarnings("unused") IOException e) {
158            // Port is in use, try next port in array
159         }
160      }
161      return 0;
162   }
163
164   private static String normalizePathSpec(String rawPath) {
165      var p = rawPath == null ? "" : rawPath;
166      if (p.isEmpty() || eq(p, "/"))
167         return "/*";
168      if (! p.startsWith("/"))
169         p = "/" + p;
170      if (! p.endsWith("/*"))
171         p = trimTrailingSlashes(p) + "/*";
172      return p;
173   }
174
175   private static String normalizeExactPathSpec(String rawPath) {
176      var p = rawPath == null ? "" : trimTrailingSlashes(rawPath);
177      if (p.isEmpty())
178         return "/";
179      if (! p.startsWith("/"))
180         p = "/" + p;
181      return p;
182   }
183
184   /**
185    * Resolves the top-level Jetty mount path-specs for an auto-discovered {@code @Rest}-annotated servlet.
186    *
187    * <p>
188    * Delegates to {@link RestContext#resolveTopLevelPaths(Class, Object, BeanStore)} so the runtime-override
189    * resolution chain (programmatic &gt; {@code getPaths()} getter &gt; annotation default) is honored at
190    * mount time. The programmatic Builder rung is N/A for Jetty auto-discovery (the {@code RestContext} does
191    * not exist yet at this point in the lifecycle); users can substitute by overriding {@code getPaths()} on
192    * the resource class, or by leaning on SVL inside {@code @Rest(paths=...)} elements (e.g.
193    * {@code paths={"${C:health.paths}"}}) so each element is resolved through {@code Config} /
194    * {@code ${E:...}} / {@code ${S:...}} before being comma-split.
195    *
196    * @return The normalized exact-match path-specs (for multi-mount), or the singular {@code @Rest(path)}-style
197    *    {@code "/...&#47;*"} pathspec when no {@code paths} are resolved.
198    */
199   private static String[] restPathsFor(Servlet servlet, BeanStore store) {
200      var cls = servlet.getClass();
201      var r = cls.getAnnotation(Rest.class);
202      if (r == null)
203         return new String[] {"/*"};
204      var resolved = RestContext.resolveTopLevelPaths(cls, servlet, store);
205      if (resolved.length > 0)
206         return Arrays.stream(resolved).map(JettyServerComponent::normalizeExactPathSpec).toArray(String[]::new);
207      return new String[] {normalizePathSpec(r.path())};
208   }
209
210   /**
211    * Constructor.
212    */
213   @SuppressWarnings({
214      "java:S1186" // Empty constructor; all state is initialized via onStart(Microservice) when wired through the bean store.
215   })
216   public JettyServerComponent() {}
217
218   @Override /* Overridden from MicroserviceListener */
219   @SuppressWarnings({
220      "java:S1141", // Nested try blocks scope checked-exception translation tightly to single call sites
221      "java:S3776", // Cognitive complexity acceptable for server creation logic
222      "java:S6541" // Brain Method acceptable for server startup wiring logic
223   })
224   public void onStart(Microservice ms) {
225      try {
226         microservice.set(ms);
227         var store = ms.getBeanStore();
228         ClassInfo.of(this).inject(this, store);
229         var cf = ms.getConfig();
230         var mf = ms.getManifest();
231         var vr = ms.getVarResolver();
232         var settings = store.getBean(JettySettings.class).orElseGet(() -> JettySettings.create().build());
233
234         // Port resolution: settings > Jetty/port config > Jetty-Port manifest > 8000
235         var ports = settings.getPorts();
236         if (ports == null)
237            ports = cf.get("Jetty/port").as(int[].class)
238               .orElseGet(() -> mf.get("Jetty-Port").map(JettyServerComponent::parseIntArray).orElseGet(() -> ints(8000)));
239         var availablePort = findOpenPort(ports);
240
241         if (availablePortEnv.isEmpty())
242            // Intentional real-JVM-property publish: the bundled jetty.xml binds its connector to
243            // ${S:availablePort:10000}, and the ${S:...} SVL var resolves via raw System.getProperty (bypassing
244            // the Settings override chain).  A Settings-based write would be invisible to jetty.xml, so the
245            // bound port MUST be published as a real system property here.  The @Value-injected availablePortEnv
246            // read side is already Settings-abstracted; only this publish must stay raw.
247            System.setProperty("availablePort", String.valueOf(availablePort));
248
249         // Prefer a @Bean-supplied Server, else build one from jetty.xml.
250         var injectedServer = store.getBean(Server.class).orElse(null);
251         if (nn(injectedServer)) {
252            server.set(injectedServer);
253         } else {
254            var factory = store.getBean(JettyServerFactory.class).orElseGet(BasicJettyServerFactory::new);
255            var jettyXml = settings.getJettyXml();
256            var jettyConfig = cf.get("Jetty/config").orElseGet(() -> mf.get("Jetty-Config").orElse("jetty.xml"));
257            var resolveVars = coalesce(settings.getJettyXmlResolveVars(), cf.get("Jetty/resolveVars").asBoolean().orElse(false));
258            boolean resolveVars2 = isTrue(resolveVars);
259
260            if (jettyXml == null)
261               jettyXml = loadSystemResourceAsString(jettyConfig, ".", "files");
262            if (jettyXml == null)
263               throw rex("jetty.xml file '%s' was not found on the file system or classpath.", jettyConfig);
264
265            if (resolveVars2)
266               jettyXml = vr.resolve(jettyXml);
267
268            ms.getLogger().config(jettyXml);
269
270            createLogDir(cf.get("Logging/logDir").orElse("logs"), ms.getLogger());
271
272            try {
273               server.set(factory.create(jettyXml));
274            } catch (Exception e) {
275               throw toRex(e);
276            }
277         }
278
279         // Publish back to the store for downstream beans / lookups.
280         store.addBean(Server.class, server.get());
281
282         // Graceful-shutdown wiring (zero-downtime k8s rollouts):
283         //  - Apply a bounded stopTimeout so server.stop() drains in-flight requests before the connector closes.
284         //    Precedence: JettySettings > Jetty/stopTimeout config > jetty.xml value (if any) > 30s default.
285         //  - Remember the settle delay so onStop() can let the LB observe the /readyz 503 before draining.
286         //  - Mark readiness ready so a freshly-(re)started service serves traffic.
287         var stopTimeoutOverride = settings.getStopTimeout() != null
288            ? settings.getStopTimeout()
289            : cf.get("Jetty/stopTimeout").asLong().map(Duration::ofMillis).orElse(null);
290         if (stopTimeoutOverride != null)
291            server.get().setStopTimeout(Math.max(0L, stopTimeoutOverride.toMillis()));
292         else if (server.get().getStopTimeout() <= 0L)
293            server.get().setStopTimeout(DEFAULT_STOP_TIMEOUT.toMillis());
294         shutdownSettleDelay.set(coalesce(settings.getShutdownSettleDelay(), cf.get("Jetty/shutdownSettleDelay").asLong().map(Duration::ofMillis).orElse(Duration.ZERO)));
295
296         // Per-service readiness: reuse an app/test-supplied @Bean ReadinessState if present, else construct
297         // one, and publish it into this microservice's bean store.  shared() is intentionally NOT used here:
298         // it is one JVM-wide singleton, so falling back to it would leak this service's readiness into every
299         // other default-configured microservice in the same JVM.  The health-probe servlet side of this
300         // dual-store publish happens below, in the @Rest servlet auto-discovery loop.
301         var readinessState = store.getBean(ReadinessState.class).orElseGet(ReadinessState::new);
302         store.addBean(ReadinessState.class, readinessState);
303         readinessState.markReady();
304
305         // Track each servlet pathSpec with its declaring source so we can fail loudly on collisions.
306         var mountedPaths = new LinkedHashMap<String,String>();
307
308         for (var s : cf.get("Jetty/servlets").asStringArray().orElse(new String[0])) {
309            try {
310               var c = info(Class.forName(s));
311               if (c.isAssignableTo(RestServlet.class)) {
312                  var rs = (RestServlet)c.newInstance();
313                  mountWithCollisionCheck(rs, rs.getPath(), "Jetty/servlets[" + s + "]", mountedPaths);
314               } else {
315                  throw rex("Invalid servlet specified in Jetty/servlets.  Must be a subclass of RestServlet: %s", s);
316               }
317            } catch (ClassNotFoundException e) {
318               throw toRex(e);
319            }
320         }
321
322         cf.get("Jetty/servletMap").asMap().orElse(EMPTY_MAP).forEach((k, v) -> {
323            try {
324               var c = info(Class.forName(v.toString()));
325               if (c.isAssignableTo(Servlet.class)) {
326                  var rs = (Servlet)c.newInstance();
327                  mountWithCollisionCheck(rs, k, "Jetty/servletMap[" + k + "]", mountedPaths);
328               } else {
329                  throw rex("Invalid servlet specified in Jetty/servletMap.  Must be a subclass of Servlet: %s", cn(v));
330               }
331            } catch (ClassNotFoundException e) {
332               throw toRex(e);
333            }
334         });
335
336         cf.get("Jetty/servletAttributes").asMap().orElse(EMPTY_MAP).forEach(this::addServletAttribute);
337
338         // Mount the @Bean ServletFilterRegistration filters, plus the @Bean AuthFilterChain at /* unless a
339         // registration already wraps it, outermost first.  Filter matching does not depend on whether the
340         // servlets or the filters were added first, so mounting after the config-sourced servlets is fine.
341         for (var registration : ServletFilterRegistration.collect(store))
342            addFilter(registration);
343
344         // Auto-discover @Rest servlets contributed via @Configuration/@Bean methods.
345         // Path source precedence: @Rest(path=...) on the resource class, else "/".
346         for (var e : store.getBeansOfType(Servlet.class).entrySet()) {
347            var servlet = e.getValue();
348            var cls = servlet.getClass();
349            if (cls.getAnnotation(Rest.class) == null)
350               continue;
351            if (servlet instanceof HealthServlet hs)
352               // Dual-store publish (READY-394): this probe's own RestContext bean store is not linked to
353               // ms.getBeanStore(), so the lifecycle-owned instance must be handed to it explicitly before
354               // it initializes; HealthServlet.initReadinessState() registers it into its own bean store.
355               hs.publishReadinessState(readinessState);
356            if (servlet instanceof ReadinessStateAware rsa)
357               // Lets servlets holding long-lived streams (e.g. MCP subscriptions/listen) end them when shutdown
358               // begins, so the graceful drain does not wait out the full stopTimeout for them.
359               rsa.acceptReadinessState(readinessState);
360            var pathSpecs = restPathsFor(servlet, store);
361            var source = "@Bean " + cls.getName() + (ine(e.getKey()) ? "[" + e.getKey() + "]" : "");
362            for (var pathSpec : pathSpecs)
363               checkPathCollision(pathSpec, source, mountedPaths);
364            addServlet(servlet, pathSpecs);
365         }
366
367         if (serverPortEnv.isEmpty())
368            // Intentional real-JVM-property publish: juneau.serverPort is a documented cross-component/external
369            // publication of the bound port, consumed via raw System.getProperty (and ${S:...} SVL).  A
370            // Settings-based write would not be visible to those raw readers, so this is kept.  The
371            // @Value-injected serverPortEnv read side is already Settings-abstracted.
372            System.setProperty("juneau.serverPort", String.valueOf(availablePort));
373
374         server.get().start();
375         ms.out(messages, "ServerStarted", getPort());
376      } catch (Exception e) {
377         throw toRex(e);
378      }
379   }
380
381   @Override /* Overridden from MicroserviceListener */
382   public void onStop(Microservice ms) {
383      final Logger logger = ms.getLogger();
384      // Flip readiness out of service BEFORE the connector stops so /readyz returns 503 and the load balancer /
385      // Kubernetes stops routing new traffic while in-flight requests drain.  /livez stays healthy so the pod is
386      // not killed mid-drain.  The settle delay (default 0) gives the LB a window to observe the 503.
387      ReadinessState.resolve(ms.getBeanStore()).markOutOfService();
388      ms.out(messages, "DrainingRequests");
389      sleepQuietly(shutdownSettleDelay.get());
390      var t = new Thread("JettyServerComponentStop") {
391         @Override /* Overridden from Thread */
392         public void run() {
393            try {
394               var s = server.get();
395               if (s == null || s.isStopping() || s.isStopped())
396                  return;
397               ms.out(messages, "StoppingServer");
398               s.stop();
399               ms.out(messages, "ServerStopped");
400            } catch (Exception e) {
401               logger.log(Level.WARNING, localizedMessage(e), e);
402            }
403         }
404      };
405      t.start();
406      try {
407         t.join();
408      } catch (@SuppressWarnings("unused") InterruptedException e) {
409         Thread.currentThread().interrupt();
410      }
411   }
412
413   private static void sleepQuietly(Duration d) {
414      if (d == null || d.isZero() || d.isNegative())
415         return;
416      try {
417         Thread.sleep(d.toMillis());
418      } catch (@SuppressWarnings("unused") InterruptedException e) {
419         Thread.currentThread().interrupt();
420      }
421   }
422
423   @Override /* Overridden from MicroserviceListener */
424   public void onConfigChange(Microservice ms, ConfigEvents events) {
425      // No-op: Intentional empty implementation - this component is purely lifecycle-driven.
426   }
427
428   /**
429    * Adds an arbitrary servlet to this Jetty server.
430    *
431    * @param servlet The servlet instance.
432    * @param pathSpec The context path of the servlet.
433    * @return This object.
434    */
435   public JettyServerComponent addServlet(Servlet servlet, String pathSpec) {
436      if (nn(pathSpec) && ! pathSpec.endsWith("/*"))
437         pathSpec = trimTrailingSlashes(pathSpec) + "/*";
438      return addServlet(servlet, new String[]{pathSpec});
439   }
440
441   /**
442    * Adds an arbitrary servlet to this Jetty server at one or more context paths.
443    *
444    * @param servlet The servlet instance.
445    * @param pathSpecs The context paths of the servlet.
446    * @return This object.
447    */
448   public JettyServerComponent addServlet(Servlet servlet, String...pathSpecs) {
449      var sh = new ServletHolder(servlet);
450      for (var pathSpec : pathSpecs)
451         getServletContextHandler().addServlet(sh, pathSpec);
452      return this;
453   }
454
455   /**
456    * Adds a servlet filter to this Jetty server at the specified URL pattern.
457    *
458    * @param filter The filter instance.
459    * @param urlPattern The URL pattern the filter applies to (e.g. {@code "/*"}, {@code "/api/*"}).
460    * @return This object.
461    */
462   public JettyServerComponent addFilter(jakarta.servlet.Filter filter, String urlPattern) {
463      return addFilter(filter, new String[]{urlPattern});
464   }
465
466   /**
467    * Adds a servlet filter to this Jetty server at one or more URL patterns.
468    *
469    * @param filter The filter instance.
470    * @param urlPatterns The URL patterns the filter applies to.
471    * @return This object.
472    */
473   public JettyServerComponent addFilter(jakarta.servlet.Filter filter, String... urlPatterns) {
474      var fh = new FilterHolder(filter);
475      for (var urlPattern : urlPatterns)
476         getServletContextHandler().addFilter(fh, urlPattern, EnumSet.of(DispatcherType.REQUEST));
477      return this;
478   }
479
480   /**
481    * Adds a servlet filter registration to this Jetty server.
482    *
483    * <p>
484    * Maps the filter on every URL pattern and dispatcher type of the registration with one mapping, so the filter runs at
485    * most once per dispatch even when the patterns overlap.  Mapping order is call order, so call this outermost first.
486    *
487    * <p>
488    * Applications contribute a {@link ServletFilterRegistration} <c>@Bean</c> instead; {@link #onStart(Microservice)}
489    * applies the beans through this method in {@link ServletFilterRegistration#getOrder() order}.  Calling it directly
490    * is only possible once the server object exists (during startup) and before the server runs.
491    *
492    * @param registration The registration.  Cannot be <jk>null</jk>.
493    * @return This object.
494    * @throws IllegalArgumentException If the registration is <jk>null</jk>.
495    * @throws IllegalStateException If the server has already started.
496    */
497   public JettyServerComponent addFilter(ServletFilterRegistration registration) {
498      if (registration == null)
499         throw iaex("registration must not be null.");
500      var jetty = getServer();
501      if (jetty.isRunning() || jetty.isStopping())
502         throw isex("Filters must be added before the server starts.");
503      var filter = registration.getFilter();
504      var name = registration.getName().orElseGet(() -> cn(filter) + "#" + UUID.randomUUID());
505      var holder = new FilterHolder(filter);
506      holder.setName(name);
507      holder.setAsyncSupported(registration.isAsyncSupported());
508      var mapping = new FilterMapping();
509      mapping.setFilterName(name);
510      mapping.setPathSpecs(registration.getUrlPatterns().toArray(new String[0]));
511      mapping.setDispatcherTypes(EnumSet.copyOf(registration.getDispatcherTypes()));
512      getServletContextHandler().getServletHandler().addFilter(holder, mapping);
513      return this;
514   }
515
516   /**
517    * Adds a servlet filter to this Jetty server on the given dispatcher types and URL patterns.
518    *
519    * <p>
520    * Shorthand for {@link #addFilter(ServletFilterRegistration)} with the default order and async support, and the same
521    * validation.  The overloads without dispatcher types keep their {@code REQUEST}-only behavior.
522    *
523    * @param filter The filter instance.  Cannot be <jk>null</jk>.
524    * @param dispatcherTypes The dispatcher types.  Cannot be empty.
525    * @param urlPatterns The URL patterns.  At least one is required; see {@link org.apache.juneau.microservice.ServletFilterRegistration.Builder#urlPatterns(String...) ServletFilterRegistration.Builder#urlPatterns(String...)}.
526    * @return This object.
527    * @throws IllegalArgumentException If an argument is invalid.
528    * @throws IllegalStateException If the server has already started.
529    */
530   public JettyServerComponent addFilter(jakarta.servlet.Filter filter, Set<DispatcherType> dispatcherTypes, String... urlPatterns) {
531      if (dispatcherTypes == null)
532         throw iaex("dispatcherTypes must not be null.");
533      return addFilter(ServletFilterRegistration.create(filter).urlPatterns(urlPatterns).dispatcherTypes(dispatcherTypes.toArray(DispatcherType[]::new)).build());
534   }
535
536   /**
537    * Adds an attribute to the Jetty server.
538    *
539    * @param name The server attribute name.
540    * @param value The attribute value.
541    * @return This object.
542    */
543   public JettyServerComponent addServletAttribute(String name, Object value) {
544      getServer().setAttribute(name, value);
545      return this;
546   }
547
548   /**
549    * Returns the context path that this server is using.
550    *
551    * @return The context path.
552    */
553   public String getContextPath() {
554      return getServletContextHandler().getContextPath();
555   }
556
557   /**
558    * Returns the hostname of this microservice.
559    *
560    * @return The hostname.
561    */
562   public String getHostName() {
563      String hostname = "localhost";
564      try {
565         hostname = InetAddress.getLocalHost().getHostName();
566      } catch (@SuppressWarnings("unused") UnknownHostException e) {
567         // Cannot determine hostname, use default "localhost"
568      }
569      return hostname;
570   }
571
572   /**
573    * Returns the port that this server is listening on.
574    *
575    * @return The port.
576    */
577   public int getPort() {
578      for (var c : getServer().getConnectors())
579         if (c instanceof ServerConnector c2)
580            return c2.getPort();
581      throw new IllegalStateException("Could not locate ServerConnector in Jetty server.");
582   }
583
584   /**
585    * Returns whether this server is using <js>"http"</js> or <js>"https"</js>.
586    *
587    * @return The protocol.
588    */
589   public String getProtocol() {
590      for (var c : getServer().getConnectors())
591         if (c instanceof ServerConnector c2)
592            for (var cf : c2.getConnectionFactories())
593               if (cf instanceof SslConnectionFactory)
594                  return "https";
595      return "http";
596   }
597
598   /**
599    * Returns the underlying Jetty server.
600    *
601    * @return The underlying Jetty server.
602    * @throws NullPointerException If the server has not been created yet.
603    */
604   public Server getServer() {
605      return Objects.requireNonNull(server.get(), "Server not found.  Microservice has not been started yet.");
606   }
607
608   /**
609    * Finds and returns the servlet context handler defined in the Jetty container.
610    *
611    * @return The servlet context handler.
612    * @throws IllegalStateException If the context handler is not defined.
613    */
614   public ServletContextHandler getServletContextHandler() {
615      var obj = getServer().getAttribute(KEY_SERVLET_CONTEXT_HANDLER);
616      if (obj instanceof ServletContextHandler obj2)
617         return obj2;
618      throw isex("Servlet context handler not found in jetty server or at attribute '%s'", KEY_SERVLET_CONTEXT_HANDLER);
619   }
620
621   /**
622    * Returns the URI where this server is listening.
623    *
624    * @return The URI.
625    */
626   public URI getURI() {
627      var cp = getContextPath();
628      try {
629         return new URI(getProtocol(), null, getHostName(), getPort(), eq(cp, "/") ? null : cp, null, null);
630      } catch (URISyntaxException e) {
631         throw toRex(e);
632      }
633   }
634
635   private void mountWithCollisionCheck(Servlet servlet, String rawPath, String source, Map<String,String> mountedPaths) {
636      var pathSpec = normalizePathSpec(rawPath);
637      checkPathCollision(pathSpec, source, mountedPaths);
638      addServlet(servlet, pathSpec);
639   }
640
641   private void checkPathCollision(String pathSpec, String source, Map<String,String> mountedPaths) {
642      var prior = mountedPaths.get(pathSpec);
643      if (nn(prior))
644         throw rex("Servlet mount path collision: '%s' is already mounted by %s; refused by %s.", pathSpec, prior, source);
645      mountedPaths.put(pathSpec, source);
646   }
647}