@Test
  public void testExtensionMatchServletWithGlobalFilter() throws IOException, ServletException {

    DeploymentInfo builder = new DeploymentInfo();

    final PathHandler root = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();

    builder.addServlet(new ServletInfo("*.jsp", PathMappingServlet.class).addMapping("*.jsp"));

    builder.addFilter(new FilterInfo("/*", PathFilter.class));
    builder.addFilterUrlMapping("/*", "/*", DispatcherType.REQUEST);

    builder
        .setClassIntrospecter(TestClassIntrospector.INSTANCE)
        .setClassLoader(FilterPathMappingTestCase.class.getClassLoader())
        .setContextPath("/servletContext")
        .setDeploymentName("servletContext.war");

    final DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    root.addPrefixPath(builder.getContextPath(), manager.start());

    DefaultServer.setRootHandler(root);

    TestHttpClient client = new TestHttpClient();
    try {
      runTest(client, "aa.jsp", "*.jsp - /aa.jsp - null", "/*");

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Пример #2
0
 @Override
 public FilterRegistration.Dynamic addFilter(
     final String filterName, final Class<? extends Filter> filterClass) {
   ensureNotProgramaticListener();
   ensureNotInitialized();
   if (deploymentInfo.getFilters().containsKey(filterName)) {
     return null;
   }
   FilterInfo filter = new FilterInfo(filterName, filterClass);
   deploymentInfo.addFilter(filter);
   deployment.getFilters().addFilter(filter);
   return new FilterRegistrationImpl(filter, deployment);
 }
Пример #3
0
  @Override
  public FilterRegistration.Dynamic addFilter(final String filterName, final Filter filter) {
    ensureNotProgramaticListener();
    ensureNotInitialized();

    if (deploymentInfo.getFilters().containsKey(filterName)) {
      return null;
    }
    FilterInfo f =
        new FilterInfo(filterName, filter.getClass(), new ImmediateInstanceFactory<Filter>(filter));
    deploymentInfo.addFilter(f);
    deployment.getFilters().addFilter(f);
    return new FilterRegistrationImpl(f, deployment);
  }
Пример #4
0
 @Override
 public FilterRegistration.Dynamic addFilter(final String filterName, final String className) {
   ensureNotProgramaticListener();
   ensureNotInitialized();
   if (deploymentInfo.getFilters().containsKey(filterName)) {
     return null;
   }
   try {
     FilterInfo filter =
         new FilterInfo(
             filterName,
             (Class<? extends Filter>) deploymentInfo.getClassLoader().loadClass(className));
     deploymentInfo.addFilter(filter);
     deployment.getFilters().addFilter(filter);
     return new FilterRegistrationImpl(filter, deployment);
   } catch (ClassNotFoundException e) {
     throw UndertowServletMessages.MESSAGES.cannotLoadClass(className, e);
   }
 }
Пример #5
0
  @Override
  public DeploymentInfo clone() {
    final DeploymentInfo info =
        new DeploymentInfo()
            .setClassLoader(classLoader)
            .setContextPath(contextPath)
            .setResourceLoader(resourceLoader)
            .setMajorVersion(majorVersion)
            .setMinorVersion(minorVersion)
            .setDeploymentName(deploymentName);

    for (Map.Entry<String, ServletInfo> e : servlets.entrySet()) {
      info.addServlet(e.getValue().clone());
    }

    for (Map.Entry<String, FilterInfo> e : filters.entrySet()) {
      info.addFilter(e.getValue().clone());
    }
    info.displayName = displayName;
    info.filterUrlMappings.addAll(filterUrlMappings);
    info.filterServletNameMappings.addAll(filterServletNameMappings);
    info.listeners.addAll(listeners);
    info.servletContainerInitializers.addAll(servletContainerInitializers);
    info.threadSetupActions.addAll(threadSetupActions);
    info.initParameters.putAll(initParameters);
    info.servletContextAttributes.putAll(servletContextAttributes);
    info.welcomePages.addAll(welcomePages);
    info.errorPages.addAll(errorPages);
    info.mimeMappings.addAll(mimeMappings);
    info.executorFactory = executorFactory;
    info.asyncExecutorFactory = asyncExecutorFactory;
    info.tempDir = tempDir;
    info.jspConfigDescriptor = jspConfigDescriptor;
    info.defaultServletConfig = defaultServletConfig;
    info.localeCharsetMapping.putAll(localeCharsetMapping);
    info.sessionManager = sessionManager;
    info.loginConfig = loginConfig;
    info.identityManager = identityManager;
    info.securityConstraints.addAll(securityConstraints);
    info.principleVsRoleMapping.putAll(principleVsRoleMapping);
    return info;
  }
Пример #6
0
 public DeploymentInfo addFilters(final Collection<FilterInfo> filters) {
   for (final FilterInfo filter : filters) {
     addFilter(filter);
   }
   return this;
 }
Пример #7
0
 public DeploymentInfo addFilters(final FilterInfo... filters) {
   for (final FilterInfo filter : filters) {
     addFilter(filter);
   }
   return this;
 }
Пример #8
0
  @Override
  public DeploymentInfo clone() {
    final DeploymentInfo info =
        new DeploymentInfo()
            .setClassLoader(classLoader)
            .setContextPath(contextPath)
            .setResourceManager(resourceManager)
            .setMajorVersion(majorVersion)
            .setMinorVersion(minorVersion)
            .setDeploymentName(deploymentName)
            .setClassIntrospecter(classIntrospecter);

    for (Map.Entry<String, ServletInfo> e : servlets.entrySet()) {
      info.addServlet(e.getValue().clone());
    }

    for (Map.Entry<String, FilterInfo> e : filters.entrySet()) {
      info.addFilter(e.getValue().clone());
    }
    info.displayName = displayName;
    info.filterUrlMappings.addAll(filterUrlMappings);
    info.filterServletNameMappings.addAll(filterServletNameMappings);
    info.listeners.addAll(listeners);
    info.servletContainerInitializers.addAll(servletContainerInitializers);
    info.threadSetupActions.addAll(threadSetupActions);
    info.initParameters.putAll(initParameters);
    info.servletContextAttributes.putAll(servletContextAttributes);
    info.welcomePages.addAll(welcomePages);
    info.errorPages.addAll(errorPages);
    info.mimeMappings.addAll(mimeMappings);
    info.executor = executor;
    info.asyncExecutor = asyncExecutor;
    info.tempDir = tempDir;
    info.jspConfigDescriptor = jspConfigDescriptor;
    info.defaultServletConfig = defaultServletConfig;
    info.localeCharsetMapping.putAll(localeCharsetMapping);
    info.sessionManagerFactory = sessionManagerFactory;
    if (loginConfig != null) {
      info.loginConfig = loginConfig.clone();
    }
    info.identityManager = identityManager;
    info.confidentialPortManager = confidentialPortManager;
    info.defaultEncoding = defaultEncoding;
    info.urlEncoding = urlEncoding;
    info.securityConstraints.addAll(securityConstraints);
    info.outerHandlerChainWrappers.addAll(outerHandlerChainWrappers);
    info.innerHandlerChainWrappers.addAll(innerHandlerChainWrappers);
    info.initialHandlerChainWrappers.addAll(initialHandlerChainWrappers);
    info.securityRoles.addAll(securityRoles);
    info.notificationReceivers.addAll(notificationReceivers);
    info.allowNonStandardWrappers = allowNonStandardWrappers;
    info.defaultSessionTimeout = defaultSessionTimeout;
    info.servletContextAttributeBackingMap = servletContextAttributeBackingMap;
    info.servletSessionConfig = servletSessionConfig;
    info.hostName = hostName;
    info.denyUncoveredHttpMethods = denyUncoveredHttpMethods;
    info.servletStackTraces = servletStackTraces;
    info.invalidateSessionOnLogout = invalidateSessionOnLogout;
    info.defaultCookieVersion = defaultCookieVersion;
    info.sessionPersistenceManager = sessionPersistenceManager;
    info.principalVersusRolesMap.putAll(principalVersusRolesMap);
    info.ignoreFlush = ignoreFlush;
    info.authorizationManager = authorizationManager;
    info.authenticationMechanisms.putAll(authenticationMechanisms);
    info.servletExtensions.addAll(servletExtensions);
    info.jaspiAuthenticationMechanism = jaspiAuthenticationMechanism;
    info.securityContextFactory = securityContextFactory;
    info.serverName = serverName;
    info.metricsCollector = metricsCollector;
    info.sessionConfigWrapper = sessionConfigWrapper;
    info.eagerFilterInit = eagerFilterInit;
    info.disableCachingForSecuredPages = disableCachingForSecuredPages;
    this.lifecycleInterceptors.addAll(lifecycleInterceptors);
    return info;
  }
  @Test
  public void testBasicFilterMappings() throws IOException, ServletException {

    DeploymentInfo builder = new DeploymentInfo();

    final PathHandler root = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();

    builder.addServlet(new ServletInfo("/a/*", PathMappingServlet.class).addMapping("/a/*"));

    builder.addServlet(new ServletInfo("/aa", PathMappingServlet.class).addMapping("/aa"));

    builder.addServlet(new ServletInfo("/", PathMappingServlet.class).addMapping("/"));

    builder.addServlet(new ServletInfo("contextRoot", PathMappingServlet.class).addMapping(""));

    builder.addServlet(
        new ServletInfo("/myservlet/*", PathMappingServlet.class).addMapping("/myservlet/*"));

    builder.addServlet(new ServletInfo("*.jsp", PathMappingServlet.class).addMapping("*.jsp"));

    builder.addServlet(
        new ServletInfo("/hello/*", PathMappingServlet.class).addMapping("/hello/*"));

    builder.addServlet(new ServletInfo("/test/*", PathMappingServlet.class).addMapping("/test/*"));

    builder.addFilter(new FilterInfo("/*", PathFilter.class));
    builder.addFilterUrlMapping("/*", "/*", DispatcherType.REQUEST);

    // non standard, but we still support it
    builder.addFilter(new FilterInfo("*", PathFilter.class));
    builder.addFilterUrlMapping("*", "*", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("/a/*", PathFilter.class));
    builder.addFilterUrlMapping("/a/*", "/a/*", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("/aa", PathFilter.class));
    builder.addFilterUrlMapping("/aa", "/aa", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("*.bop", PathFilter.class));
    builder.addFilterUrlMapping("*.bop", "*.bop", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("/myservlet/myfilter/*", PathFilter.class));
    builder.addFilterUrlMapping(
        "/myservlet/myfilter/*", "/myservlet/myfilter/*", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("/myfilter/*", PathFilter.class));
    builder.addFilterUrlMapping("/myfilter/*", "/myfilter/*", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("contextRoot", PathFilter.class));
    builder.addFilterServletNameMapping("contextRoot", "contextRoot", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("defaultName", PathFilter.class));
    builder.addFilterServletNameMapping("defaultName", "/", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("/helloworld/index.html", PathFilter.class));
    builder.addFilterUrlMapping(
        "/helloworld/index.html", "/helloworld/index.html", DispatcherType.REQUEST);

    builder.addFilter(new FilterInfo("/test", PathFilter.class));
    builder.addFilterUrlMapping("/test", "/test", DispatcherType.REQUEST);

    builder
        .setClassIntrospecter(TestClassIntrospector.INSTANCE)
        .setClassLoader(FilterPathMappingTestCase.class.getClassLoader())
        .setContextPath("/servletContext")
        .setDeploymentName("servletContext.war");

    final DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    root.addPrefixPath(builder.getContextPath(), manager.start());

    DefaultServer.setRootHandler(root);

    TestHttpClient client = new TestHttpClient();
    try {
      runTest(client, "test", "/test/* - /test - null", "/*", "*", "/test");
      runTest(client, "aa", "/aa - /aa - null", "/*", "*", "/aa");
      runTest(client, "a/c", "/a/* - /a - /c", "/*", "*", "/a/*");
      runTest(client, "a", "/a/* - /a - null", "/*", "*", "/a/*");
      runTest(client, "aa/b", "/ - /aa/b - null", "/*", "*", "defaultName");
      runTest(client, "a/b/c/d", "/a/* - /a - /b/c/d", "/*", "*", "/a/*");
      runTest(client, "defaultStuff", "/ - /defaultStuff - null", "/*", "*", "defaultName");
      runTest(client, "", "contextRoot - / - null", "/*", "*", "contextRoot");
      runTest(client, "yyyy.bop", "/ - /yyyy.bop - null", "/*", "*", "*.bop", "defaultName");
      runTest(client, "a/yyyy.bop", "/a/* - /a - /yyyy.bop", "/*", "*", "*.bop", "/a/*");
      runTest(
          client,
          "myservlet/myfilter/file.dat",
          "/myservlet/* - /myservlet - /myfilter/file.dat",
          "/*",
          "*",
          "/myservlet/myfilter/*");
      runTest(
          client,
          "myservlet/myfilter/file.jsp",
          "/myservlet/* - /myservlet - /myfilter/file.jsp",
          "/*",
          "*",
          "/myservlet/myfilter/*");
      runTest(
          client,
          "otherservlet/myfilter/file.jsp",
          "*.jsp - /otherservlet/myfilter/file.jsp - null",
          "/*",
          "*");
      runTest(
          client,
          "myfilter/file.jsp",
          "*.jsp - /myfilter/file.jsp - null",
          "/*",
          "*",
          "/myfilter/*");
      runTest(
          client,
          "helloworld/index.html",
          "/ - /helloworld/index.html - null",
          "/*",
          "*",
          "/helloworld/index.html",
          "defaultName");

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
  private DeploymentInfo createServletConfig(
      final JBossWebMetaData mergedMetaData,
      final DeploymentUnit deploymentUnit,
      final Module module,
      final DeploymentClassIndex classReflectionIndex,
      final WebInjectionContainer injectionContainer,
      final ComponentRegistry componentRegistry,
      final ScisMetaData scisMetaData,
      final VirtualFile deploymentRoot)
      throws DeploymentUnitProcessingException {
    try {
      mergedMetaData.resolveAnnotations();
      final DeploymentInfo d = new DeploymentInfo();
      d.setContextPath(mergedMetaData.getContextRoot());
      if (mergedMetaData.getDescriptionGroup() != null) {
        d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName());
      }
      d.setDeploymentName(deploymentUnit.getName());
      d.setResourceLoader(new DeploymentResourceLoader(deploymentRoot));
      d.setClassLoader(module.getClassLoader());
      final String servletVersion = mergedMetaData.getServletVersion();
      if (servletVersion != null) {
        d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + ""));
        d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + ""));
      } else {
        d.setMajorVersion(3);
        d.setMinorVersion(1);
      }

      // for 2.2 apps we do not require a leading / in path mappings
      boolean is22OrOlder;
      if (d.getMajorVersion() == 1) {
        is22OrOlder = true;
      } else if (d.getMajorVersion() == 2) {
        is22OrOlder = d.getMinorVersion() < 3;
      } else {
        is22OrOlder = false;
      }

      HashMap<String, TagLibraryInfo> tldInfo =
          createTldsInfo(deploymentUnit, classReflectionIndex, componentRegistry, d);
      HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData);

      JspServletBuilder.setupDeployment(
          d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(injectionContainer));
      d.setJspConfigDescriptor(
          new JspConfigDescriptorImpl(tldInfo.values(), propertyGroups.values()));
      d.setDefaultServletConfig(new DefaultServletConfig(true, Collections.<String>emptySet()));

      // default JSP servlet
      final ServletInfo jspServlet =
          new ServletInfo("Default JSP Servlet", JspServlet.class)
              .addMapping("*.jsp")
              .addMapping("*.jspx")
              .addInitParam("development", "false"); // todo: make configurable
      d.addServlet(jspServlet);

      final Set<String> jspPropertyGroupMappings = propertyGroups.keySet();
      for (final String mapping : jspPropertyGroupMappings) {
        jspServlet.addMapping(mapping);
      }

      d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry));

      final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>();

      if (mergedMetaData.getServletMappings() != null) {
        for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) {
          List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName());
          if (list == null) {
            servletMappings.put(mapping.getServletName(), list = new ArrayList<>());
          }
          list.add(mapping);
        }
      }
      final Set<String> seenMappings = new HashSet<>(jspPropertyGroupMappings);
      if (mergedMetaData.getServlets() != null) {
        for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) {
          final ServletInfo s;

          if (servlet.getJspFile() != null) {
            // TODO: real JSP support
            s = new ServletInfo(servlet.getName(), JspServlet.class);
            s.addHandlerChainWrapper(new JspFileWrapper(servlet.getJspFile()));
          } else {
            Class<? extends Servlet> servletClass =
                (Class<? extends Servlet>)
                    classReflectionIndex.classIndex(servlet.getServletClass()).getModuleClass();
            ComponentRegistry.ComponentManagedReferenceFactory creator =
                componentRegistry.getComponentsByClass().get(servletClass);
            if (creator != null) {
              InstanceFactory<Servlet> factory = createInstanceFactory(creator);
              s = new ServletInfo(servlet.getName(), servletClass, factory);
            } else {
              s = new ServletInfo(servlet.getName(), servletClass);
            }
          }
          s.setAsyncSupported(servlet.isAsyncSupported())
              .setJspFile(servlet.getJspFile())
              .setEnabled(servlet.isEnabled());
          if (servlet.getRunAs() != null) {
            s.setRunAs(servlet.getRunAs().getRoleName());
          }
          if (servlet
              .getLoadOnStartupSet()) { // todo why not cleanup api and just use int everywhere
            s.setLoadOnStartup(servlet.getLoadOnStartupInt());
          }

          List<ServletMappingMetaData> mappings = servletMappings.get(servlet.getName());
          if (mappings != null) {
            for (ServletMappingMetaData mapping : mappings) {
              for (String pattern : mapping.getUrlPatterns()) {
                if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) {
                  pattern = "/" + pattern;
                }
                if (!seenMappings.contains(pattern)) {
                  s.addMapping(pattern);
                  seenMappings.add(pattern);
                }
              }
            }
          }
          if (servlet.getInitParam() != null) {
            for (ParamValueMetaData initParam : servlet.getInitParam()) {
              if (!s.getInitParams().containsKey(initParam.getParamName())) {
                s.addInitParam(initParam.getParamName(), initParam.getParamValue());
              }
            }
          }
          if (servlet.getServletSecurity() != null) {
            ServletSecurityInfo securityInfo = new ServletSecurityInfo();
            s.setServletSecurityInfo(securityInfo);
            securityInfo
                .setEmptyRoleSemantic(
                    servlet.getServletSecurity().getEmptyRoleSemantic()
                            == EmptyRoleSemanticType.PERMIT
                        ? PERMIT
                        : DENY)
                .setTransportGuaranteeType(
                    transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee()))
                .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed());
            if (servlet.getServletSecurity().getHttpMethodConstraints() != null) {
              for (HttpMethodConstraintMetaData method :
                  servlet.getServletSecurity().getHttpMethodConstraints()) {
                securityInfo.addHttpMethodSecurityInfo(
                    new HttpMethodSecurityInfo()
                        .setEmptyRoleSemantic(
                            method.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT
                                ? PERMIT
                                : DENY)
                        .setTransportGuaranteeType(
                            transportGuaranteeType(method.getTransportGuarantee()))
                        .addRolesAllowed(method.getRolesAllowed())
                        .setMethod(method.getMethod()));
              }
            }
          }
          if (servlet.getSecurityRoleRefs() != null) {
            for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) {
              s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink());
            }
          }

          d.addServlet(s);
        }
      }

      if (mergedMetaData.getFilters() != null) {
        for (final FilterMetaData filter : mergedMetaData.getFilters()) {
          Class<? extends Filter> filterClass =
              (Class<? extends Filter>)
                  classReflectionIndex.classIndex(filter.getFilterClass()).getModuleClass();
          ComponentRegistry.ComponentManagedReferenceFactory creator =
              componentRegistry.getComponentsByClass().get(filterClass);
          FilterInfo f;
          if (creator != null) {
            InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator);
            f = new FilterInfo(filter.getName(), filterClass, instanceFactory);
          } else {
            f = new FilterInfo(filter.getName(), filterClass);
          }
          f.setAsyncSupported(filter.isAsyncSupported());
          d.addFilter(f);

          if (filter.getInitParam() != null) {
            for (ParamValueMetaData initParam : filter.getInitParam()) {
              f.addInitParam(initParam.getParamName(), initParam.getParamValue());
            }
          }
        }
      }
      if (mergedMetaData.getFilterMappings() != null) {
        for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) {
          if (mapping.getUrlPatterns() != null) {
            for (String url : mapping.getUrlPatterns()) {
              if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) {
                url = "/" + url;
              }
              if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                for (DispatcherType dispatcher : mapping.getDispatchers()) {

                  d.addFilterUrlMapping(
                      mapping.getFilterName(),
                      url,
                      javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                }
              } else {
                d.addFilterUrlMapping(
                    mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST);
              }
            }
          }
          if (mapping.getServletNames() != null) {
            for (String servletName : mapping.getServletNames()) {
              if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                for (DispatcherType dispatcher : mapping.getDispatchers()) {
                  d.addFilterServletNameMapping(
                      mapping.getFilterName(),
                      servletName,
                      javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                }
              } else {
                d.addFilterServletNameMapping(
                    mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST);
              }
            }
          }
        }
      }

      if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) {
        for (final Map.Entry<ServletContainerInitializer, Set<Class<?>>> sci :
            scisMetaData.getHandlesTypes().entrySet()) {
          final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory =
              new ImmediateInstanceFactory<>(sci.getKey());
          d.addServletContainerInitalizer(
              new ServletContainerInitializerInfo(
                  sci.getKey().getClass(), instanceFactory, sci.getValue()));
        }
      }

      if (mergedMetaData.getListeners() != null) {
        for (ListenerMetaData listener : mergedMetaData.getListeners()) {
          addListener(classReflectionIndex, componentRegistry, d, listener);
        }
      }
      if (mergedMetaData.getContextParams() != null) {
        for (ParamValueMetaData param : mergedMetaData.getContextParams()) {
          d.addInitParameter(param.getParamName(), param.getParamValue());
        }
      }

      if (mergedMetaData.getWelcomeFileList() != null
          && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) {
        d.addWelcomePages(mergedMetaData.getWelcomeFileList().getWelcomeFiles());
      } else {
        d.addWelcomePages("index.html", "index.htm", "index.jsp");
      }

      if (mergedMetaData.getErrorPages() != null) {
        for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) {
          final ErrorPage errorPage;
          if (page.getExceptionType() == null || page.getExceptionType().isEmpty()) {
            errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode()));
          } else {
            errorPage =
                new ErrorPage(
                    page.getLocation(),
                    (Class<? extends Throwable>)
                        classReflectionIndex.classIndex(page.getExceptionType()).getModuleClass());
          }
          d.addErrorPages(errorPage);
        }
      }

      if (mergedMetaData.getMimeMappings() != null) {
        for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) {
          d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType()));
        }
      }

      if (mergedMetaData.getSecurityConstraints() != null) {
        for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) {
          SecurityConstraint securityConstraint =
              new SecurityConstraint()
                  .setTransportGuaranteeType(
                      transportGuaranteeType(constraint.getTransportGuarantee()))
                  .addRolesAllowed(constraint.getRoleNames());

          if (constraint.getAuthConstraint() == null) {
            // no auth constraint means we permit the empty roles
            securityConstraint.setEmptyRoleSemantic(PERMIT);
          }

          if (constraint.getResourceCollections() != null) {
            for (final WebResourceCollectionMetaData resourceCollection :
                constraint.getResourceCollections()) {
              securityConstraint.addWebResourceCollection(
                  new WebResourceCollection()
                      .addHttpMethods(resourceCollection.getHttpMethods())
                      .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions())
                      .addUrlPatterns(resourceCollection.getUrlPatterns()));
            }
          }
          d.addSecurityConstraint(securityConstraint);
        }
      }
      final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig();
      if (loginConfig != null) {
        String authMethod = authMethod(loginConfig.getAuthMethod());
        if (loginConfig.getFormLoginConfig() != null) {
          d.setLoginConfig(
              new LoginConfig(
                  authMethod,
                  loginConfig.getRealmName(),
                  loginConfig.getFormLoginConfig().getLoginPage(),
                  loginConfig.getFormLoginConfig().getErrorPage()));
        } else {
          d.setLoginConfig(new LoginConfig(authMethod, loginConfig.getRealmName()));
        }
      }

      d.addSecurityRoles(mergedMetaData.getSecurityRoleNames());

      if (mergedMetaData.getSecurityDomain() != null) {

        String contextId = deploymentUnit.getName();
        if (deploymentUnit.getParent() != null) {
          contextId = deploymentUnit.getParent().getName() + "!" + contextId;
        }
        d.addOuterHandlerChainWrapper(
            SecurityContextCreationHandler.wrapper(mergedMetaData.getSecurityDomain()));
        d.addDispatchedHandlerChainWrapper(
            SecurityContextAssociationHandler.wrapper(
                mergedMetaData.getPrincipalVersusRolesMap(), contextId));
      }

      // Setup an deployer configured ServletContext attributes
      final List<ServletContextAttribute> attributes =
          deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY);
      for (ServletContextAttribute attribute : attributes) {
        d.addServletContextAttribute(attribute.getName(), attribute.getValue());
      }

      if (mergedMetaData.getLocalEncodings() != null
          && mergedMetaData.getLocalEncodings().getMappings() != null) {
        for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) {
          d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding());
        }
      }

      return d;
    } catch (ClassNotFoundException e) {
      throw new DeploymentUnitProcessingException(e);
    }
  }