Search in sources :

Example 11 with CuratedApplication

use of io.quarkus.bootstrap.app.CuratedApplication in project quarkus-platform by quarkusio.

the class GenerateCodeMojo method generateCode.

void generateCode(Path sourcesDir, Consumer<Path> sourceRegistrar, boolean test) throws MojoFailureException, MojoExecutionException {
    final LaunchMode launchMode = test ? LaunchMode.TEST : LaunchMode.valueOf(mode);
    if (getLog().isDebugEnabled()) {
        getLog().debug("Bootstrapping Quarkus application in mode " + launchMode);
    }
    ClassLoader originalTccl = Thread.currentThread().getContextClassLoader();
    CuratedApplication curatedApplication = null;
    try {
        curatedApplication = bootstrapApplication(launchMode);
        QuarkusClassLoader deploymentClassLoader = curatedApplication.createDeploymentClassLoader();
        Thread.currentThread().setContextClassLoader(deploymentClassLoader);
        final Class<?> codeGenerator = deploymentClassLoader.loadClass("io.quarkus.deployment.CodeGenerator");
        final Method initAndRun = codeGenerator.getMethod("initAndRun", ClassLoader.class, PathCollection.class, Path.class, Path.class, Consumer.class, ApplicationModel.class, Properties.class, String.class, boolean.class);
        initAndRun.invoke(null, deploymentClassLoader, PathList.of(sourcesDir), generatedSourcesDir(test), buildDir().toPath(), sourceRegistrar, curatedApplication.getApplicationModel(), mavenProject().getProperties(), launchMode.name(), test);
    } catch (Exception any) {
        throw new MojoExecutionException("Quarkus code generation phase has failed", any);
    } finally {
        // in case of test mode, we can't share the bootstrapped app with the testing plugins, so we are closing it right away
        if (test && curatedApplication != null) {
            curatedApplication.close();
        }
        Thread.currentThread().setContextClassLoader(originalTccl);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) CuratedApplication(io.quarkus.bootstrap.app.CuratedApplication) LaunchMode(io.quarkus.runtime.LaunchMode) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) Method(java.lang.reflect.Method) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 12 with CuratedApplication

use of io.quarkus.bootstrap.app.CuratedApplication in project quarkus-test-framework by quarkus-qe.

the class ProdQuarkusApplicationManagedResourceBuilder method buildArtifact.

private Path buildArtifact() {
    try {
        createSnapshotOfBuildProperties();
        Path appFolder = getApplicationFolder();
        JavaArchive javaArchive = ShrinkWrap.create(JavaArchive.class).addClasses(getAppClasses());
        javaArchive.as(ExplodedExporter.class).exportExplodedInto(appFolder.toFile());
        Path testLocation = PathTestHelper.getTestClassesLocation(getContext().getTestContext().getRequiredTestClass());
        QuarkusBootstrap.Builder builder = QuarkusBootstrap.builder().setApplicationRoot(appFolder).setMode(QuarkusBootstrap.Mode.PROD).addExcludedPath(testLocation).setIsolateDeployment(true).setProjectRoot(testLocation).setBaseName(getContext().getName()).setTargetDirectory(appFolder);
        if (!getForcedDependencies().isEmpty()) {
            // The method setForcedDependencies signature changed from `List<AppDependency>` to `List<Dependency>` where
            // Dependency is an interface of AppDependency, so it should be fine. However, the compiler fails to cast it,
            // so we need to use reflection to sort it out for the most recent version and older versions.
            ReflectionUtils.invokeMethod(builder, "setForcedDependencies", getForcedDependencies());
        }
        // The method `setLocalProjectDiscovery` signature changed from `Boolean` to `boolean` and this might make
        // to fail the tests at runtime when using different versions.
        // In order to workaround this, we need to invoke this method at runtime to let JVM unbox the arguments properly.
        // Note that this is happening because we want to support both 2.x and 1.13.x Quarkus versions.
        // Another strategy could be to have our own version of Quarkus bootstrap.
        ReflectionUtils.invokeMethod(builder, "setLocalProjectDiscovery", true);
        AugmentResult result;
        try (CuratedApplication curatedApplication = builder.build().bootstrap()) {
            AugmentAction action = curatedApplication.createAugmentor();
            result = action.createProductionApplication();
        }
        return Optional.ofNullable(result.getNativeResult()).orElseGet(() -> result.getJar().getPath());
    } catch (Exception ex) {
        fail("Failed to build Quarkus artifacts. Caused by " + ex);
    }
    return null;
}
Also used : Path(java.nio.file.Path) AugmentAction(io.quarkus.bootstrap.app.AugmentAction) CuratedApplication(io.quarkus.bootstrap.app.CuratedApplication) QuarkusBootstrap(io.quarkus.bootstrap.app.QuarkusBootstrap) AugmentResult(io.quarkus.bootstrap.app.AugmentResult) ExplodedExporter(org.jboss.shrinkwrap.api.exporter.ExplodedExporter) JavaArchive(org.jboss.shrinkwrap.api.spec.JavaArchive)

Example 13 with CuratedApplication

use of io.quarkus.bootstrap.app.CuratedApplication in project quarkus by quarkusio.

the class BuildMojo method doExecute.

@Override
protected void doExecute() throws MojoExecutionException {
    try {
        Set<String> propertiesToClear = new HashSet<>();
        // if and only if they are not already set.
        for (Map.Entry<String, String> entry : systemProperties.entrySet()) {
            String key = entry.getKey();
            if (System.getProperty(key) == null) {
                System.setProperty(key, entry.getValue());
                propertiesToClear.add(key);
            }
        }
        // they execute "mvn package -Dnative" even if quarkus.package.type has been set in application.properties
        if (!System.getProperties().containsKey(PACKAGE_TYPE_PROP) && isNativeProfileEnabled(mavenProject())) {
            Object packageTypeProp = mavenProject().getProperties().get(PACKAGE_TYPE_PROP);
            String packageType = NATIVE_PACKAGE_TYPE;
            if (packageTypeProp != null) {
                packageType = packageTypeProp.toString();
            }
            System.setProperty(PACKAGE_TYPE_PROP, packageType);
            propertiesToClear.add(PACKAGE_TYPE_PROP);
        }
        if (!propertiesToClear.isEmpty() && mavenSession().getRequest().getDegreeOfConcurrency() > 1) {
            getLog().warn("*****************************************************************");
            getLog().warn("* Your build is requesting parallel execution, but the project  *");
            getLog().warn("* relies on System properties at build time which could cause   *");
            getLog().warn("* race condition issues thus unpredictable build results.       *");
            getLog().warn("* Please avoid using System properties or avoid enabling        *");
            getLog().warn("* parallel execution                                            *");
            getLog().warn("*****************************************************************");
        }
        try (CuratedApplication curatedApplication = bootstrapApplication()) {
            AugmentAction action = curatedApplication.createAugmentor();
            AugmentResult result = action.createProductionApplication();
            Artifact original = mavenProject().getArtifact();
            if (result.getJar() != null) {
                if (!skipOriginalJarRename && result.getJar().isUberJar() && result.getJar().getOriginalArtifact() != null) {
                    final Path standardJar = result.getJar().getOriginalArtifact();
                    if (Files.exists(standardJar)) {
                        final Path renamedOriginal = standardJar.getParent().toAbsolutePath().resolve(standardJar.getFileName() + ".original");
                        try {
                            IoUtils.recursiveDelete(renamedOriginal);
                            Files.move(standardJar, renamedOriginal);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                        original.setFile(result.getJar().getOriginalArtifact().toFile());
                    }
                }
                if (result.getJar().isUberJar()) {
                    projectHelper.attachArtifact(mavenProject(), result.getJar().getPath().toFile(), result.getJar().getClassifier());
                }
            }
        } finally {
            // Clear all the system properties set by the plugin
            propertiesToClear.forEach(System::clearProperty);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to build quarkus application", e);
    }
}
Also used : Path(java.nio.file.Path) AugmentAction(io.quarkus.bootstrap.app.AugmentAction) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) AugmentResult(io.quarkus.bootstrap.app.AugmentResult) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Artifact(org.apache.maven.artifact.Artifact) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) UncheckedIOException(java.io.UncheckedIOException) CuratedApplication(io.quarkus.bootstrap.app.CuratedApplication) Map(java.util.Map) HashSet(java.util.HashSet)

Example 14 with CuratedApplication

use of io.quarkus.bootstrap.app.CuratedApplication in project quarkus by quarkusio.

the class JBangAugmentorImpl method accept.

@Override
public void accept(CuratedApplication curatedApplication, Map<String, Object> resultMap) {
    QuarkusClassLoader classLoader = curatedApplication.getAugmentClassLoader();
    QuarkusBootstrap quarkusBootstrap = curatedApplication.getQuarkusBootstrap();
    QuarkusAugmentor.Builder builder = QuarkusAugmentor.builder().setRoot(quarkusBootstrap.getApplicationRoot()).setClassLoader(classLoader).addFinal(ApplicationClassNameBuildItem.class).setTargetDir(quarkusBootstrap.getTargetDirectory()).setDeploymentClassLoader(curatedApplication.createDeploymentClassLoader()).setBuildSystemProperties(quarkusBootstrap.getBuildSystemProperties()).setEffectiveModel(curatedApplication.getApplicationModel());
    if (quarkusBootstrap.getBaseName() != null) {
        builder.setBaseName(quarkusBootstrap.getBaseName());
    }
    boolean auxiliaryApplication = curatedApplication.getQuarkusBootstrap().isAuxiliaryApplication();
    builder.setAuxiliaryApplication(auxiliaryApplication);
    builder.setAuxiliaryDevModeType(curatedApplication.getQuarkusBootstrap().isHostApplicationIsTestOnly() ? DevModeType.TEST_ONLY : (auxiliaryApplication ? DevModeType.LOCAL : null));
    builder.setLaunchMode(LaunchMode.NORMAL);
    builder.setRebuild(quarkusBootstrap.isRebuild());
    builder.setLiveReloadState(new LiveReloadBuildItem(false, Collections.emptySet(), new HashMap<>(), null));
    for (AdditionalDependency i : quarkusBootstrap.getAdditionalApplicationArchives()) {
        // if it is forced as an app archive
        if (i.isForceApplicationArchive()) {
            builder.addAdditionalApplicationArchive(i.getResolvedPaths());
        }
    }
    builder.addBuildChainCustomizer(new Consumer<BuildChainBuilder>() {

        @Override
        public void accept(BuildChainBuilder builder) {
            final BuildStepBuilder stepBuilder = builder.addBuildStep((ctx) -> {
                ctx.produce(new ProcessInheritIODisabledBuildItem());
            });
            stepBuilder.produces(ProcessInheritIODisabledBuildItem.class).build();
        }
    });
    builder.excludeFromIndexing(quarkusBootstrap.getExcludeFromClassPath());
    builder.addFinal(GeneratedClassBuildItem.class);
    builder.addFinal(MainClassBuildItem.class);
    builder.addFinal(GeneratedResourceBuildItem.class);
    builder.addFinal(TransformedClassesBuildItem.class);
    builder.addFinal(DeploymentResultBuildItem.class);
    boolean nativeRequested = "native".equals(System.getProperty("quarkus.package.type"));
    boolean containerBuildRequested = Boolean.getBoolean("quarkus.container-image.build");
    if (nativeRequested) {
        builder.addFinal(NativeImageBuildItem.class);
    }
    if (containerBuildRequested) {
        // TODO: this is a bit ugly
        // we don't nessesarily need these artifacts
        // but if we include them it does mean that you can auto create docker images
        // and deploy to kube etc
        // for an ordinary build with no native and no docker this is a waste
        builder.addFinal(ArtifactResultBuildItem.class);
    }
    try {
        BuildResult buildResult = builder.build().run();
        Map<String, byte[]> result = new HashMap<>();
        for (GeneratedClassBuildItem i : buildResult.consumeMulti(GeneratedClassBuildItem.class)) {
            result.put(i.getName().replace(".", "/") + ".class", i.getClassData());
        }
        for (GeneratedResourceBuildItem i : buildResult.consumeMulti(GeneratedResourceBuildItem.class)) {
            result.put(i.getName(), i.getClassData());
        }
        for (Map.Entry<Path, Set<TransformedClassesBuildItem.TransformedClass>> entry : buildResult.consume(TransformedClassesBuildItem.class).getTransformedClassesByJar().entrySet()) {
            for (TransformedClassesBuildItem.TransformedClass transformed : entry.getValue()) {
                if (transformed.getData() != null) {
                    result.put(transformed.getFileName(), transformed.getData());
                } else {
                    log.warn("Unable to remove resource " + transformed.getFileName() + " as this is not supported in JBangf");
                }
            }
        }
        resultMap.put("files", result);
        final List<String> javaargs = new ArrayList<>();
        javaargs.add("-Djava.util.logging.manager=org.jboss.logmanager.LogManager");
        javaargs.add("-Djava.util.concurrent.ForkJoinPool.common.threadFactory=io.quarkus.bootstrap.forkjoin.QuarkusForkJoinWorkerThreadFactory");
        resultMap.put("java-args", javaargs);
        resultMap.put("main-class", buildResult.consume(MainClassBuildItem.class).getClassName());
        if (nativeRequested) {
            resultMap.put("native-image", buildResult.consume(NativeImageBuildItem.class).getPath());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : TransformedClassesBuildItem(io.quarkus.deployment.builditem.TransformedClassesBuildItem) CuratedApplication(io.quarkus.bootstrap.app.CuratedApplication) BuildResult(io.quarkus.builder.BuildResult) DevModeType(io.quarkus.dev.spi.DevModeType) Logger(org.jboss.logging.Logger) BuildStepBuilder(io.quarkus.builder.BuildStepBuilder) LaunchMode(io.quarkus.runtime.LaunchMode) HashMap(java.util.HashMap) AdditionalDependency(io.quarkus.bootstrap.app.AdditionalDependency) ArrayList(java.util.ArrayList) QuarkusAugmentor(io.quarkus.deployment.QuarkusAugmentor) BuildChainBuilder(io.quarkus.builder.BuildChainBuilder) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Path(java.nio.file.Path) DeploymentResultBuildItem(io.quarkus.deployment.pkg.builditem.DeploymentResultBuildItem) GeneratedResourceBuildItem(io.quarkus.deployment.builditem.GeneratedResourceBuildItem) ProcessInheritIODisabledBuildItem(io.quarkus.deployment.pkg.builditem.ProcessInheritIODisabledBuildItem) NativeImageBuildItem(io.quarkus.deployment.pkg.builditem.NativeImageBuildItem) ApplicationClassNameBuildItem(io.quarkus.deployment.builditem.ApplicationClassNameBuildItem) Set(java.util.Set) ArtifactResultBuildItem(io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) Consumer(java.util.function.Consumer) List(java.util.List) QuarkusBootstrap(io.quarkus.bootstrap.app.QuarkusBootstrap) GeneratedClassBuildItem(io.quarkus.deployment.builditem.GeneratedClassBuildItem) Collections(java.util.Collections) LiveReloadBuildItem(io.quarkus.deployment.builditem.LiveReloadBuildItem) MainClassBuildItem(io.quarkus.deployment.builditem.MainClassBuildItem) LiveReloadBuildItem(io.quarkus.deployment.builditem.LiveReloadBuildItem) Set(java.util.Set) ProcessInheritIODisabledBuildItem(io.quarkus.deployment.pkg.builditem.ProcessInheritIODisabledBuildItem) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GeneratedClassBuildItem(io.quarkus.deployment.builditem.GeneratedClassBuildItem) AdditionalDependency(io.quarkus.bootstrap.app.AdditionalDependency) Path(java.nio.file.Path) QuarkusAugmentor(io.quarkus.deployment.QuarkusAugmentor) GeneratedResourceBuildItem(io.quarkus.deployment.builditem.GeneratedResourceBuildItem) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) TransformedClassesBuildItem(io.quarkus.deployment.builditem.TransformedClassesBuildItem) BuildResult(io.quarkus.builder.BuildResult) BuildStepBuilder(io.quarkus.builder.BuildStepBuilder) BuildChainBuilder(io.quarkus.builder.BuildChainBuilder) QuarkusBootstrap(io.quarkus.bootstrap.app.QuarkusBootstrap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 15 with CuratedApplication

use of io.quarkus.bootstrap.app.CuratedApplication in project quarkus by quarkusio.

the class QuarkusGenerateCode method prepareQuarkus.

@TaskAction
public void prepareQuarkus() {
    LaunchMode launchMode = test ? LaunchMode.TEST : devMode ? LaunchMode.DEVELOPMENT : LaunchMode.NORMAL;
    final ApplicationModel appModel = extension().getApplicationModel(launchMode);
    final Properties realProperties = getBuildSystemProperties(appModel.getAppArtifact());
    Path buildDir = getProject().getBuildDir().toPath();
    try (CuratedApplication appCreationContext = QuarkusBootstrap.builder().setBaseClassLoader(getClass().getClassLoader()).setExistingModel(appModel).setTargetDirectory(buildDir).setBaseName(extension().finalName()).setBuildSystemProperties(realProperties).setAppArtifact(appModel.getAppArtifact()).setLocalProjectDiscovery(false).setIsolateDeployment(true).build().bootstrap()) {
        final JavaPluginConvention javaConvention = getProject().getConvention().findPlugin(JavaPluginConvention.class);
        if (javaConvention != null) {
            final String generateSourcesDir = test ? QUARKUS_TEST_GENERATED_SOURCES : QUARKUS_GENERATED_SOURCES;
            final SourceSet generatedSources = javaConvention.getSourceSets().findByName(generateSourcesDir);
            List<Path> paths = new ArrayList<>();
            generatedSources.getOutput().filter(f -> f.getName().equals(generateSourcesDir)).forEach(f -> paths.add(f.toPath()));
            if (paths.isEmpty()) {
                throw new GradleException("Failed to create quarkus-generated-sources");
            }
            getLogger().debug("Will trigger preparing sources for source directory: {} buildDir: {}", sourcesDirectories, getProject().getBuildDir().getAbsolutePath());
            QuarkusClassLoader deploymentClassLoader = appCreationContext.createDeploymentClassLoader();
            Class<?> codeGenerator = deploymentClassLoader.loadClass(CodeGenerator.class.getName());
            Optional<Method> initAndRun = Arrays.stream(codeGenerator.getMethods()).filter(m -> m.getName().equals(INIT_AND_RUN)).findAny();
            if (initAndRun.isEmpty()) {
                throw new GradleException("Failed to find " + INIT_AND_RUN + " method in " + CodeGenerator.class.getName());
            }
            initAndRun.get().invoke(null, deploymentClassLoader, PathList.from(sourcesDirectories), paths.get(0), buildDir, sourceRegistrar, appCreationContext.getApplicationModel(), realProperties, launchMode.name(), test);
        }
    } catch (BootstrapException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
        throw new GradleException("Failed to generate sources in the QuarkusPrepare task", e);
    }
}
Also used : Path(java.nio.file.Path) CuratedApplication(io.quarkus.bootstrap.app.CuratedApplication) Arrays(java.util.Arrays) PathList(io.quarkus.paths.PathList) LaunchMode(io.quarkus.runtime.LaunchMode) InputFiles(org.gradle.api.tasks.InputFiles) OutputDirectory(org.gradle.api.tasks.OutputDirectory) ArrayList(java.util.ArrayList) SourceSet(org.gradle.api.tasks.SourceSet) HashSet(java.util.HashSet) Configuration(org.gradle.api.artifacts.Configuration) TaskAction(org.gradle.api.tasks.TaskAction) Method(java.lang.reflect.Method) Path(java.nio.file.Path) Properties(java.util.Properties) CompileClasspath(org.gradle.api.tasks.CompileClasspath) Files(java.nio.file.Files) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) BootstrapException(io.quarkus.bootstrap.BootstrapException) Set(java.util.Set) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException) Consumer(java.util.function.Consumer) List(java.util.List) QuarkusBootstrap(io.quarkus.bootstrap.app.QuarkusBootstrap) ApplicationModel(io.quarkus.bootstrap.model.ApplicationModel) GradleException(org.gradle.api.GradleException) CodeGenerator(io.quarkus.deployment.CodeGenerator) Optional(java.util.Optional) ArrayList(java.util.ArrayList) ApplicationModel(io.quarkus.bootstrap.model.ApplicationModel) CodeGenerator(io.quarkus.deployment.CodeGenerator) Method(java.lang.reflect.Method) Properties(java.util.Properties) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) InvocationTargetException(java.lang.reflect.InvocationTargetException) SourceSet(org.gradle.api.tasks.SourceSet) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) CuratedApplication(io.quarkus.bootstrap.app.CuratedApplication) LaunchMode(io.quarkus.runtime.LaunchMode) GradleException(org.gradle.api.GradleException) BootstrapException(io.quarkus.bootstrap.BootstrapException) TaskAction(org.gradle.api.tasks.TaskAction)

Aggregations

CuratedApplication (io.quarkus.bootstrap.app.CuratedApplication)19 Path (java.nio.file.Path)14 QuarkusBootstrap (io.quarkus.bootstrap.app.QuarkusBootstrap)11 IOException (java.io.IOException)9 AugmentAction (io.quarkus.bootstrap.app.AugmentAction)8 ApplicationModel (io.quarkus.bootstrap.model.ApplicationModel)8 ArrayList (java.util.ArrayList)8 Map (java.util.Map)7 HashMap (java.util.HashMap)6 AugmentResult (io.quarkus.bootstrap.app.AugmentResult)5 QuarkusClassLoader (io.quarkus.bootstrap.classloading.QuarkusClassLoader)5 LaunchMode (io.quarkus.runtime.LaunchMode)5 HashSet (java.util.HashSet)5 List (java.util.List)5 Properties (java.util.Properties)5 AdditionalDependency (io.quarkus.bootstrap.app.AdditionalDependency)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Closeable (java.io.Closeable)4 ObjectInputStream (java.io.ObjectInputStream)4 Files (java.nio.file.Files)4