Esempio n. 1
0
  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 start(StartContext startContext) throws StartException {

    ServerEnvironment env = injectedServerEnvironment.getValue();
    Host virtualHost = injectedVirtualHost.getValue().getHost();
    BundleContext syscontext = injectedSystemContext.getValue();
    WebServer webServer = injectedWebServer.getValue();

    File storageDir =
        new File(
            env.getServerTempDir()
                + File.separator
                + CONTEXT_NAME
                + File.separator
                + "httpservice-root");
    context.setDocBase(storageDir.getPath());
    storageDir.mkdirs();

    context.setPath(CONTEXT_NAME);
    context.addLifecycleListener(new ContextConfig());
    Loader loader = new WebCtxLoader(getClass().getClassLoader());
    loader.setContainer(virtualHost);
    context.setLoader(loader);
    context.setInstanceManager(new LocalInstanceManager());

    context.addMimeMapping("html", "text/html");
    context.addMimeMapping("jpg", "image/jpeg");
    context.addMimeMapping("png", "image/png");
    context.addMimeMapping("gif", "image/gif");
    context.addMimeMapping("css", "text/css");
    context.addMimeMapping("js", "text/javascript");

    virtualHost.addChild(context);

    WEB_LOGGER.registerWebapp(context.getName());
    try {
      context.create();
    } catch (Exception ex) {
      throw new StartException(WebMessages.MESSAGES.createContextFailed(), ex);
    }
    try {
      context.start();
    } catch (LifecycleException ex) {
      throw new StartException(WebMessages.MESSAGES.startContextFailed(), ex);
    }

    Hashtable<String, Object> props = new Hashtable<String, Object>();
    props.put(Constants.SERVICE_RANKING, Integer.MIN_VALUE);
    props.put("provider", getClass().getPackage().getName());

    ServiceFactory serviceFactory = new HttpServiceFactory(webServer, virtualHost, context);
    registration = syscontext.registerService(HttpService.class.getName(), serviceFactory, props);
  }
  @Override
  public synchronized void start() throws Exception {

    Host host = ServerUtil.getDefaultHost().getHost();
    _serverContext = (StandardContext) host.findChild("/" + _contextName);
    if (_serverContext == null) {
      _serverContext = new StandardContext();
      _serverContext.setPath("/" + _contextName);
      File docBase = new File(SERVER_TEMP_DIR, _contextName);
      if (!docBase.exists()) {
        if (!docBase.mkdirs()) {
          throw new RuntimeException("Unable to create temp directory " + docBase.getPath());
        }
      }
      _serverContext.setDocBase(docBase.getPath());
      _serverContext.addLifecycleListener(new ContextConfig());

      final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader());
      loader.setContainer(host);
      _serverContext.setLoader(loader);
      _serverContext.setInstanceManager(new LocalInstanceManager());

      Wrapper wrapper = _serverContext.createWrapper();
      wrapper.setName(SERVLET_NAME);
      wrapper.setServletClass(SwitchYardRemotingServlet.class.getName());
      wrapper.setLoadOnStartup(1);
      _serverContext.addChild(wrapper);
      _serverContext.addServletMapping("/*", SERVLET_NAME);

      host.addChild(_serverContext);
      _serverContext.create();
      _serverContext.start();

      SwitchYardRemotingServlet remotingServlet = (SwitchYardRemotingServlet) wrapper.getServlet();
      remotingServlet.setEndpointPublisher(this);
      _log.info("Published Remote Service Endpoint " + _serverContext.getPath());
    } else {
      throw new RuntimeException("Context " + _contextName + " already exists!");
    }
  }
  protected void processDeployment(
      final String hostName, final WarMetaData warMetaData, final DeploymentUnitContext context)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot = VirtualFileAttachment.getVirtualFileAttachment(context);
    final Module module = context.getAttachment(ModuleDeploymentProcessor.MODULE_ATTACHMENT_KEY);
    if (module == null) {
      throw new DeploymentUnitProcessingException(
          "failed to resolve module for deployment " + deploymentRoot);
    }
    final ClassLoader classLoader = module.getClassLoader();
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();

    // Create the context
    final StandardContext webContext = new StandardContext();
    final ContextConfig config = new JBossContextConfig(context);
    // Set the deployment root
    try {
      webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath());
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(e);
    }
    webContext.addLifecycleListener(config);

    // Set the path name
    final String deploymentName = context.getName();
    String pathName = null;
    if (metaData.getContextRoot() == null) {
      pathName = deploymentRoot.getName();
      if (pathName.equals("ROOT.war")) {
        pathName = "";
      } else {
        pathName = "/" + pathName.substring(0, pathName.length() - 4);
      }
    } else {
      pathName = metaData.getContextRoot();
      if ("/".equals(pathName)) {
        pathName = "";
      }
    }
    webContext.setPath(pathName);
    webContext.setIgnoreAnnotations(true);

    // Add a dummy realm for now
    Realm realm = new MemoryRealm();
    webContext.setRealm(realm);

    //
    final Loader loader = new WebCtxLoader(classLoader);
    final InstanceManager manager = new WebInjectionContainer(classLoader);
    webContext.setInstanceManager(manager);
    webContext.setLoader(loader);

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
      case JBossWebMetaData.SESSION_COOKIES_ENABLED:
        webContext.setCookies(true);
        break;
      case JBossWebMetaData.SESSION_COOKIES_DISABLED:
        webContext.setCookies(false);
        break;
    }

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    // Add the context service
    final BatchBuilder builder = context.getBatchBuilder();
    builder
        .addService(
            WebSubsystemElement.JBOSS_WEB.append(deploymentName),
            new WebDeploymentService(webContext))
        .addDependency(
            WebSubsystemElement.JBOSS_WEB_HOST.append(hostName),
            Host.class,
            new WebContextInjector(webContext))
        .setInitialMode(Mode.ACTIVE);
  }
  protected void processDeployment(
      final String hostName,
      final WarMetaData warMetaData,
      final DeploymentUnit deploymentUnit,
      final ServiceTarget serviceTarget)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot =
        deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToResolveModule(deploymentRoot));
    }
    final ClassLoader classLoader = module.getClassLoader();
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();
    final List<SetupAction> setupActions =
        deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS);

    // Create the context
    final StandardContext webContext = new StandardContext();
    final JBossContextConfig config = new JBossContextConfig(deploymentUnit);

    // Add SecurityAssociationValve right at the beginning
    webContext.addValve(new SecurityContextAssociationValve(deploymentUnit));

    // Set the deployment root
    try {
      webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath());
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(e);
    }
    webContext.addLifecycleListener(config);

    final String pathName = pathNameOfDeployment(deploymentUnit, metaData);
    webContext.setPath(pathName);
    webContext.setIgnoreAnnotations(true);
    webContext.setCrossContext(!metaData.isDisableCrossContext());

    final WebInjectionContainer injectionContainer =
        new WebInjectionContainer(module.getClassLoader());

    // see AS7-2077
    // basically we want to ignore components that have failed for whatever reason
    // if they are important they will be picked up when the web deployment actually starts
    final Map<String, ComponentInstantiator> components =
        deploymentUnit.getAttachment(WebAttachments.WEB_COMPONENT_INSTANTIATORS);
    if (components != null) {
      final Set<ServiceName> failed =
          deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.FAILED_COMPONENTS);
      for (Map.Entry<String, ComponentInstantiator> entry : components.entrySet()) {
        boolean skip = false;
        for (final ServiceName serviceName : entry.getValue().getServiceNames()) {
          if (failed.contains(serviceName)) {
            skip = true;
            break;
          }
        }
        if (!skip) {
          injectionContainer.addInstantiator(entry.getKey(), entry.getValue());
        }
      }
    }

    final Loader loader = new WebCtxLoader(classLoader);
    webContext.setLoader(loader);

    // Valves
    List<ValveMetaData> valves = metaData.getValves();
    if (valves == null) {
      metaData.setValves(valves = new ArrayList<ValveMetaData>());
    }
    for (ValveMetaData valve : valves) {
      Valve valveInstance =
          (Valve) getInstance(module, valve.getModule(), valve.getValveClass(), valve.getParams());
      webContext.getPipeline().addValve(valveInstance);
    }

    // Container listeners
    List<ContainerListenerMetaData> listeners = metaData.getContainerListeners();
    if (listeners != null) {
      for (ContainerListenerMetaData listener : listeners) {
        switch (listener.getListenerType()) {
          case CONTAINER:
            ContainerListener containerListener =
                (ContainerListener)
                    getInstance(
                        module,
                        listener.getModule(),
                        listener.getListenerClass(),
                        listener.getParams());
            webContext.addContainerListener(containerListener);
            break;
          case LIFECYCLE:
            LifecycleListener lifecycleListener =
                (LifecycleListener)
                    getInstance(
                        module,
                        listener.getModule(),
                        listener.getListenerClass(),
                        listener.getParams());
            if (webContext instanceof Lifecycle) {
              ((Lifecycle) webContext).addLifecycleListener(lifecycleListener);
            }
            break;
          case SERVLET_INSTANCE:
            webContext.addInstanceListener(listener.getListenerClass());
            break;
          case SERVLET_CONTAINER:
            webContext.addWrapperListener(listener.getListenerClass());
            break;
          case SERVLET_LIFECYCLE:
            webContext.addWrapperLifecycle(listener.getListenerClass());
            break;
        }
      }
    }

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
      case JBossWebMetaData.SESSION_COOKIES_ENABLED:
        webContext.setCookies(true);
        break;
      case JBossWebMetaData.SESSION_COOKIES_DISABLED:
        webContext.setCookies(false);
        break;
    }

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    String securityDomain =
        metaDataSecurityDomain == null
            ? SecurityConstants.DEFAULT_APPLICATION_POLICY
            : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain);

    // Setup an deployer configured ServletContext attributes
    final List<ServletContextAttribute> attributes =
        deploymentUnit.getAttachment(ServletContextAttribute.ATTACHMENT_KEY);

    try {
      final ServiceName deploymentServiceName =
          WebSubsystemServices.deploymentServiceName(hostName, pathName);
      final ServiceName realmServiceName = deploymentServiceName.append("realm");

      final JBossWebRealmService realmService = new JBossWebRealmService(deploymentUnit);
      ServiceBuilder<?> builder = serviceTarget.addService(realmServiceName, realmService);
      builder
          .addDependency(
              DependencyType.REQUIRED,
              SecurityDomainService.SERVICE_NAME.append(securityDomain),
              SecurityDomainContext.class,
              realmService.getSecurityDomainContextInjector())
          .setInitialMode(Mode.ACTIVE)
          .install();

      final WebDeploymentService webDeploymentService =
          new WebDeploymentService(webContext, injectionContainer, setupActions, attributes);
      builder =
          serviceTarget
              .addService(deploymentServiceName, webDeploymentService)
              .addDependency(
                  WebSubsystemServices.JBOSS_WEB_HOST.append(hostName),
                  VirtualHost.class,
                  new WebContextInjector(webContext))
              .addDependencies(injectionContainer.getServiceNames())
              .addDependency(realmServiceName, Realm.class, webDeploymentService.getRealm())
              .addDependencies(deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES))
              .addDependency(JndiNamingDependencyProcessor.serviceName(deploymentUnit));

      // add any dependencies required by the setup action
      for (final SetupAction action : setupActions) {
        builder.addDependencies(action.dependencies());
      }

      if (metaData.getDistributable() != null) {
        DistributedCacheManagerFactoryService factoryService =
            new DistributedCacheManagerFactoryService();
        DistributedCacheManagerFactory factory = factoryService.getValue();
        if (factory != null) {
          ServiceName factoryServiceName = deploymentServiceName.append("session");
          builder.addDependency(
              DependencyType.OPTIONAL,
              factoryServiceName,
              DistributedCacheManagerFactory.class,
              config.getDistributedCacheManagerFactoryInjector());

          ServiceBuilder<DistributedCacheManagerFactory> factoryBuilder =
              serviceTarget.addService(factoryServiceName, factoryService);
          boolean enabled = factory.addDependencies(serviceTarget, factoryBuilder, metaData);
          factoryBuilder
              .setInitialMode(
                  enabled ? ServiceController.Mode.ON_DEMAND : ServiceController.Mode.NEVER)
              .install();
        }
      }

      builder.install();

      // adding JACC service
      AbstractSecurityDeployer<?> deployer = new WarSecurityDeployer();
      JaccService<?> service = deployer.deploy(deploymentUnit);
      if (service != null) {
        ((WarJaccService) service).setContext(webContext);
        final ServiceName jaccServiceName =
            JaccService.SERVICE_NAME.append(deploymentUnit.getName());
        builder = serviceTarget.addService(jaccServiceName, service);
        if (deploymentUnit.getParent() != null) {
          // add dependency to parent policy
          final DeploymentUnit parentDU = deploymentUnit.getParent();
          builder.addDependency(
              JaccService.SERVICE_NAME.append(parentDU.getName()),
              PolicyConfiguration.class,
              service.getParentPolicyInjector());
        }
        // add dependency to web deployment service
        builder.addDependency(deploymentServiceName);
        builder.setInitialMode(Mode.ACTIVE).install();
      }
    } catch (ServiceRegistryException e) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToAddWebDeployment(), e);
    }

    // Process the web related mgmt information
    final ModelNode node = deploymentUnit.getDeploymentSubsystemModel("web");
    node.get("context-root").set("".equals(pathName) ? "/" : pathName);
    node.get("virtual-host").set(hostName);
    processManagement(deploymentUnit, metaData);
  }