Entry point for embedded applications.  This method attaches
to the given {@link ContextFactory} with the given scope.  No
I/O redirection is performed as with {@link #main(String[])}.
323030
public static Main mainEmbedded(ContextFactory factory,
                                    ScopeProvider scopeProvider,
                                    String title) {
        return mainEmbeddedImpl(factory, scopeProvider, title);
    }
785888
public void addContextDataFactory(ContextDataFactory contextDataFactory) {
		if (contextDataFactory == null) {
			throw new IllegalArgumentException("Parameter contextDataFactory must not be null.");
		}
		this.contextDataFactories.add(contextDataFactory);

		if (postInitialisation) {
			for (Context context : getSession().getContexts()) {
				contextDataFactory.loadContextData(getSession(), context);
			}
		}
	}
150973
@SuppressWarnings("unchecked")
    void initThreadContext(WSContextService contextSvc, Map<String, String> execProps) {
        threadContext = contextSvc.captureThreadContext(execProps);
    }
1048479
public Interceptor create(final InterceptorFactoryContext context) {
        final InterceptorFactory[] factories = interceptorFactories;
        final int length = factories.length;
        final Interceptor[] interceptors = new Interceptor[length];
        for (int i = 0; i < length; i++) {
            interceptors[i] = factories[i].create(context);
        }
        return new ChainedInterceptor(interceptors);
    }
1159064
public static ConfigurableApplicationContext start(Class<?>[] app, String... args) {
        Class<?>[] apps = ObjectArrays.concat(app, GHEventApiServer.class);
        return SpringApplication.run(apps, args);
    }
492240
public void enableMvc(ConfigurableListableBeanFactory factory, BundleContext context) {
        if (factory == null) {
            throw new IllegalArgumentException("Method argument factory must not be null.");
        }
        if (context == null) {
            throw new IllegalArgumentException("Method argument context must not be null.");
        }

        BundleAwareServletConfig servletConfig = new BundleAwareServletConfig(context);

        factory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, servletConfig));
        factory.ignoreDependencyInterface(ServletContextAware.class);
        factory.ignoreDependencyInterface(ServletConfigAware.class);

        final BundleSpecificDispatcherServlet dispatcherServlet = createBundleSpecificDispatcherServlet(factory, servletConfig);
        factory.registerSingleton(generateNameFor(BundleSpecificDispatcherServlet.class), dispatcherServlet);
        this.mvcCapableBundles.put(context.getBundle(), dispatcherServlet);
    }
668626
@Override
  public Object execute(@Nonnull final CommandContext context) throws Exception {
    IO io = context.getIo();
    Variables variables = context.getVariables();

    // TODO: args may need special handling for ~/ as this won't translate to executable

    log.debug("Executing: {}", args);

    ProcessBuilder builder = new ProcessBuilder()
      .command(args)
      .inheritIO();

    File dir = directory;
    if (dir == null) {
      dir = variables.require(VariableNames.SHELL_USER_DIR, File.class);
    }
    log.debug("Directory: {}", dir);
    builder.directory(dir);

    if (!newenvironment) {
      log.debug("Propagating environment variables");
      builder.environment().putAll(System.getenv());
    }

    Process p = builder.start();

    PumpStreamHandler handler = new PumpStreamHandler(io.streams.out, io.streams.err);
    handler.setProcessInputStream(p.getOutputStream());
    handler.setProcessOutputStream(p.getInputStream());
    handler.setProcessErrorStream(p.getErrorStream());

    handler.start();

    log.debug("Waiting for process to exit...");

    int exitCode = p.waitFor();

    log.debug("Process exited w/code: {}", exitCode);

    handler.stop();

    return exitCode;
  }
124216
protected void configureContext(Context context,
			ServletContextInitializer[] initializers) {
		TomcatStarter starter = new TomcatStarter(initializers);
		if (context instanceof TomcatEmbeddedContext) {
			TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context;
			embeddedContext.setStarter(starter);
			embeddedContext.setFailCtxIfServletStartFails(true);
		}
		context.addServletContainerInitializer(starter, NO_CLASSES);
		for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) {
			context.addLifecycleListener(lifecycleListener);
		}
		for (Valve valve : this.contextValves) {
			context.getPipeline().addValve(valve);
		}
		for (ErrorPage errorPage : getErrorPages()) {
			new TomcatErrorPage(errorPage).addToContext(context);
		}
		for (MimeMappings.Mapping mapping : getMimeMappings()) {
			context.addMimeMapping(mapping.getExtension(), mapping.getMimeType());
		}
		configureSession(context);
		new DisableReferenceClearingContextCustomizer().customize(context);
		for (TomcatContextCustomizer customizer : this.tomcatContextCustomizers) {
			customizer.customize(context);
		}
	}
500725
public static void main(final String[] args) throws IOException, InjectionException {
    final ClientProtocol.DriverClientConfiguration driverClientConfigurationProto;
    if (args.length > 0) {
      final String content = new String(Files.readAllBytes(Paths.get(args[0])));
      final ClientProtocol.DriverClientConfiguration.Builder driverClientConfigurationProtoBuilder =
          ClientProtocol.DriverClientConfiguration.newBuilder();
      JsonFormat.parser()
          .usingTypeRegistry(JsonFormat.TypeRegistry.getEmptyTypeRegistry())
          .merge(content, driverClientConfigurationProtoBuilder);
      driverClientConfigurationProto = driverClientConfigurationProtoBuilder.build();
      final int port = (args.length == 2) ? Integer.parseInt(args[1]) : 0;
      final LauncherStatus status = submit(port, driverClientConfigurationProto);
      LOG.log(Level.INFO, "Status: {0}", status);
    } else {
      LOG.log(Level.SEVERE, ClientLauncher.class.getName() +
          " accepts single required argument referencing a file that contains a " +
          "client protocol buffer driver configuration");
      System.exit(1);
    }
  }
239853
public void contextInitialized(ServletContextEvent event) {
        this.context = event.getServletContext();

        // Output a simple message to the server's console
        System.out.println("The Simple Web App. Is Ready");

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "/client.xml");
        LocatorService client = (LocatorService) context
                .getBean("locatorService");

        String serviceHost = this.context.getInitParameter("serviceHost");

        try {
            client.registerEndpoint(new QName(
                    "http://talend.org/esb/examples/", "GreeterService"),
                    serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);
        } catch (InterruptedExceptionFault e) {
            e.printStackTrace();
        } catch (ServiceLocatorFault e) {
            e.printStackTrace();
        }
    }
1051957
public Object beginContext(Map<URL, ModuleMetaData> mmdi) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            if (mmdi != null && !mmdi.isEmpty())
                Tr.debug(tc, "begin context " + mmdi.values().iterator().next().getJ2EEName());
            else
                Tr.debug(tc, "null or empty object was passed.");
        }

        return threadContext.beginContext(mmdi);
    }
825796
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;

		if (servletContext == null)
			if (applicationContext instanceof WebApplicationContext) {
				servletContext = ((WebApplicationContext) applicationContext).getServletContext();
				if (servletContext == null) {
					System.err.print("this class only fit for Spring Web Application");
					return;
				}

			}

		// start up jdon
		AppContextWrapper acw = new ServletContextWrapper(servletContext);
		ContainerFinder containerFinder = new ContainerFinderImp();
		containerWrapper = containerFinder.findContainer(acw);

	}
860037
public WebApplicationContext addWebApplication(String contextPathSpec,
                                                   String webApp)
        throws IOException
    {
        return addWebApplication(null,contextPathSpec,webApp);
    }
1256917
public static void main(String[] args) throws InterruptedException {
        Channel mainChannel = new NamedChannel("main");
        EchoUntilQuit app = new EchoUntilQuit(mainChannel);
        app.attach(new InputStreamMonitor(mainChannel, System.in));
        Components.start(app);
        Components.awaitExhaustion();
    }
976553
protected void initializeContext(
            @Nonnull List<BeanDefinitionReference> contextScopeBeans,
            @Nonnull List<BeanDefinitionReference> processedBeans) {

        if (CollectionUtils.isNotEmpty(contextScopeBeans)) {
            final Collection<BeanDefinition> contextBeans = new ArrayList<>();

            for (BeanDefinitionReference contextScopeBean : contextScopeBeans) {
                try {
                    loadContextScopeBean(contextScopeBean, contextBeans::add);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeBean.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            filterProxiedTypes((Collection) contextBeans, true, false);
            filterReplacedBeans((Collection) contextBeans);

            for (BeanDefinition contextScopeDefinition: contextBeans) {
                try {
                    loadContextScopeBean(contextScopeDefinition);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeDefinition.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            contextBeans.clear();
        }

        if (!processedBeans.isEmpty()) {

            @SuppressWarnings("unchecked") Stream<BeanDefinitionMethodReference<?, ?>> methodStream = processedBeans
                    .stream()
                    // is the bean reference enabled
                    .filter(ref -> ref.isEnabled(this))
                    // ok - continue and load it
                    .map((Function<BeanDefinitionReference, BeanDefinition<?>>) reference -> {
                        try {
                            return reference.load(this);
                        } catch (Exception e) {
                            throw new BeanInstantiationException("Bean definition [" + reference.getName() + "] could not be loaded: " + e.getMessage(), e);
                        }
                    })
                    // is the bean itself enabled
                    .filter(bean -> bean.isEnabled(this))
                    // ok continue and get all of the ExecutableMethod references
                    .flatMap(beanDefinition ->
                            beanDefinition.getExecutableMethods()
                                    .parallelStream()
                                    .map((Function<ExecutableMethod<?, ?>, BeanDefinitionMethodReference<?, ?>>) executableMethod ->
                                            BeanDefinitionMethodReference.of((BeanDefinition) beanDefinition, executableMethod)
                                    )
                    );

            // group the method references by annotation type such that we have a map of Annotation -> MethodReference
            // ie. Class<Scheduled> -> @Scheduled void someAnnotation()
            Map<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> byAnnotation = methodStream
                    .collect(
                            Collectors.groupingBy((Function<ExecutableMethod<?, ?>, Class<? extends Annotation>>) executableMethod ->
                                    executableMethod.getAnnotationTypeByStereotype(Executable.class)
                                            .orElseThrow(() ->
                                                    new IllegalStateException("BeanDefinition.requiresMethodProcessing() returned true but method has no @Executable definition. This should never happen. Please report an issue.")
                                            )));

            // Find ExecutableMethodProcessor for each annotation and process the BeanDefinitionMethodReference
            for (Map.Entry<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> entry : byAnnotation.entrySet()) {
                Class<? extends Annotation> annotationType = entry.getKey();
                streamOfType(ExecutableMethodProcessor.class, Qualifiers.byTypeArguments(annotationType))
                        .forEach(processor -> {
                            for (BeanDefinitionMethodReference<?, ?> method : entry.getValue()) {

                                BeanDefinition<?> beanDefinition = method.getBeanDefinition();

                                // Only process the method if the the annotation is not declared at the class level
                                // If declared at the class level it will already have been processed by AnnotationProcessorListener
                                if (!beanDefinition.hasStereotype(annotationType)) {
                                    //noinspection unchecked
                                    if (method.hasDeclaredStereotype(Parallel.class)) {
                                        ForkJoinPool.commonPool().execute(() -> {
                                            try {
                                                processor.process(beanDefinition, method);
                                            } catch (Throwable e) {
                                                if (LOG.isErrorEnabled()) {
                                                    LOG.error("Error processing bean method " + beanDefinition + "." + method + " with processor (" + processor + "): " + e.getMessage(), e);
                                                }
                                                Boolean shutdownOnError = method.getValue(Parallel.class, "shutdownOnError", Boolean.class).orElse(true);
                                                if (shutdownOnError) {
                                                    stop();
                                                }
                                            }
                                        });
                                    } else {
                                        processor.process(beanDefinition, method);
                                    }
                                }
                            }

                            if (processor instanceof Completable) {
                                ((Completable) processor).onComplete();
                            }

                        });
            }
        }

        final Runnable runnable = () ->
                beanDefinitionsClasses.removeIf((BeanDefinitionReference beanDefinitionReference) ->
                        !beanDefinitionReference.isEnabled(this));
        if (ClassLoadingReporter.isReportingEnabled()) {
            // do this in a blocking manner so that reporting is immediately aware of missing classes
            runnable.run();
        } else {
            // proactively remove bean definitions that are not enabled
            new Thread(runnable).start();
        }

    }
338052
public void init(HttpInboundServiceContext context) {
        this.message = context.getRequest();
        if (this.useEE7Streams) {
            this.body = new HttpInputStreamEE7(context);
        } else {
            this.body = new HttpInputStreamImpl(context);
        }
    }
914332
@Override
  public SparkAppHandle startApplication(SparkAppHandle.Listener... listeners) throws IOException {
    if (builder.isClientMode(builder.getEffectiveConfig())) {
      LOG.warning("It's not recommended to run client-mode applications using InProcessLauncher.");
    }

    Method main = findSparkSubmit();
    LauncherServer server = LauncherServer.getOrCreateServer();
    InProcessAppHandle handle = new InProcessAppHandle(server);
    for (SparkAppHandle.Listener l : listeners) {
      handle.addListener(l);
    }

    String secret = server.registerHandle(handle);
    setConf(LauncherProtocol.CONF_LAUNCHER_PORT, String.valueOf(server.getPort()));
    setConf(LauncherProtocol.CONF_LAUNCHER_SECRET, secret);

    List<String> sparkArgs = builder.buildSparkSubmitArgs();
    String[] argv = sparkArgs.toArray(new String[sparkArgs.size()]);

    String appName = CommandBuilderUtils.firstNonEmpty(builder.appName, builder.mainClass,
      "<unknown>");
    handle.start(appName, main, argv);
    return handle;
  }