private static ServiceName installSessionManagerFactory(
     ServiceTarget target,
     ServiceName deploymentServiceName,
     String deploymentName,
     Module module,
     JBossWebMetaData metaData) {
   ServiceName name = deploymentServiceName.append("session");
   if (metaData.getDistributable() != null) {
     DistributableSessionManagerFactoryBuilder sessionManagerFactoryBuilder =
         new DistributableSessionManagerFactoryBuilderValue().getValue();
     if (sessionManagerFactoryBuilder != null) {
       sessionManagerFactoryBuilder
           .build(
               target,
               name,
               new SimpleDistributableSessionManagerConfiguration(
                   metaData, deploymentName, module))
           .setInitialMode(Mode.ON_DEMAND)
           .install();
       return name;
     }
     // Fallback to local session manager if server does not support clustering
     UndertowLogger.ROOT_LOGGER.clusteringNotSupported();
   }
   Integer maxActiveSessions = metaData.getMaxActiveSessions();
   InMemorySessionManagerFactory factory =
       (maxActiveSessions != null)
           ? new InMemorySessionManagerFactory(maxActiveSessions.intValue())
           : new InMemorySessionManagerFactory();
   target
       .addService(name, new ValueService<>(new ImmediateValue<>(factory)))
       .setInitialMode(Mode.ON_DEMAND)
       .install();
   return name;
 }
  /** {@inheritDoc} */
  public void init(String name, JBossWebMetaData webMetaData)
      throws ClusteringNotSupportedException {
    if (webMetaData.getMaxActiveSessions() != null) {
      maxActiveAllowed_ = webMetaData.getMaxActiveSessions().intValue();
    }

    PassivationConfig pConfig = webMetaData.getPassivationConfig();
    if (pConfig != null) {
      if (pConfig.getUseSessionPassivation() != null) {
        setUseSessionPassivation(pConfig.getUseSessionPassivation().booleanValue());
        if (getUseSessionPassivation()) {
          Integer min = pConfig.getPassivationMinIdleTime();
          if (min != null) setPassivationMinIdleTime(min.intValue());
          Integer max = pConfig.getPassivationMaxIdleTime();
          if (max != null) setPassivationMaxIdleTime(max.intValue());
        }
      }
    }

    log_.debug(
        "init(): maxActiveSessions allowed is "
            + maxActiveAllowed_
            + " and passivationMode is "
            + passivationMode_);
  }
  private static StandardContext startWebApp(Host host, WSEndpointDeploymentUnit unit)
      throws Exception {
    StandardContext context = new StandardContext();
    try {
      JBossWebMetaData jbwebMD = unit.getAttachment(WSAttachmentKeys.JBOSSWEB_METADATA_KEY);
      context.setPath(jbwebMD.getContextRoot());
      context.addLifecycleListener(new ContextConfig());
      ServerConfigService config =
          (ServerConfigService)
              unit.getServiceRegistry().getService(WSServices.CONFIG_SERVICE).getService();
      File docBase = new File(config.getValue().getServerTempDir(), jbwebMD.getContextRoot());
      if (!docBase.exists()) {
        docBase.mkdirs();
      }
      context.setDocBase(docBase.getPath());

      final Loader loader = new WebCtxLoader(unit.getAttachment(WSAttachmentKeys.CLASSLOADER_KEY));
      loader.setContainer(host);
      context.setLoader(loader);
      context.setInstanceManager(new LocalInstanceManager());

      addServlets(jbwebMD, context);

      host.addChild(context);
      context.create();
    } catch (Exception e) {
      throw MESSAGES.createContextPhaseFailed(e);
    }
    try {
      context.start();
    } catch (LifecycleException e) {
      throw MESSAGES.startContextPhaseFailed(e);
    }
    return context;
  }
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    if (!KeycloakAdapterConfigService.getInstance().isSecureDeployment(deploymentUnit)) {
      WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
      if (warMetaData == null) {
        return;
      }
      JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
      if (webMetaData == null) {
        return;
      }
      LoginConfigMetaData loginConfig = webMetaData.getLoginConfig();
      if (loginConfig == null) return;
      if (loginConfig.getAuthMethod() == null) return;
      if (!loginConfig.getAuthMethod().equals("KEYCLOAK")) return;
    }

    final ModuleSpecification moduleSpecification =
        deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    final ModuleLoader moduleLoader = Module.getBootModuleLoader();
    addCommonModules(moduleSpecification, moduleLoader);
    addPlatformSpecificModules(moduleSpecification, moduleLoader);
  }
  private static void addServlets(JBossWebMetaData jbwebMD, StandardContext context) {
    for (JBossServletMetaData smd : jbwebMD.getServlets()) {
      final String sc = smd.getServletClass();
      if (sc.equals(WSFServlet.class.getName())) {
        final String servletName = smd.getServletName();
        List<ParamValueMetaData> params = smd.getInitParam();
        List<String> urlPatterns = null;
        for (ServletMappingMetaData smmd : jbwebMD.getServletMappings()) {
          if (smmd.getServletName().equals(servletName)) {
            urlPatterns = smmd.getUrlPatterns();
            break;
          }
        }

        WSFServlet wsfs = new WSFServlet();
        Wrapper wsfsWrapper = context.createWrapper();
        wsfsWrapper.setName(servletName);
        wsfsWrapper.setServlet(wsfs);
        wsfsWrapper.setServletClass(WSFServlet.class.getName());
        for (ParamValueMetaData param : params) {
          wsfsWrapper.addInitParameter(param.getParamName(), param.getParamValue());
        }
        context.addChild(wsfsWrapper);
        for (String urlPattern : urlPatterns) {
          context.addServletMapping(urlPattern, servletName);
        }
      }
    }
  }
 /**
  * Test parsing of jboss-web.xml which doesn't have any distinct-name set
  *
  * @throws Exception
  */
 @Test
 public void testDistinctNameAbsence() throws Exception {
   final MetaDataElementParser.DTDInfo resolver = new MetaDataElementParser.DTDInfo();
   final JBossWebMetaData jBossWebMetaData =
       JBossWebMetaDataParser.parse(getReader("no-distinct-name-jboss-web.xml", resolver));
   Assert.assertNull("Distinct name was expected to be null", jBossWebMetaData.getDistinctName());
 }
  protected Class<?> checkDeclaredApplicationClassAsServlet(
      JBossWebMetaData webData, ClassLoader classLoader) throws DeploymentUnitProcessingException {
    if (webData.getServlets() == null) return null;

    for (ServletMetaData servlet : webData.getServlets()) {
      String servletClass = servlet.getServletClass();
      if (servletClass == null) continue;
      Class<?> clazz = null;
      try {
        clazz = classLoader.loadClass(servletClass);
      } catch (ClassNotFoundException e) {
        throw new DeploymentUnitProcessingException(e);
      }
      if (Application.class.isAssignableFrom(clazz)) {
        servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
        servlet.setAsyncSupported(true);
        ParamValueMetaData param = new ParamValueMetaData();
        param.setParamName("javax.ws.rs.Application");
        param.setParamValue(servletClass);
        List<ParamValueMetaData> params = servlet.getInitParam();
        if (params == null) {
          params = new ArrayList<ParamValueMetaData>();
          servlet.setInitParam(params);
        }
        params.add(param);

        return clazz;
      }
    }
    return null;
  }
Beispiel #8
0
  public static JBossWebMetaData createWebMetaData(
      ReplicationGranularity granularity,
      ReplicationTrigger trigger,
      int maxSessions,
      boolean passivation,
      int maxIdle,
      int minIdle,
      boolean batchMode,
      int maxUnreplicated) {
    JBossWebMetaData webMetaData = new JBossWebMetaData();
    webMetaData.setDistributable(new EmptyMetaData());
    webMetaData.setMaxActiveSessions(new Integer(maxSessions));
    PassivationConfig pcfg = new PassivationConfig();
    pcfg.setUseSessionPassivation(Boolean.valueOf(passivation));
    pcfg.setPassivationMaxIdleTime(new Integer(maxIdle));
    pcfg.setPassivationMinIdleTime(new Integer(minIdle));
    webMetaData.setPassivationConfig(pcfg);
    ReplicationConfig repCfg = new ReplicationConfig();
    repCfg.setReplicationGranularity(granularity);
    repCfg.setReplicationTrigger(trigger);
    repCfg.setReplicationFieldBatchMode(Boolean.valueOf(batchMode));
    repCfg.setMaxUnreplicatedInterval(Integer.valueOf(maxUnreplicated));
    repCfg.setSnapshotMode(SnapshotMode.INSTANT);
    webMetaData.setReplicationConfig(repCfg);

    return webMetaData;
  }
  public static String pathNameOfDeployment(
      final DeploymentUnit deploymentUnit, final JBossWebMetaData metaData) {
    String pathName;
    if (metaData.getContextRoot() == null) {

      final EEModuleDescription description =
          deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
      if (description != null) {
        // if there is a EEModuleDescription we need to take into account that the module name
        // may have been overridden
        pathName = "/" + description.getModuleName();
      } else {
        pathName =
            "/" + deploymentUnit.getName().substring(0, deploymentUnit.getName().length() - 4);
      }
    } else {
      pathName = metaData.getContextRoot();
      if ("/".equals(pathName)) {
        pathName = "";
      } else if (pathName.length() > 0 && pathName.charAt(0) != '/') {
        pathName = "/" + pathName;
      }
    }
    return pathName;
  }
 /**
  * Test parsing of a simple distinct-name (which doesn't have any reference to system properties)
  * in jboss-web.xml
  *
  * @throws Exception
  */
 @Test
 public void testSimpleDistinctName() throws Exception {
   final MetaDataElementParser.DTDInfo resolver = new MetaDataElementParser.DTDInfo();
   final JBossWebMetaData jBossWebMetaData =
       JBossWebMetaDataParser.parse(getReader("simple-distinct-name-jboss-web.xml", resolver));
   Assert.assertEquals(
       "Unexpected distinct name", "simple-foo-bar", jBossWebMetaData.getDistinctName());
 }
 private static String getDeploymentSecurityDomainName(final Endpoint ep) {
   JBossWebMetaData metadata =
       ep.getService().getDeployment().getAttachment(JBossWebMetaData.class);
   String metaDataSecurityDomain = metadata != null ? metadata.getSecurityDomain() : null;
   return metaDataSecurityDomain == null
       ? SecurityConstants.DEFAULT_APPLICATION_POLICY
       : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain.trim());
 }
 /**
  * Test parsing of distinct-name which contains reference to a system property
  *
  * @throws Exception
  */
 @Test
 public void testDistinctNameWithExpression() throws Exception {
   // set the system property first
   System.setProperty("org.jboss.test.metadata.web.sysprop.foo", "bar");
   final MetaDataElementParser.DTDInfo resolver = new MetaDataElementParser.DTDInfo();
   final JBossWebMetaData jBossWebMetaData =
       JBossWebMetaDataParser.parse(getReader("expression-distinct-name-jboss-web.xml", resolver));
   Assert.assertEquals(
       "Unexpected distinct name", "bar-distinct-name", jBossWebMetaData.getDistinctName());
 }
  protected boolean doAccepts(DeploymentUnit unit) {
    // ejbs
    JBossMetaData jbm = unit.getAttachment(JBossMetaData.class);
    if (jbm != null && jbm.isMetadataComplete()) return false;

    // wars
    JBossWebMetaData jwbm = unit.getAttachment(JBossWebMetaData.class);
    if (jwbm != null && jwbm.isMetadataComplete()) return false;

    return true;
  }
 public static void setContextParameter(JBossWebMetaData webdata, String name, String value) {
   ParamValueMetaData param = new ParamValueMetaData();
   param.setParamName(name);
   param.setParamValue(value);
   List<ParamValueMetaData> params = webdata.getContextParams();
   if (params == null) {
     params = new ArrayList<ParamValueMetaData>();
     webdata.setContextParams(params);
   }
   params.add(param);
 }
 private void addValve(JBossWebMetaData webMetaData) {
   List<ValveMetaData> valves = webMetaData.getValves();
   if (valves == null) {
     valves = new ArrayList<ValveMetaData>(1);
     webMetaData.setValves(valves);
   }
   ValveMetaData valve = new ValveMetaData();
   valve.setValveClass(KeycloakAuthenticatorValve.class.getName());
   valve.setModule("org.keycloak.keycloak-as7-adapter");
   // log.info("******* adding Keycloak valve to: " + deploymentName);
   valves.add(valve);
 }
Beispiel #16
0
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    if (warMetaData == null) {
      return; // Nothing we can do without WarMetaData
    }
    final ResourceRoot deploymentRoot =
        deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
    if (deploymentRoot == null) {
      return; // We don't have a root to work with
    }

    final DeploymentUnit parent = deploymentUnit.getParent();
    if (parent == null || !DeploymentTypeMarker.isType(DeploymentType.EAR, parent)) {
      return; // Only care if this war is nested in an EAR
    }

    final EarMetaData earMetaData = parent.getAttachment(Attachments.EAR_METADATA);
    if (earMetaData == null) {
      return; // Nothing to see here
    }

    final ModulesMetaData modulesMetaData = earMetaData.getModules();
    if (modulesMetaData != null)
      for (ModuleMetaData moduleMetaData : modulesMetaData) {
        if (Web.equals(moduleMetaData.getType())
            && moduleMetaData.getFileName().equals(deploymentRoot.getRootName())) {
          String contextRoot =
              WebModuleMetaData.class.cast(moduleMetaData.getValue()).getContextRoot();

          if (contextRoot == null
              && (warMetaData.getJbossWebMetaData() == null
                  || warMetaData.getJbossWebMetaData().getContextRoot() == null)) {
            contextRoot =
                "/"
                    + parent.getName().substring(0, parent.getName().length() - 4)
                    + "/"
                    + deploymentUnit.getName().substring(0, deploymentUnit.getName().length() - 4);
          }

          if (contextRoot != null) {
            JBossWebMetaData jBossWebMetaData = warMetaData.getJbossWebMetaData();
            if (jBossWebMetaData == null) {
              jBossWebMetaData = new JBoss70WebMetaData();
              warMetaData.setJbossWebMetaData(jBossWebMetaData);
            }
            jBossWebMetaData.setContextRoot(contextRoot);
          }
          return;
        }
      }
  }
  private void verifyDependencies(
      String cacheName, ServiceName sessionCacheServiceName, ServiceName jvmRouteCacheServiceName) {
    ReplicationConfig config = new ReplicationConfig();
    config.setCacheName(cacheName);
    JBossWebMetaData metaData = new JBossWebMetaData();
    metaData.setReplicationConfig(config);

    Collection<ServiceName> dependencies = this.factory.getDependencies(metaData);

    assertEquals(2, dependencies.size());
    assertTrue(dependencies.contains(sessionCacheServiceName));
    assertTrue(dependencies.contains(jvmRouteCacheServiceName));
  }
 protected void processEncReferences(WebApplication webApp, Context envCtx)
     throws ClassNotFoundException, NamingException {
   DeploymentUnit unit = webApp.getDeploymentUnit();
   JBossWebMetaData metaData = webApp.getMetaData();
   EnvironmentEntriesMetaData envEntries = metaData.getEnvironmentEntries();
   log.debug("addEnvEntries");
   addEnvEntries(envEntries, envCtx);
   ResourceEnvironmentReferencesMetaData resourceEnvRefs =
       metaData.getResourceEnvironmentReferences();
   log.debug("linkResourceEnvRefs");
   linkResourceEnvRefs(resourceEnvRefs, envCtx);
   ResourceReferencesMetaData resourceRefs = metaData.getResourceReferences();
   log.debug("linkResourceRefs");
   linkResourceRefs(resourceRefs, envCtx);
   log.debug("linkMessageDestinationRefs");
   MessageDestinationReferencesMetaData msgRefs = metaData.getMessageDestinationReferences();
   linkMessageDestinationRefs(unit, msgRefs, envCtx);
   EJBReferencesMetaData ejbRefs = metaData.getEjbReferences();
   log.debug("linkEjbRefs");
   linkEjbRefs(unit, ejbRefs, envCtx);
   EJBLocalReferencesMetaData ejbLocalRefs = metaData.getEjbLocalReferences();
   log.debug("linkEjbLocalRefs");
   linkEjbLocalRefs(unit, ejbLocalRefs, envCtx);
   log.debug("linkServiceRefs");
   ServiceReferencesMetaData serviceRefs = metaData.getServiceReferences();
   linkServiceRefs(unit, serviceRefs, envCtx);
 }
  /**
   * This method is invoked from within subclass performDeploy() method implementations when they
   * invoke WebDescriptorParser.parseWebAppDescriptors().
   *
   * @param loader the ClassLoader for the web application. May not be null.
   * @param metaData the WebMetaData from the WebApplication object passed to the performDeploy
   *     method.
   */
  protected void processEnc(ClassLoader loader, WebApplication webApp) throws Exception {
    if (loader == null)
      throw new IllegalArgumentException("Classloader passed to process ENC refs is null");
    log.debug("AbstractWebContainer.parseWebAppDescriptors, Begin");
    InitialContext iniCtx = new InitialContext();
    Context envCtx = null;
    Thread currentThread = Thread.currentThread();
    ClassLoader currentLoader = currentThread.getContextClassLoader();
    JBossWebMetaData metaData = webApp.getMetaData();
    try {
      // Create a java:comp/env environment unique for the web application
      log.debug("Creating ENC using ClassLoader: " + loader);
      ClassLoader parent = loader.getParent();
      while (parent != null) {
        log.debug(".." + parent);
        parent = parent.getParent();
      }
      // TODO: The enc should be an input?
      currentThread.setContextClassLoader(loader);
      // webApp.setENCLoader(loader);
      envCtx = (Context) iniCtx.lookup("java:comp");

      // TODO: inject the ORB
      ORB orb = null;
      try {
        ObjectName ORB_NAME = new ObjectName("jboss:service=CorbaORB");
        orb = (ORB) server.getAttribute(ORB_NAME, "ORB");
        // Bind the orb
        if (orb != null) {
          NonSerializableFactory.rebind(envCtx, "ORB", orb);
          log.debug("Bound java:comp/ORB");
        }
      } catch (Throwable t) {
        log.debug("Unable to retrieve orb" + t.toString());
      }

      // TODO: injection, Add a link to the global transaction manager
      envCtx.bind("UserTransaction", new LinkRef("UserTransaction"));
      log.debug("Linked java:comp/UserTransaction to JNDI name: UserTransaction");
      envCtx = envCtx.createSubcontext("env");
      processEncReferences(webApp, envCtx);
    } finally {
      currentThread.setContextClassLoader(currentLoader);
    }

    String securityDomain = metaData.getSecurityDomain();
    log.debug("linkSecurityDomain");
    linkSecurityDomain(securityDomain, envCtx);
    log.debug("AbstractWebContainer.parseWebAppDescriptors, End");
  }
 /** If any servlet/filter classes are declared, then we probably don't want to scan. */
 protected boolean hasBootClasses(JBossWebMetaData webdata)
     throws DeploymentUnitProcessingException {
   if (webdata.getServlets() != null) {
     for (ServletMetaData servlet : webdata.getServlets()) {
       String servletClass = servlet.getServletClass();
       if (BOOT_CLASSES.contains(servletClass)) return true;
     }
   }
   if (webdata.getFilters() != null) {
     for (FilterMetaData filter : webdata.getFilters()) {
       if (BOOT_CLASSES.contains(filter.getFilterClass())) return true;
     }
   }
   return false;
 }
  protected void scanWebDeployment(
      final DeploymentUnit du,
      final JBossWebMetaData webdata,
      final ClassLoader classLoader,
      final ResteasyDeploymentData resteasyDeploymentData)
      throws DeploymentUnitProcessingException {

    // If there is a resteasy boot class in web.xml, then the default should be to not scan
    // make sure this call happens before checkDeclaredApplicationClassAsServlet!!!
    boolean hasBoot = hasBootClasses(webdata);
    resteasyDeploymentData.setBootClasses(hasBoot);

    Class<?> declaredApplicationClass =
        checkDeclaredApplicationClassAsServlet(webdata, classLoader);
    // Assume that checkDeclaredApplicationClassAsServlet created the dispatcher
    if (declaredApplicationClass != null) {
      resteasyDeploymentData.setDispatcherCreated(true);
    }

    // set scanning on only if there are no boot classes
    if (!hasBoot && !webdata.isMetadataComplete()) {
      resteasyDeploymentData.setScanAll(true);
      resteasyDeploymentData.setScanProviders(true);
      resteasyDeploymentData.setScanResources(true);
    }

    // check resteasy configuration flags

    List<ParamValueMetaData> contextParams = webdata.getContextParams();

    if (contextParams != null) {
      for (ParamValueMetaData param : contextParams) {
        if (param.getParamName().equals(RESTEASY_SCAN)) {
          resteasyDeploymentData.setScanAll(valueOf(RESTEASY_SCAN, param.getParamValue()));
        } else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS)) {
          resteasyDeploymentData.setScanProviders(
              valueOf(RESTEASY_SCAN_PROVIDERS, param.getParamValue()));
        } else if (param.getParamName().equals(RESTEASY_SCAN_RESOURCES)) {
          resteasyDeploymentData.setScanResources(
              valueOf(RESTEASY_SCAN_RESOURCES, param.getParamValue()));
        } else if (param
            .getParamName()
            .equals(ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS)) {
          resteasyDeploymentData.setUnwrappedExceptionsParameterSet(true);
        }
      }
    }
  }
  public WSEndpointDeploymentUnit(
      ClassLoader loader,
      String context,
      Map<String, String> urlPatternToClassName,
      JBossWebMetaData jbossWebMetaData,
      WebservicesMetaData metadata,
      JBossWebservicesMetaData jbwsMetaData) {
    this.deploymentName = context + ".deployment";

    JAXWSDeployment jaxwsDeployment = new JAXWSDeployment();
    if (jbossWebMetaData == null) {
      jbossWebMetaData = new JBossWebMetaData();
    }
    jbossWebMetaData.setContextRoot(context);
    String endpointName = null;
    String className = null;
    for (String urlPattern : urlPatternToClassName.keySet()) {
      className = urlPatternToClassName.get(urlPattern);
      endpointName = getShortName(className, urlPattern);
      addEndpoint(jbossWebMetaData, jaxwsDeployment, endpointName, className, urlPattern);
    }
    this.putAttachment(WSAttachmentKeys.CLASSLOADER_KEY, loader);
    this.putAttachment(WSAttachmentKeys.JAXWS_ENDPOINTS_KEY, jaxwsDeployment);
    this.putAttachment(WSAttachmentKeys.JBOSSWEB_METADATA_KEY, jbossWebMetaData);
    if (metadata != null) {
      this.putAttachment(WSAttachmentKeys.WEBSERVICES_METADATA_KEY, metadata);
    }
    if (jbwsMetaData != null) {
      this.putAttachment(WSAttachmentKeys.JBOSS_WEBSERVICES_METADATA_KEY, jbwsMetaData);
    }
  }
Beispiel #23
0
  /**
   * Returns context root associated with webservice deployment.
   *
   * <p>If there's application.xml descriptor provided defining nested web module, then context root
   * defined there will be returned. Otherwise context root defined in jboss-web.xml will be
   * returned.
   *
   * @param dep webservice deployment
   * @param jbossWebMD jboss web meta data
   * @return context root
   */
  public static String getContextRoot(final Deployment dep, final JBossWebMetaData jbossWebMD) {
    final DeploymentUnit unit = WSHelper.getRequiredAttachment(dep, DeploymentUnit.class);
    final JBossAppMetaData jbossAppMD =
        unit.getParent() == null
            ? null
            : ASHelper.getOptionalAttachment(
                unit.getParent(), WSAttachmentKeys.JBOSS_APP_METADATA_KEY);

    String contextRoot = null;

    // prefer context root defined in application.xml over one defined in jboss-web.xml
    if (jbossAppMD != null) {
      final ModuleMetaData moduleMD = jbossAppMD.getModules().get(dep.getSimpleName());
      if (moduleMD != null) {
        final WebModuleMetaData webModuleMD = (WebModuleMetaData) moduleMD.getValue();
        contextRoot = webModuleMD.getContextRoot();
      }
    }

    if (contextRoot == null) {
      contextRoot = jbossWebMD != null ? jbossWebMD.getContextRoot() : null;
    }

    return contextRoot;
  }
  private HashMap<String, JspPropertyGroup> createJspConfig(JBossWebMetaData metaData) {
    final HashMap<String, JspPropertyGroup> result = new HashMap<>();
    // JSP Config
    JspConfigMetaData config = metaData.getJspConfig();
    if (config != null) {
      // JSP Property groups
      List<JspPropertyGroupMetaData> groups = config.getPropertyGroups();
      if (groups != null) {
        for (JspPropertyGroupMetaData group : groups) {
          org.apache.jasper.deploy.JspPropertyGroup jspPropertyGroup =
              new org.apache.jasper.deploy.JspPropertyGroup();
          for (String pattern : group.getUrlPatterns()) {
            jspPropertyGroup.addUrlPattern(pattern);
          }
          jspPropertyGroup.setElIgnored(group.getElIgnored());
          jspPropertyGroup.setPageEncoding(group.getPageEncoding());
          jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid());
          jspPropertyGroup.setIsXml(group.getIsXml());
          if (group.getIncludePreludes() != null) {
            for (String includePrelude : group.getIncludePreludes()) {
              jspPropertyGroup.addIncludePrelude(includePrelude);
            }
          }
          if (group.getIncludeCodas() != null) {
            for (String includeCoda : group.getIncludeCodas()) {
              jspPropertyGroup.addIncludeCoda(includeCoda);
            }
          }
          jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(
              group.getDeferredSyntaxAllowedAsLiteral());
          jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces());
          jspPropertyGroup.setDefaultContentType(group.getDefaultContentType());
          jspPropertyGroup.setBuffer(group.getBuffer());
          jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace());
          for (String pattern : jspPropertyGroup.getUrlPatterns()) {
            // Split off the groups to individual mappings
            result.put(pattern, jspPropertyGroup);
          }
        }
      }
    }

    // it looks like jasper needs these in order of least specified to most specific
    final LinkedHashMap<String, JspPropertyGroup> ret = new LinkedHashMap<>();
    final ArrayList<String> paths = new ArrayList<>(result.keySet());
    Collections.sort(
        paths,
        new Comparator<String>() {
          @Override
          public int compare(final String o1, final String o2) {
            return o1.length() - o2.length();
          }
        });
    for (String path : paths) {
      ret.put(path, result.get(path));
    }
    return ret;
  }
  /**
   * A template pattern implementation of the deploy() method. This method calls the {@link
   * #performDeploy(WebApplication, String, WebDescriptorParser) performDeploy()} method to perform
   * the container specific deployment steps and registers the returned WebApplication in the
   * deployment map. The steps performed are:
   *
   * <p>ClassLoader appClassLoader = thread.getContextClassLoader(); URLClassLoader warLoader =
   * URLClassLoader.newInstance(empty, appClassLoader); thread.setContextClassLoader(warLoader);
   * WebDescriptorParser webAppParser = ...; WebMetaData metaData = di.metaData; // Create JACC
   * permissions, contextID, etc. ... WebApplication warInfo = new WebApplication(metaData);
   * performDeploy(warInfo, warUrl, webAppParser); deploymentMap.put(warUrl, warInfo);
   * thread.setContextClassLoader(appClassLoader);
   *
   * <p>The subclass performDeploy() implementation needs to invoke processEnc(loader, warInfo) to
   * have the JNDI java:comp/env namespace setup before any web app component can access this
   * namespace.
   *
   * <p>Also, an MBean for each servlet deployed should be created and its JMX ObjectName placed
   * into the DeploymentInfo.mbeans list so that the JSR77 layer can create the approriate model
   * view. The servlet MBean needs to provide access to the min, max and total time in milliseconds.
   * Expose this information via MinServiceTime, MaxServiceTime and TotalServiceTime attributes to
   * integrate seemlessly with the JSR77 factory layer.
   *
   * @param unit The deployment info that contains the context-root element value from the J2EE
   *     application/module/web application.xml descriptor. This may be null if war was is not being
   *     deployed as part of an enterprise application. It also contains the URL of the web
   *     application war.
   */
  public synchronized WebApplication start(DeploymentUnit unit, JBossWebMetaData metaData)
      throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader appClassLoader = thread.getContextClassLoader();
    WebApplication webApp = null;
    try {
      // Create a classloader for the war to ensure a unique ENC
      ClassLoader warLoader = unit.getClassLoader();
      thread.setContextClassLoader(warLoader);
      String webContext = metaData.getContextRoot();

      // Get the war URL
      URL warUrl = unit.getAttachment("org.jboss.web.expandedWarURL", URL.class);
      if (warUrl == null && unit instanceof VFSDeploymentUnit) {
        VFSDeploymentUnit vdu = VFSDeploymentUnit.class.cast(unit);
        warUrl = VFSUtils.getRealURL(vdu.getRoot());
      }

      // Dynamic WebMetaData deployments might not provide an URL
      // We use the DEploymentUnit name as identifier instead.
      // The JAXWS Endpoint API for example does this.
      String warURLString = (warUrl != null ? warUrl.toExternalForm() : unit.getName());

      // Strip any jar: url syntax. This should be be handled by the vfs
      if (warURLString.startsWith("jar:"))
        warURLString = warURLString.substring(4, warURLString.length() - 2);

      log.debug("webContext: " + webContext);
      log.debug("warURL: " + warURLString);

      // Register the permissions with the JACC layer
      String contextID = metaData.getJaccContextID();
      if (contextID == null) contextID = unit.getSimpleName();
      metaData.setJaccContextID(contextID);

      webApp = new WebApplication(metaData);
      webApp.setClassLoader(warLoader);
      webApp.setDeploymentUnit(unit);
      performDeploy(webApp, warURLString);
    } finally {
      thread.setContextClassLoader(appClassLoader);
    }
    return webApp;
  }
  private void addJSONData(String json, WarMetaData warMetaData) {
    JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
    if (webMetaData == null) {
      webMetaData = new JBossWebMetaData();
      warMetaData.setMergedJBossWebMetaData(webMetaData);
    }

    List<ParamValueMetaData> contextParams = webMetaData.getContextParams();
    if (contextParams == null) {
      contextParams = new ArrayList<ParamValueMetaData>();
    }

    ParamValueMetaData param = new ParamValueMetaData();
    param.setParamName(KeycloakAdapterConfigDeploymentProcessor.AUTH_DATA_PARAM_NAME);
    param.setParamValue(json);
    contextParams.add(param);

    webMetaData.setContextParams(contextParams);
  }
Beispiel #27
0
  /**
   * Returns servlet meta data for requested servlet name.
   *
   * @param jbossWebMD jboss web meta data
   * @param servletName servlet name
   * @return servlet meta data
   */
  public static ServletMetaData getServletForName(
      final JBossWebMetaData jbossWebMD, final String servletName) {
    for (JBossServletMetaData servlet : jbossWebMD.getServlets()) {
      if (servlet.getName().equals(servletName)) {
        return servlet;
      }
    }

    return null;
  }
Beispiel #28
0
  /**
   * Returns servlet meta data for requested servlet name.
   *
   * @param jbossWebMD jboss web meta data
   * @param servletName servlet name
   * @return servlet meta data
   */
  public static ServletMetaData getServletForName(
      final JBossWebMetaData jbossWebMD, final String servletName) {
    for (JBossServletMetaData servlet : jbossWebMD.getServlets()) {
      if (servlet.getName().equals(servletName)) {
        return servlet;
      }
    }

    throw new IllegalStateException("Cannot find servlet for link: " + servletName);
  }
 public static ParamValueMetaData findContextParam(JBossWebMetaData webdata, String name) {
   List<ParamValueMetaData> params = webdata.getContextParams();
   if (params == null) return null;
   for (ParamValueMetaData param : params) {
     if (param.getParamName().equals(name)) {
       return param;
     }
   }
   return null;
 }
 public static boolean servletMappingsExist(JBossWebMetaData webdata, String servletName) {
   List<ServletMappingMetaData> mappings = webdata.getServletMappings();
   if (mappings == null) return false;
   for (ServletMappingMetaData mapping : mappings) {
     if (mapping.getServletName().equals(servletName)) {
       return true;
     }
   }
   return false;
 }