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);
}
}
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;
}
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);
}
}
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);
}
}
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);
}
}
Aggregations