protected CamelContext createCamelContext()

in dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/KameletMain.java [428:728]


    protected CamelContext createCamelContext() {
        this.verbose = "true".equals(getInitialProperties().get(getInstanceType() + ".verbose"));

        // do not build/init camel context yet
        DefaultCamelContext answer = new DefaultCamelContext(false);
        // setup backlog recorder from very start
        answer.getCamelContextExtension().setStartupStepRecorder(new BacklogStartupStepRecorder());

        boolean export = "true".equals(getInitialProperties().get(getInstanceType() + ".export"));
        if (export) {
            setupExport(answer, export);
        } else {
            PropertiesComponent pc = (PropertiesComponent) answer.getPropertiesComponent();
            pc.setPropertiesFunctionResolver(new DependencyDownloaderPropertiesFunctionResolver(answer, false));
        }

        boolean prompt = "true".equals(getInitialProperties().get(getInstanceType() + ".prompt"));
        if (prompt) {
            answer.getPropertiesComponent().addPropertiesSource(new PromptPropertyPlaceholderSource());
        }

        ClassLoader dynamicCL = createApplicationContextClassLoader(answer);
        answer.setApplicationContextClassLoader(dynamicCL);
        PluginHelper.getPackageScanClassResolver(answer).addClassLoader(dynamicCL);
        PluginHelper.getPackageScanResourceResolver(answer).addClassLoader(dynamicCL);

        final MavenDependencyDownloader downloader = createMavenDependencyDownloader(dynamicCL, answer);

        // register as extension
        try {
            answer.addService(downloader);
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeException(e);
        }

        // in case we use circuit breakers
        CircuitBreakerDownloader.registerDownloadReifiers();

        // in case we use transacted
        TransactedDownloader.registerDownloadReifiers(this);

        // in case we use saga
        SagaDownloader.registerDownloadReifiers(this);

        // if transforming DSL then disable processors as we just want to work on the model (not runtime processors)
        boolean transform = "true".equals(getInitialProperties().get(getInstanceType() + ".transform"));
        if (transform) {
            // we just want to transform, so disable custom bean or processors as they may use code that does not work
            answer.getGlobalOptions().put(ProcessorReifier.DISABLE_BEAN_OR_PROCESS_PROCESSORS, "true");
            // stub everything
            this.stubPattern = "*";
            // turn off inlining routes
            configure().rest().withInlineRoutes(false);
            blueprintXmlBeansHandler.setTransform(true);
        }
        if (silent) {
            // silent should not include http server
            configure().httpServer().withEnabled(false);
        }

        if (silent || "*".equals(stubPattern)) {
            // turn off auto-wiring when running in silent mode (or stub = *)
            mainConfigurationProperties.setAutowiredEnabled(false);
            // and turn off fail fast as we stub components
            mainConfigurationProperties.setAutoConfigurationFailFast(false);
        }

        var infos = startupInfo();
        infos.forEach(LOG::info);

        answer.getCamelContextExtension().setRegistry(registry);
        if (silent || "*".equals(stubPattern)) {
            registry.addBeanRepository(new StubBeanRepository(stubPattern));
        }

        // load camel component and custom health-checks
        answer.setLoadHealthChecks(true);

        // annotation based dependency injection for camel/spring/quarkus annotations in DSLs and Java beans
        boolean lazyBean = "true".equals(getInitialProperties().get(getInstanceType() + ".lazyBean"));
        new AnnotationDependencyInjection(answer, lazyBean);

        if (!silent) {
            // silent should not include cli-connector
            // setup cli-connector if not already done
            if (answer.hasService(CliConnector.class) == null) {
                CliConnectorFactory ccf = answer.getCamelContextExtension().getContextPlugin(CliConnectorFactory.class);
                if (ccf != null && ccf.isEnabled()) {
                    CliConnector connector = ccf.createConnector();
                    try {
                        answer.addService(connector, true);
                        // force start cli connector early as otherwise it will be deferred until context is started
                        // but, we want status available during startup phase
                        ServiceHelper.startService(connector);
                    } catch (Exception e) {
                        LOG.warn("Cannot start camel-cli-connector due: {}. This integration cannot be managed by Camel CLI.",
                                e.getMessage());
                    }
                }
            }
        }
        configure().withProfile(profile);

        // embed HTTP server if port is specified
        Object port = getInitialProperties().get(getInstanceType() + ".platform-http.port");
        if (port != null) {
            configure().httpServer().withEnabled(true);
            configure().httpServer().withPort(Integer.parseInt(port.toString()));
        }
        boolean console = "true".equals(getInitialProperties().get(getInstanceType() + ".console"));
        if (console) {
            configure().setDevConsoleEnabled(true);
            configure().httpServer().withEnabled(true);
            configure().httpServer().withDevConsoleEnabled(true);
            // also include health,info and jolokia
            configure().httpServer().withHealthCheckEnabled(true);
            configure().httpServer().withInfoEnabled(true);
            configure().httpServer().withJolokiaEnabled(true);
        }
        boolean tracing = "true".equals(getInitialProperties().get(getInstanceType() + ".backlogTracing"));
        if (tracing) {
            configure().tracerConfig().withEnabled(true);
        }
        boolean infoConsole = "true".equals(getInitialProperties().get(getInstanceType() + ".info"));
        if (infoConsole) {
            configure().httpServer().withEnabled(true);
            configure().httpServer().withInfoEnabled(true);
        }
        // Deprecated: to be replaced by observe flag
        boolean health = "true".equals(getInitialProperties().get(getInstanceType() + ".health"));
        if (health) {
            configure().health().withEnabled(true);
            configure().httpServer().withEnabled(true);
            configure().httpServer().withHealthCheckEnabled(true);
        }
        // Deprecated: to be replaced by observe flag
        boolean metrics = "true".equals(getInitialProperties().get(getInstanceType() + ".metrics"));
        if (metrics) {
            configure().metrics()
                    .witheEnableRouteEventNotifier(true)
                    .withEnableMessageHistory(true)
                    .withEnableExchangeEventNotifier(true)
                    .withEnableRoutePolicy(true).withEnabled(true);
            configure().httpServer().withEnabled(true);
            configure().httpServer().withMetricsEnabled(true);
        }
        boolean ignoreLoading = "true".equals(getInitialProperties().get(getInstanceType() + ".ignoreLoadingError"));
        if (ignoreLoading) {
            configure().withRoutesCollectorIgnoreLoadingError(true);
            answer.getPropertiesComponent().setIgnoreMissingProperty(true);
            answer.getPropertiesComponent().setIgnoreMissingLocation(true);
        }

        // need to setup jfr early
        Object jfr = getInitialProperties().get(getInstanceType() + ".jfr");
        Object jfrProfile = getInitialProperties().get(getInstanceType() + ".jfr-profile");
        if ("jfr".equals(jfr) || jfrProfile != null) {
            FlightRecorderStartupStepRecorder recorder = new FlightRecorderStartupStepRecorder();
            recorder.setRecording(true);
            if (jfrProfile != null) {
                recorder.setRecordingProfile(jfrProfile.toString());
            }
            answer.getCamelContextExtension().setStartupStepRecorder(recorder);
        }

        // special for source compilation to a specific package based on Maven GAV
        String gav = getInitialProperties().getProperty(getInstanceType() + ".gav");
        if (gav != null) {
            MavenGav g = MavenGav.parseGav(gav);
            if (g.getGroupId() != null && g.getArtifactId() != null) {
                // plugin a custom source loader with package name based on GAV
                String defaultPackageName = g.getGroupId().replace('-', '.') + "." + g.getArtifactId().replace('-', '.');
                SourceLoader sl = new PackageNameSourceLoader(defaultPackageName);
                answer.getRegistry().bind("PackageNameSourceLoader", sl);
            }
        }

        // source-dir
        String sourceDir = getInitialProperties().getProperty(getInstanceType() + ".sourceDir");

        try {
            // dependencies from CLI
            Object dependencies = getInitialProperties().get(getInstanceType() + ".dependencies");
            if (dependencies != null) {
                answer.addService(new CommandLineDependencyDownloader(answer, dependencies.toString()));
            }

            String springBootVersion = (String) getInitialProperties().get(getInstanceType() + ".springBootVersion");
            String quarkusVersion = (String) getInitialProperties().get(getInstanceType() + ".quarkusVersion");

            KnownDependenciesResolver knownDeps = new KnownDependenciesResolver(answer, springBootVersion, quarkusVersion);
            knownDeps.loadKnownDependencies();
            DependencyDownloaderPropertyBindingListener listener
                    = new DependencyDownloaderPropertyBindingListener(answer, knownDeps);
            answer.getCamelContextExtension().getRegistry()
                    .bind(DependencyDownloaderPropertyBindingListener.class.getSimpleName(), listener);
            answer.getCamelContextExtension().getRegistry().bind(DependencyDownloaderStrategy.class.getSimpleName(),
                    new DependencyDownloaderStrategy(answer));
            // add support for automatic downloaded needed JARs from java imports
            new JavaKnownImportsDownloader(answer, knownDeps);

            // download class-resolver
            ClassResolver classResolver = new DependencyDownloaderClassResolver(answer, knownDeps, silent);
            answer.setClassResolver(classResolver);
            // re-create factory finder with download class-resolver
            FactoryFinderResolver ffr = PluginHelper.getFactoryFinderResolver(answer);
            FactoryFinder ff = ffr.resolveBootstrapFactoryFinder(classResolver);
            answer.getCamelContextExtension().setBootstrapFactoryFinder(ff);
            ff = ffr.resolveDefaultFactoryFinder(classResolver);
            answer.getCamelContextExtension().setDefaultFactoryFinder(ff);

            // period task resolver that can download needed dependencies
            Object camelVersion = getInitialProperties().get(getInstanceType() + ".camelVersion");
            PeriodTaskResolver ptr = new DependencyDownloaderPeriodTaskResolver(
                    ff, answer, Optional.ofNullable(camelVersion).map(Object::toString).orElse(null), export);
            answer.getCamelContextExtension().addContextPlugin(PeriodTaskResolver.class, ptr);

            answer.getCamelContextExtension().registerEndpointCallback(new DownloadEndpointStrategy(answer, silent));
            answer.getCamelContextExtension().addContextPlugin(ComponentResolver.class,
                    new DependencyDownloaderComponentResolver(answer, stubPattern, silent, transform));
            answer.getCamelContextExtension().addContextPlugin(DataFormatResolver.class,
                    new DependencyDownloaderDataFormatResolver(answer, stubPattern, silent));
            answer.getCamelContextExtension().addContextPlugin(LanguageResolver.class,
                    new DependencyDownloaderLanguageResolver(answer, stubPattern, silent));
            answer.getCamelContextExtension().addContextPlugin(TransformerResolver.class,
                    new DependencyDownloaderTransformerResolver(answer, stubPattern, silent));
            answer.getCamelContextExtension().addContextPlugin(UriFactoryResolver.class,
                    new DependencyDownloaderUriFactoryResolver(answer));
            answer.getCamelContextExtension().addContextPlugin(ResourceLoader.class,
                    new DependencyDownloaderResourceLoader(answer, sourceDir));

            if (stubPattern != null) {
                // need to replace autowire strategy with stub capable
                answer.getLifecycleStrategies()
                        .removeIf(s -> s.getClass().getSimpleName().equals("DefaultAutowiredLifecycleStrategy"));
                answer.getLifecycleStrategies().add(new StubComponentAutowireStrategy(answer, stubPattern));
            }
            answer.setInjector(new KameletMainInjector(answer.getInjector(), stubPattern, silent));
            Object kameletsVersion = getInitialProperties().get(getInstanceType() + ".kameletsVersion");
            if (kameletsVersion != null) {
                answer.addService(new DependencyDownloaderKamelet(answer, kameletsVersion.toString()));
            } else {
                answer.addService(new DependencyDownloaderKamelet(answer));
            }
            answer.getCamelContextExtension().getRegistry().bind(DownloadModelineParser.class.getSimpleName(),
                    new DownloadModelineParser(answer));

            answer.addService(new DependencyDownloaderPropertiesComponent(answer, knownDeps, silent));

            // reloader
            if (sourceDir != null) {
                configure().httpServer().withStaticSourceDir(sourceDir);
                configure().httpServer().withUploadSourceDir(sourceDir);

                if (console || health) {
                    // allow to upload/download source (source-dir is intended to be dynamic) via http when HTTP console enabled
                    configure().httpServer().withEnabled(true);
                    configure().httpServer().withUploadEnabled(true);
                    configure().httpServer().withDownloadEnabled(true);
                }
                RouteOnDemandReloadStrategy reloader = new RouteOnDemandReloadStrategy(sourceDir, true);
                reloader.setPattern("*");
                answer.addService(reloader);

                // add source-dir as location for loading kamelets (if not already included)
                String loc = this.initialProperties.getProperty("camel.component.kamelet.location");
                String target = "file:" + sourceDir + ",";
                if (!loc.contains(target)) {
                    loc = target + loc;
                    addInitialProperty("camel.component.kamelet.location", loc);
                }
            } else {
                answer.addService(new DefaultContextReloadStrategy());
            }

            // special for reloading enabled on clipboard
            String reloadDir = getInitialProperties().getProperty("camel.main.routesIncludePattern");
            if (reloadDir != null && reloadDir.startsWith("file:.camel-jbang/generated-clipboard")) {
                String name = reloadDir.substring(5);
                File file = new File(name);
                ClipboardReloadStrategy reloader = new ClipboardReloadStrategy(file);
                answer.addService(reloader);
                PeriodTaskScheduler scheduler = PluginHelper.getPeriodTaskScheduler(answer);
                scheduler.schedulePeriodTask(reloader, 2000);
            }

            // reload with openapi
            String openapi = getInitialProperties().getProperty(getInstanceType() + ".open-api");
            String reload = getInitialProperties().getProperty("camel.main.routesReloadDirectory");
            if (openapi != null && (reload != null || sourceDir != null)) {
                // add open-api reloader that generate output to .camel-jbang/generated-openapi.yaml
                File file = Paths.get(openapi).toFile();
                OpenApiGeneratorReloadStrategy rs = new OpenApiGeneratorReloadStrategy(file);
                answer.addService(rs);
            }
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeException(e);
        }

        return answer;
    }