BEGIN: NEVER INVOKED BY WEBSPHERE APPLICATION SERVER (Common Component Specific)
14190
@SuppressWarnings("unchecked")
    public void addWebApplication(DeployedModule deployedModule, List extensionFactories)
								throws Throwable
	{
		WebAppConfiguration wConfig = deployedModule.getWebAppConfig();
		String displayName = wConfig.getDisplayName();
		logger.logp(Level.INFO, CLASS_NAME,"addWebApplication", "loading.web.module", displayName);
		WebApp webApp = deployedModule.getWebApp();
		try
		{
                        this.webApp = webApp;   // PK40127
			webApp.initialize(wConfig, deployedModule, extensionFactories);
		}
		catch (Throwable th)
		{
			webApp.failed();
			webApp.destroy();
			this.webApp = null;     // PK40127
			com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.webcontainer.webapp.WebGroup", "131", this);
			Object[] arg = {displayName};
			logger.logp(Level.SEVERE, CLASS_NAME,"addWebApplication", "Failed.to.initialize.webapp.{0}", arg);
			throw th;
		}
		//this.webApp = webApp;  // PK25527		
		
	}
1076373
public static void main(String[] args) throws Exception {
        ModuleConfigParser mParser = new ModuleConfigParser();
        mParser.parse("/com/ibm/websphere/pmi/custom/test/PmiServletModule1.xml", true);
    }
1113393
public final synchronized void start() throws IOException {
		LaunchingMessageKind.IJMX0001.format(this.host, this.port);
		this.mbs = ManagementFactory.getPlatformMBeanServer();

		final String oldRmiServerName = System
				.getProperty("java.rmi.server.hostname");
		System.setProperty("java.rmi.server.hostname", this.host);

		register = LocateRegistry.createRegistry(this.port);
		if (oldRmiServerName == null) {
			final Properties props = System.getProperties();
			for (Object key : props.keySet()) {
				if (key.equals("java.rmi.server.hostname")) {
					props.remove(key);
					break;
				}
			}
		} else {
			System.setProperty("java.rmi.server.hostname", oldRmiServerName);
		}

		final String serviceURL = String.format(serverUrlFormat, this.host,
				this.host, this.port);
		LaunchingMessageKind.IJMX0002.format(serviceURL);

		final JMXServiceURL url = new JMXServiceURL(serviceURL);
		this.jmxConnectorServer = JMXConnectorServerFactory
				.newJMXConnectorServer(url, null, mbs);
		this.jmxConnectorServer.start();
		registerMBeans();
	}
293465
private static void launchServer(final String url,
                                     final CloseableHttpClient client) {
        try {
            final JDialog dialog = new JDialog();
            dialog.setSize(new java.awt.Dimension(400, 75));
            dialog.setModalityType(ModalityType.MODELESS);
            dialog.setTitle("DuraCloud Sync");
            dialog.setLocationRelativeTo(null);

            JPanel panel = new JPanel();
            final JLabel label = new JLabel("Loading...");
            final JProgressBar progress = new JProgressBar();
            progress.setStringPainted(true);

            panel.add(label);
            panel.add(progress);
            dialog.add(panel);
            dialog.setVisible(true);

            port = SyncUIConfig.getPort();
            contextPath = SyncUIConfig.getContextPath();
            Server srv = new Server(port);

            // Setup JMX
            MBeanContainer mbContainer = new MBeanContainer(
                    ManagementFactory.getPlatformMBeanServer() );
            srv.addBean( mbContainer );

            ProtectionDomain protectionDomain =
                org.duracloud.syncui.SyncUIDriver.class.getProtectionDomain();
            String warFile =
                protectionDomain.getCodeSource().getLocation().toExternalForm();

            log.debug("warfile: {}", warFile);
            WebAppContext context = new WebAppContext();
            context.setContextPath(contextPath);
            context.setWar(warFile);
            context.setExtractWAR(Boolean.TRUE);

            Configuration.ClassList classlist = Configuration.ClassList
                    .setServerDefault( srv );
            classlist.addBefore(
                    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                    "org.eclipse.jetty.annotations.AnnotationConfiguration" );

            context.setAttribute(
                    "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                    ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

            srv.setHandler(context);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    createSysTray(url, srv);

                    while (true) {
                        if (progress.getValue() < 100) {
                            progress.setValue(progress.getValue() + 3);
                        }

                        sleep(2000);
                        if (isAppRunning(url, client)) {
                            break;
                        }
                    }

                    progress.setValue(100);

                    label.setText("Launching browser...");
                    launchBrowser(url);
                    dialog.setVisible(false);
                }
            }).start();

            srv.start();

            srv.join();
        } catch (Exception e) {
            log.error("Error launching server: " + e.getMessage(), e);
        }
    }
854913
void startEngine() throws ServerStartException {

		// setting up the server
		final boolean isDaemon = true;
		final boolean isSilent = false;

		final HsqlProperties hsqlProp = new HsqlProperties();

		// gives the chance to the descriptors to contribute to the server configuration.
		final AtomicInteger dbCounter = new AtomicInteger(0);
		for (HsqlDatabaseDescriptor db : dbs) {
			
			db.contributeToServerConfiguration(new LocationConfiguration() {

				@Override
				public void setLocation(String dbName, String location) {

					log.info("Registering db #{} : '{}' stored on '{}'", dbCounter, dbName, location);
					int dbIndex = dbCounter.getAndAdd(1);
					if (!(location.startsWith("file:") || location.startsWith("res:") || location
							.startsWith("mem:"))) {
						throw new IllegalArgumentException(location);
					}
					
					hsqlProp.setProperty("server.database." + dbIndex, location);
					hsqlProp.setProperty("server.dbname." + dbIndex, dbName);
				}

			});

		}
		// avoid to open a db remotely
		server = new Server();
		hsqlProp.setProperty("server.remote_open", false);
		try {
			server.setProperties(hsqlProp);
		} catch (IOException | AclFormatException e1) {
			throw new ServerStartException(e1);
		}

		server.setLogWriter(lubricantLoggerWriter.asPrintWriter());
		server.setDaemon(isDaemon);
		server.setSilent(isSilent);
		server.setTrace(false);
		server.setNoSystemExit(true);

		if (definedPort != null) {
			server.setPort(definedPort);
		}
		if (this.address != null) {
			server.setAddress(this.address);
		}

		for (int i = 0; i < this.dbs.size(); i++) {
			log.info("db " + i);
			log.info(server.getDatabaseType(i));
			log.info(server.getDatabaseName(i, true));
			log.info(server.getDatabasePath(i, true));
		}

		// dump config
		log.info("Starting HSQL standalone DBMS...");
		log.info("is daemon: {}", isDaemon);
		log.info("is silent: {}", isSilent);
		log.info("port: {} ", (definedPort != null ? definedPort
				: "HSQL default"));
		log.info("address: {} ", (address != null ? address : "HSQL default"));

		log.info("Waiting for hsql engine to start...");
		
		
		Integer state = server.start();
		Throwable serverError = server.getServerError();
		if(serverError!=null){
			throw new ServerStartException(serverError);
		}			
		do {
			state = server.getState();
			Thread.yield();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// nothing special
			}			
		}while(state != 1);
		
		log.info("Hsql engine started.");

		try{
			log.info("Starting databases post setup...");
			for (int i = 0; i < dbs.size(); i++) {
				final HsqlDatabaseDescriptor db = dbs.get(i);
				log.info("Post start up for db '{}', {}/{}.", db.getDbName(), i+1, dbs.size());
				db.postStartSetUp();
				db.goReady();
			}
			log.info("Post setup completed.");			
		}catch(Exception e){
			throw new ServerStartException("An error occurred during post setup.", e);
		}

		log.info("Dump connection strings:");
		for (HsqlDatabaseDescriptor db : dbs) {
			log.info("Connection to db {}: {}, account {}/{} ", db.getDbName(),
					db.getUrl(), db.getDbName(), db.getPassword());
		}

		log.info("HSQL standalone DBMS is ready");

	}
707437
private void fireEventForNonWebModules(Type eventType, Object event, Annotation... qualifiers) {
        try {
                BeanDeploymentModules modules = deploymentManager.getServices().get(BeanDeploymentModules.class);
                if (modules != null) {
                    // fire event for non-web modules
                    // web modules are handled by HttpContextLifecycle
                    for (BeanDeploymentModule module : modules) {
                        if (!module.isWebModule()) {
                            module.fireEvent(eventType, event, qualifiers);
                        }
                    }
                }
            } catch (Exception ignored) {
            }
    }
14556
@FFDCIgnore(Exception.class)
    public void deactivate(ComponentContext componentContext) {
        String methodName = "deactivate";

        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(tc, "Deactivating the WebContainer bundle");
        }
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, methodName, "Posting STOPPED_EVENT");
        }
        Event event = this.eventService.createEvent(WebContainerConstants.STOPPED_EVENT);
        this.eventService.postEvent(event);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, methodName, "Posted STOPPED_EVENT");
        }

        this.classLoadingSRRef.deactivate(componentContext);
        this.sessionHelperSRRef.deactivate(componentContext);
        this.cacheManagerSRRef.deactivate(componentContext);
        this.injectionEngineSRRef.deactivate(componentContext);
        this.managedObjectServiceSRRef.deactivate(context);
        this.servletContainerInitializers.deactivate(componentContext);
        this.transferContextServiceRef.deactivate(componentContext);
        this.webMBeanRuntimeServiceRef.deactivate(componentContext);

        // will now purge each host as it becomes redundant rather than all here.
        //this.vhostManager.purge(); // Clear/purge all maps.

        WebContainer.instance.compareAndSet(this, null);
        extensionFactories.clear();

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, methodName, "Deactivating the WebContainer bundle: Complete");
        }                
    }
1067309
@Activate
    protected void activate(ComponentContext cc) throws Exception {

        RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
        //This is a workaroud to avoid invoking createWoodstoxFactory in org.apache.cxf.staxutils.StaxUtils.createXMLInputFactor
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run()
                            throws Exception
            {
                System.setProperty(StaxUtils.ALLOW_INSECURE_PARSER, "1"); // sets the bla property without throwing an exception -> ok
                return Boolean.TRUE;
            }
        });
        ClassLoader orignalClassLoader = THREAD_CONTEXT_ACCESSOR.getContextClassLoader(Thread.currentThread());
        try {
            //Make sure the current ThreadContextClassLoader is not an App classloader
            THREAD_CONTEXT_ACCESSOR.setContextClassLoader(Thread.currentThread(), JaxRsServiceActivator.class.getClassLoader());
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put("org.apache.cxf.bus.id", "Default Bus");
            Bus defaultBus = LibertyApplicationBusFactory.getInstance().createBus(null, properties);
            LibertyApplicationBusFactory.setDefaultBus(defaultBus);
        } finally {
            THREAD_CONTEXT_ACCESSOR.setContextClassLoader(Thread.currentThread(), orignalClassLoader);
        }

    }
71183
public void run () throws Exception
  {
    if (System.getSecurityManager () != null)
      throw new IllegalStateException ("Security Manager is set but not supported - aborting!");

    final String sTempDir = SystemProperties.getTmpDir ();

    // Create main server
    final Server aServer = new Server (m_aThreadPool);
    {
      // Create connector on Port
      final ServerConnector aConnector = new ServerConnector (aServer);
      aConnector.setPort (m_nPort);
      aConnector.setIdleTimeout (30_000);
      customizeServerConnector (aConnector);
      aServer.setConnectors (new Connector [] { aConnector });
      aServer.setAttribute ("org.eclipse.jetty.server.Request.maxFormContentSize",
                            Integer.valueOf (2 * CGlobal.BYTES_PER_MEGABYTE));
      aServer.setAttribute ("org.eclipse.jetty.server.Request.maxFormKeys", Integer.valueOf (20000));
    }

    customizeServer (aServer);

    final WebAppContext aWebAppCtx = new WebAppContext ();
    {
      aWebAppCtx.setBaseResource (m_aResourceBase);
      aWebAppCtx.setDescriptor (m_sWebXmlResource != null ? m_sWebXmlResource
                                                          : m_aResourceBase.addPath ("/WEB-INF/web.xml").getName ());
      aWebAppCtx.setContextPath (m_sContextPath);
      aWebAppCtx.setTempDirectory (new File (sTempDir + '/' + m_sDirBaseName + ".webapp"));
      aWebAppCtx.setParentLoaderPriority (true);
      aWebAppCtx.setThrowUnavailableOnStartupException (true);
      if (m_sContainerIncludeJarPattern != null)
      {
        // http://www.eclipse.org/jetty/documentation/9.4.x/configuring-webapps.html#container-include-jar-pattern
        // https://github.com/eclipse/jetty.project/issues/680
        aWebAppCtx.setAttribute (WebInfConfiguration.CONTAINER_JAR_PATTERN, m_sContainerIncludeJarPattern);
      }
      if (m_sWebInfIncludeJarPattern != null)
      {
        aWebAppCtx.setAttribute (WebInfConfiguration.WEBINF_JAR_PATTERN, m_sWebInfIncludeJarPattern);
      }

      if (m_bAllowAnnotationBasedConfig)
      {
        // Important to add the AnnotationConfiguration!
        aWebAppCtx.setConfigurations (new Configuration [] { new WebInfConfiguration (),
                                                             new WebXmlConfiguration (),
                                                             new MetaInfConfiguration (),
                                                             new FragmentConfiguration (),
                                                             new AnnotationConfiguration (),
                                                             new JettyWebXmlConfiguration () });
      }
      // else leave default
    }

    // Set session store directory to passivate/activate sessions
    if (m_bSpecialSessionMgr)
    {
      final SessionHandler aHdl = new SessionHandler ();
      final FileSessionDataStore aDataStore = new FileSessionDataStore ();
      aDataStore.setStoreDir (new File (sTempDir + '/' + m_sDirBaseName + ".sessions"));
      aDataStore.setDeleteUnrestorableFiles (true);
      final DefaultSessionCache aCache = new DefaultSessionCache (aHdl);
      aCache.setSessionDataStore (aDataStore);
      aCache.setRemoveUnloadableSessions (true);
      aHdl.setSessionCache (aCache);
      aWebAppCtx.setSessionHandler (aHdl);
    }

    if (StringHelper.hasText (m_sSessionCookieName))
      aWebAppCtx.getSessionHandler ().setSessionCookie (m_sSessionCookieName);

    customizeWebAppCtx (aWebAppCtx);

    aServer.setHandler (aWebAppCtx);
    final ServletContextHandler aCtx = aWebAppCtx;

    // Setting final properties
    // Stops the server when ctrl+c is pressed (registers to
    // Runtime.addShutdownHook)
    aServer.setStopAtShutdown (true);

    if (false)
    {
      // Debug output
      aServer.setDumpBeforeStop (true);
    }

    try
    {
      // Starting shutdown listener thread
      // May fail if port is in use
      if (m_bRunStopMonitor)
        new InternalJettyStopMonitorThread (m_nStopPort, m_sStopKey, () -> aServer.stop ()).start ();

      // Starting the engines:
      aServer.start ();
      LOGGER.info ("Started Jetty" + ":" + m_nPort + ":" + m_nStopPort + " " + m_sAppName);

      // Callback
      onServerStarted (aServer);

      Runtime.getRuntime ().addShutdownHook (new Thread ( () -> {
        try
        {
          aServer.stop ();
          aServer.join ();
        }
        catch (final Exception ex)
        {
          LOGGER.error ("Exception in ShutdownHook of JettyStarter!", ex);
        }
      }));
    }
    catch (final Throwable t)
    {
      // Do not throw something here, in case some exception occurs in finally
      // code
      LOGGER.error ("Failed to start Jetty " + m_sAppName + "!", t);

      // Callback
      onServerStartFailure (aServer, t);
    }
    finally
    {
      if (aCtx.isFailed ())
      {
        LOGGER.error ("Failed to start Jetty " + m_sAppName + " - stopping server!");
        try
        {
          // Throws an Exception e.g. in log4j2 2.5
          aServer.stop ();
          LOGGER.error ("Failed to start Jetty " + m_sAppName + " - stopped server!");
        }
        catch (final Throwable t)
        {
          LOGGER.error ("Error stopping Jetty " + m_sAppName + " after startup errors!", t);
        }
      }
      else
        if (!aServer.isFailed ())
        {
          // Running the server!
          aServer.join ();
        }
    }
  }
1020900
@Override
    public void doExecute() throws MojoExecutionException {
        getLog().info(" ");
        getLog().info(LINE_SEPARATOR);
        getLog().info(" S T A R T I N G    J M E T E R    S E R V E R ");
        getLog().info(LINE_SEPARATOR);
        getLog().info(String.format(" Host: %s", exportedRmiHostname));
        getLog().info(String.format(" Port: %s", serverPort));
        startJMeterServer(initializeJMeterArgumentsArray());
    }
673352
public static void main(String[] args) {

    	PluginUtilityConsole console = new PluginUtilityConsole(System.console(), System.out,System.err);
    
        // This is only needed for the GenerateFromServerPluginsTask so comment out for now.
        //IGeneratePluginConfigMBeanConnection pluginUtilityMBeanConn = new GeneratePluginConfigMBeanConnection(System.out, System.err, fileUtil);

        WebServerPluginUtility util = new WebServerPluginUtility(console);

        // Initially we are only going to deliver the function for MergePluginFilesTask
        //util.registerTask(new GenerateFromServerPluginTask(SCRIPT_NAME, fileUtil, pluginUtilityMBeanConn));
        util.registerTask(new MergePluginFilesTask(SCRIPT_NAME));
        util.registerTask(new GeneratePluginTask(SCRIPT_NAME,console));
       // util.registerTask(new DynamicRoutingPluginTask(SCRIPT_NAME, fileUtil));

        int rc = util.runProgram(args);

        System.exit(rc);
    }
266413
@Override
    public boolean contextListenerStart() {
		boolean ok = super.contextListenerStart();
		//the web listeners couldn't be started so we don't even try to load the sip ones
		if(!ok) {
			return ok;
		}

		if (logger.isDebugEnabled())
            logger.debug("Configuring sip listeners");

        // Instantiate the required listeners
        ClassLoader loader = getLoader().getClassLoader();
        ok = sipListeners.loadListeners(findSipApplicationListeners(), loader);
        if(!ok) {
			return ok;
		}

        List<ServletContextListener> servletContextListeners = sipListeners.getServletContextListeners();
        if (servletContextListeners != null) {
            ServletContextEvent event =
                new ServletContextEvent(getServletContext());
            for (ServletContextListener servletContextListener : servletContextListeners) {
                if (servletContextListener == null)
                    continue;

                try {
                    fireContainerEvent("beforeContextInitialized", servletContextListener);
                    servletContextListener.contextInitialized(event);
                    fireContainerEvent("afterContextInitialized", servletContextListener);
                } catch (Throwable t) {
                    fireContainerEvent("afterContextInitialized", servletContextListener);
//                    getLogger().error
//                        (sm.getString("standardContext.listenerStart",
//                        		servletContextListener.getClass().getName()), t);
                    getLogger().error
                    	(MESSAGES.errorSendingContextInitializedEvent(servletContextListener.getClass().getName()), t);
                    ok = false;
                }

                // TODO Annotation processing
            }
        }

        return (ok);

    }
364636
protected synchronized void doStart()
        throws Exception
    {
        if (isStarted())
            return;
        
        _contextLog = LogFactory.getLog("org.browsermob.proxy.jetty.jetty.context."+getHttpContext().getHttpContextName());
        
        if (_contextLog==null)
            _contextLog=log;
        
        if (_sessionManager!=null)
            _sessionManager.start();
        
        // Initialize classloader
        _loader=getHttpContext().getClassLoader();

        if (_autoInitializeServlets)
            initializeServlets();
    }
553106
public void servletInitialized(SipServletContextEvent ce) {
		String sendOnInit = ce.getServletContext().getInitParameter("send-on-init");
		String method = ce.getServletContext().getInitParameter("method");
		logger.info("Send on Init : "+ sendOnInit);
		if(sendOnInit == null || "true".equals(sendOnInit)) {
			SipFactory sipFactory = (SipFactory) getServletContext().getAttribute(SIP_FACTORY);
			SipApplicationSession sipApplicationSession = sipFactory.createApplicationSession();
			if(method.equalsIgnoreCase("INVITE")) {								
				sendMessage(sipFactory.createApplicationSession(), method);				
			} else {
				timerService.createTimer(sipApplicationSession, 10000, 20000, true, true, method);
			}
		}
	}
1281694
protected void initializeTargetMappings() throws Exception {
        // NOTE: namespace preinvoke/postinvoke not necessary as the only
        // external
        // code being run is the servlet's init() and that is handled in the
        // ServletWrapper

        // check if an extensionFactory is present for *.jsp:
        // We do this by constructing an arbitrary mapping which
        // will only match the *.xxx extension pattern
        //
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
            logger.entering(CLASS_NAME, "initializeTargetMappings");

        initializeStaticFileHandler();

        initializeInvokerProcessor();

        if (config.isDirectoryBrowsingEnabled()) {
            try {
                IServletWrapper dirServlet = getServletWrapper("DirectoryBrowsingServlet");
                requestMapper.addMapping(DIR_BROWSING_MAPPING, dirServlet);
            } catch (WebContainerException wce) {
                // pk435011
                logger.logp(Level.WARNING, CLASS_NAME, "initializeTargetMappings", "mapping.for.directorybrowsingservlet.already.exists");

            } catch (Exception exc) {
                // pk435011
                logger.logp(Level.WARNING, CLASS_NAME, "initializeTargetMappings", "mapping.for.directorybrowsingservlet.already.exists");
            }
        }

    }
910503
public Object beginContext(ComponentMetaData cmd) { // modified to return object d131914
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            if (cmd != null)
                Tr.debug(tc, "begin context " + cmd.getJ2EEName());
            else
                Tr.debug(tc, "NULL was passed.");
        }

        if (cmd == null) {
            Tr.error(tc, "WSVR0603E"); // d143991
            throw new IllegalArgumentException(Tr.formatMessage(tc, "WSVR0603E"));
        }

        return threadContext.beginContext(cmd); //131914
    }
319980
static AbstractBeanDefinition findServerForSpecialEnvironment() {
        boolean weblogicPresent = ClassUtils.isPresent("weblogic.management.Helper",
                ServletContextAwareMBeanServerDefinitionParser.class.getClassLoader());

        boolean webspherePresent = ClassUtils.isPresent("com.ibm.websphere.management.AdminServiceFactory",
                ServletContextAwareMBeanServerDefinitionParser.class.getClassLoader());

        if (weblogicPresent) {
            RootBeanDefinition bd = new RootBeanDefinition(JndiObjectFactoryBean.class);
            bd.getPropertyValues().add("jndiName", "java:comp/env/jmx/runtime");
            return bd;
        } else if (webspherePresent) {
            return new RootBeanDefinition(WebSphereMBeanServerFactoryBean.class);
        } else {
            return null;
        }
    }