use of org.wildfly.swarm.tools.BuildTool in project wildfly-swarm by wildfly-swarm.
the class UberjarSimpleContainer method start.
@Override
public void start(Archive<?> archive) throws Exception {
archive.add(EmptyAsset.INSTANCE, "META-INF/arquillian-testable");
ContextRoot contextRoot = null;
if (archive.getName().endsWith(".war")) {
contextRoot = new ContextRoot("/");
Node jbossWebNode = archive.as(WebArchive.class).get("WEB-INF/jboss-web.xml");
if (jbossWebNode != null) {
if (jbossWebNode.getAsset() != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(jbossWebNode.getAsset().openStream()))) {
String content = String.join("\n", reader.lines().collect(Collectors.toList()));
Pattern pattern = Pattern.compile("<context-root>(.+)</context-root>");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
contextRoot = new ContextRoot(matcher.group(1));
}
}
}
}
this.deploymentContext.getObjectStore().add(ContextRoot.class, contextRoot);
}
MainSpecifier mainSpecifier = containerContext.getObjectStore().get(MainSpecifier.class);
boolean annotatedCreateSwarm = false;
Method swarmMethod = getAnnotatedMethodWithAnnotation(this.testClass, CreateSwarm.class);
List<Class<?>> types = determineTypes(this.testClass);
// preflight check it
if (swarmMethod != null) {
if (Modifier.isStatic(swarmMethod.getModifiers())) {
// good to go
annotatedCreateSwarm = true;
types.add(CreateSwarm.class);
types.add(AnnotationBasedMain.class);
archive.as(JARArchive.class).addModule("org.wildfly.swarm.container");
archive.as(JARArchive.class).addModule("org.wildfly.swarm.configuration");
} else {
throw new IllegalArgumentException(String.format("Method annotated with %s is %s but it is not static", CreateSwarm.class.getSimpleName(), swarmMethod));
}
}
if (types.size() > 0) {
try {
((ClassContainer<?>) archive).addClasses(types.toArray(new Class[types.size()]));
} catch (UnsupportedOperationException e) {
// TODO Remove the try/catch when SHRINKWRAP-510 is resolved and we update to latest SW
archive.as(JARArchive.class).addClasses(types.toArray(new Class[types.size()]));
}
}
final ShrinkwrapArtifactResolvingHelper resolvingHelper = ShrinkwrapArtifactResolvingHelper.defaultInstance();
BuildTool tool = new BuildTool(resolvingHelper).fractionDetectionMode(BuildTool.FractionDetectionMode.when_missing).bundleDependencies(false);
String additionalModules = System.getProperty(SwarmInternalProperties.BUILD_MODULES);
// See https://issues.jboss.org/browse/SWARM-571
if (null == additionalModules) {
// see if we can find it
File modulesDir = new File("target/classes/modules");
additionalModules = modulesDir.exists() ? modulesDir.getAbsolutePath() : null;
}
if (additionalModules != null) {
tool.additionalModules(Stream.of(additionalModules.split(":")).map(File::new).filter(File::exists).map(File::getAbsolutePath).collect(Collectors.toList()));
}
final SwarmExecutor executor = new SwarmExecutor().withDefaultSystemProperties();
if (annotatedCreateSwarm) {
executor.withProperty(AnnotationBasedMain.ANNOTATED_CLASS_NAME, this.testClass.getName());
}
if (contextRoot != null) {
executor.withProperty(SwarmProperties.CONTEXT_PATH, contextRoot.context());
}
executor.withProperty("swarm.inhibit.auto-stop", "true");
String additionalRepos = System.getProperty(SwarmInternalProperties.BUILD_REPOS);
if (additionalRepos != null) {
additionalRepos = additionalRepos + ",";
} else {
additionalRepos = "";
}
additionalRepos = additionalRepos + "https://repository.jboss.org/nexus/content/groups/public/";
executor.withProperty("remote.maven.repo", additionalRepos);
// project dependencies
FileSystemLayout fsLayout = FileSystemLayout.create();
DeclaredDependencies declaredDependencies = DependencyDeclarationFactory.newInstance(fsLayout).create(fsLayout, resolvingHelper);
tool.declaredDependencies(declaredDependencies);
// see DependenciesContainer#addAllDependencies()
if (archive instanceof DependenciesContainer) {
DependenciesContainer<?> depContainer = (DependenciesContainer<?>) archive;
if (depContainer.hasMarker(DependenciesContainer.ALL_DEPENDENCIES_MARKER)) {
munge(depContainer, declaredDependencies);
}
} else if (archive instanceof WebArchive) {
// Handle the default deployment of type WAR
WebArchive webArchive = (WebArchive) archive;
if (MarkerContainer.hasMarker(webArchive, DependenciesContainer.ALL_DEPENDENCIES_MARKER)) {
munge(webArchive, declaredDependencies);
}
}
tool.projectArchive(archive);
final String debug = System.getProperty(SwarmProperties.DEBUG_PORT);
if (debug != null) {
try {
executor.withDebug(Integer.parseInt(debug));
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("Failed to parse %s of \"%s\"", SwarmProperties.DEBUG_PORT, debug), e);
}
}
if (mainSpecifier != null) {
tool.mainClass(mainSpecifier.getClassName());
String[] args = mainSpecifier.getArgs();
for (String arg : args) {
executor.withArgument(arg);
}
} else if (annotatedCreateSwarm) {
tool.mainClass(AnnotationBasedMain.class.getName());
} else {
Optional<String> mainClassName = Optional.empty();
Node node = archive.get("META-INF/arquillian-main-class");
if (node != null && node.getAsset() != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(node.getAsset().openStream()))) {
mainClassName = reader.lines().findFirst();
}
}
tool.mainClass(mainClassName.orElse(Swarm.class.getName()));
}
if (this.testClass != null) {
tool.testClass(this.testClass.getName());
}
Archive<?> wrapped = null;
try {
wrapped = tool.build();
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
if (BootstrapProperties.flagIsSet(SwarmInternalProperties.EXPORT_UBERJAR)) {
final File out = new File(wrapped.getName());
System.err.println("Exporting swarm jar to " + out.getAbsolutePath());
wrapped.as(ZipExporter.class).exportTo(out, true);
}
/* for (Map.Entry<ArchivePath, Node> each : wrapped.getContent().entrySet()) {
System.err.println("-> " + each.getKey());
}*/
File executable = File.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "arquillian", "-swarm.jar");
wrapped.as(ZipExporter.class).exportTo(executable, true);
executable.deleteOnExit();
String mavenRepoLocal = System.getProperty("maven.repo.local");
if (mavenRepoLocal != null) {
executor.withProperty("maven.repo.local", mavenRepoLocal);
}
executor.withProperty("java.net.preferIPv4Stack", "true");
File processFile = File.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "mainprocessfile", null);
executor.withProcessFile(processFile);
executor.withJVMArguments(getJavaVmArgumentsList());
executor.withExecutableJar(executable.toPath());
workingDirectory = TempFileManager.INSTANCE.newTempDirectory("arquillian", null);
executor.withWorkingDirectory(workingDirectory.toPath());
this.process = executor.execute();
this.process.getOutputStream().close();
this.process.awaitReadiness(2, TimeUnit.MINUTES);
if (!this.process.isAlive()) {
throw new DeploymentException("Process failed to start");
}
if (this.process.getError() != null) {
throw new DeploymentException("Error starting process", this.process.getError());
}
}
use of org.wildfly.swarm.tools.BuildTool in project wildfly-swarm by wildfly-swarm.
the class PackageMojo method executeSpecific.
@SuppressWarnings("deprecation")
@Override
public void executeSpecific() throws MojoExecutionException, MojoFailureException {
if (this.skip) {
getLog().info("Skipping packaging");
return;
}
if (this.project.getPackaging().equals("pom")) {
getLog().info("Not processing project with pom packaging");
return;
}
initProperties(false);
final Artifact primaryArtifact = this.project.getArtifact();
final String finalName = this.project.getBuild().getFinalName();
final String type = primaryArtifact.getType();
final File primaryArtifactFile = divineFile();
if (primaryArtifactFile == null) {
throw new MojoExecutionException("Cannot package without a primary artifact; please `mvn package` prior to invoking wildfly-swarm:package from the command-line");
}
final DeclaredDependencies declaredDependencies = new DeclaredDependencies();
final BuildTool tool = new BuildTool(mavenArtifactResolvingHelper()).projectArtifact(primaryArtifact.getGroupId(), primaryArtifact.getArtifactId(), primaryArtifact.getBaseVersion(), type, primaryArtifactFile, finalName.endsWith("." + type) ? finalName : String.format("%s.%s", finalName, type)).properties(this.properties).mainClass(this.mainClass).bundleDependencies(this.bundleDependencies).executable(executable).executableScript(executableScript).fractionDetectionMode(fractionDetectMode).hollow(hollow).logger(new SimpleLogger() {
@Override
public void debug(String msg) {
getLog().debug(msg);
}
@Override
public void info(String msg) {
getLog().info(msg);
}
@Override
public void error(String msg) {
getLog().error(msg);
}
@Override
public void error(String msg, Throwable t) {
getLog().error(msg, t);
}
});
this.additionalFractions.stream().map(f -> FractionDescriptor.fromGav(FractionList.get(), f)).map(ArtifactSpec::fromFractionDescriptor).forEach(tool::fraction);
Map<ArtifactSpec, Set<ArtifactSpec>> buckets = createBuckets(this.project.getArtifacts(), this.project.getDependencies());
for (ArtifactSpec directDep : buckets.keySet()) {
if (!(directDep.scope.equals("compile") || directDep.scope.equals("runtime"))) {
// ignore anything but compile and runtime
continue;
}
Set<ArtifactSpec> transientDeps = buckets.get(directDep);
if (transientDeps.isEmpty()) {
declaredDependencies.add(directDep);
} else {
for (ArtifactSpec transientDep : transientDeps) {
declaredDependencies.add(directDep, transientDep);
}
}
}
tool.declaredDependencies(declaredDependencies);
this.project.getResources().forEach(r -> tool.resourceDirectory(r.getDirectory()));
Path uberjarResourcesDir = null;
if (this.uberjarResources == null) {
uberjarResourcesDir = Paths.get(this.project.getBasedir().toString()).resolve("src").resolve("main").resolve("uberjar");
} else {
uberjarResourcesDir = Paths.get(this.uberjarResources);
}
tool.uberjarResourcesDirectory(uberjarResourcesDir);
this.additionalModules.stream().map(m -> new File(this.project.getBuild().getOutputDirectory(), m)).filter(File::exists).map(File::getAbsolutePath).forEach(tool::additionalModule);
try {
File jar = tool.build(finalName + (this.hollow ? "-hollow" : ""), Paths.get(this.projectBuildDir));
ArtifactHandler handler = new DefaultArtifactHandler("jar");
Artifact swarmJarArtifact = new DefaultArtifact(primaryArtifact.getGroupId(), primaryArtifact.getArtifactId(), primaryArtifact.getBaseVersion(), primaryArtifact.getScope(), "jar", (this.hollow ? "hollow" : "") + "swarm", handler);
swarmJarArtifact.setFile(jar);
this.project.addAttachedArtifact(swarmJarArtifact);
if (this.project.getPackaging().equals("war")) {
tool.repackageWar(primaryArtifactFile);
}
} catch (Exception e) {
throw new MojoFailureException("Unable to create -swarm.jar", e);
}
}
use of org.wildfly.swarm.tools.BuildTool in project wildfly-swarm by wildfly-swarm.
the class Main method generateSwarmJar.
protected static File generateSwarmJar(final String[] args) throws Exception {
OptionSet foundOptions = null;
try {
foundOptions = OPT_PARSER.parse(args);
} catch (OptionException e) {
exit(e.getMessage(), true);
}
if (foundOptions.has(HELP_OPT)) {
exit(null, 0, true);
}
if (foundOptions.has(VERSION_OPT)) {
exit("swarmtool v" + VERSION, 0);
}
final List<File> nonOptArgs = foundOptions.valuesOf(SOURCE_OPT);
if (nonOptArgs.isEmpty()) {
exit("No source artifact specified.", true);
}
if (nonOptArgs.size() > 1) {
exit("Too many source artifacts provided (" + nonOptArgs + ")", true);
}
final File source = nonOptArgs.get(0);
if (!source.exists()) {
exit("File " + source.getAbsolutePath() + " does not exist.");
}
final Properties properties = new Properties();
if (foundOptions.has(SYSPROPS_FILE_OPT)) {
try (InputStream in = new FileInputStream(foundOptions.valueOf(SYSPROPS_FILE_OPT))) {
properties.load(in);
}
}
foundOptions.valuesOf(SYSPROPS_OPT).forEach(prop -> {
final String[] parts = prop.split("=");
properties.put(parts[0], parts[1]);
});
final DeclaredDependencies dependencies = new DeclaredDependencies();
foundOptions.valuesOf(DEPENDENCIES_OPT).stream().map(DeclaredDependencies::createSpec).forEach(dependencies::add);
final String[] parts = source.getName().split("\\.(?=[^\\.]+$)");
final String baseName = parts[0];
final String type = parts[1] == null ? "jar" : parts[1];
final String jarName = foundOptions.has(NAME_OPT) ? foundOptions.valueOf(NAME_OPT) : baseName;
final String outDir = new File(foundOptions.valueOf(OUTPUT_DIR_OPT)).getCanonicalPath();
final String suffix = foundOptions.has(HOLLOW_OPT) ? "-hollow-swarm" : "-swarm";
final BuildTool tool = new BuildTool(getResolvingHelper(foundOptions.valuesOf(REPOS_OPT))).projectArtifact("", baseName, "", type, source).declaredDependencies(dependencies).fractionDetectionMode(foundOptions.has(DISABLE_AUTO_DETECT_OPT) ? BuildTool.FractionDetectionMode.never : BuildTool.FractionDetectionMode.force).bundleDependencies(!foundOptions.has(DISABLE_BUNDLE_DEPS_OPT)).executable(foundOptions.has(EXECUTABLE_OPT)).properties(properties).hollow(foundOptions.has(HOLLOW_OPT));
if (foundOptions.has(MAIN_OPT)) {
tool.mainClass(foundOptions.valueOf(MAIN_OPT));
}
if (foundOptions.has(MODULES_OPT)) {
tool.additionalModules(foundOptions.valuesOf(MODULES_OPT));
}
if (foundOptions.has(DEBUG_LOGGING)) {
tool.logger(BuildTool.STD_LOGGER_WITH_DEBUG);
}
addSwarmFractions(tool, foundOptions.valuesOf(FRACTIONS_OPT));
System.err.println(String.format("Building %s/%s%s.jar", outDir, jarName, suffix));
return tool.build(jarName, Paths.get(outDir));
}
use of org.wildfly.swarm.tools.BuildTool in project wildfly-swarm by wildfly-swarm.
the class PackageTask method packageForSwarm.
@TaskAction
public void packageForSwarm() throws Exception {
final Project project = getProject();
GradleArtifactResolvingHelper resolvingHelper = new GradleArtifactResolvingHelper(project);
Properties propertiesFromExtension = getPropertiesFromExtension();
List<File> moduleDirs = getModuleDirs();
if (moduleDirs.isEmpty()) {
Path resourcesOutputDir = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().findByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput().getResourcesDir().toPath().resolve(MODULE_DIR_NAME);
if (Files.isDirectory(resourcesOutputDir)) {
File moduleDir = resourcesOutputDir.toFile();
moduleDirs.add(moduleDir);
}
}
this.tool = new BuildTool(resolvingHelper).projectArtifact(this.jarTask.getGroup().toString(), this.jarTask.getBaseName(), this.jarTask.getVersion(), getPackaging(), getProjectArtifactFile()).mainClass(getMainClassName()).bundleDependencies(getBundleDependencies()).executable(getExecutable()).executableScript(getExecutableScript()).properties(propertiesFromExtension).properties(getPropertiesFromFile()).properties(PropertiesUtil.filteredSystemProperties(propertiesFromExtension, false)).fractionDetectionMode(getSwarmExtension().getFractionDetectMode()).hollow(getHollow()).additionalModules(moduleDirs.stream().filter(File::exists).map(File::getAbsolutePath).collect(Collectors.toList())).logger(new SimpleLogger() {
@Override
public void debug(String msg) {
getLogger().debug(msg);
}
@Override
public void info(String msg) {
getLogger().info(msg);
}
@Override
public void error(String msg) {
getLogger().error(msg);
}
@Override
public void error(String msg, Throwable t) {
getLogger().error(msg, t);
}
});
DeclaredDependencies declaredDependencies = new DeclaredDependencies();
List<ArtifactSpec> explicitDependencies = new ArrayList<>();
/* project.getConfigurations()
.getByName("compile")
.getAllDependencies()
.forEach((artifact) -> {
String groupId = artifact.getGroup();
String artifactId = artifact.getName();
explicitDependencies.add(new ArtifactSpec("compile", groupId, artifactId, null, "jar", null, null));
});
project.getConfigurations()
.getByName("compile")
.getResolvedConfiguration()
.getResolvedArtifacts()
.forEach(e -> addDependency(declaredDependencies, explicitDependencies, e));*/
ResolvedConfiguration resolvedConfiguration = project.getConfigurations().getByName("default").getResolvedConfiguration();
Set<ResolvedDependency> directDeps = resolvedConfiguration.getFirstLevelModuleDependencies();
for (ResolvedDependency directDep : directDeps) {
assert directDep.getModuleArtifacts().iterator().hasNext() : "Expected module artifacts";
ArtifactSpec parent = new ArtifactSpec("compile", directDep.getModule().getId().getGroup(), directDep.getModule().getId().getName(), directDep.getModule().getId().getVersion(), directDep.getModuleArtifacts().iterator().next().getExtension(), null, null);
Set<ArtifactSpec> artifactSpecs = resolvingHelper.resolveAll(new HashSet<>(Collections.singletonList(parent)));
artifactSpecs.forEach(a -> declaredDependencies.add(parent, a));
}
tool.declaredDependencies(declaredDependencies);
final Boolean bundleDependencies = getBundleDependencies();
if (bundleDependencies != null) {
this.tool.bundleDependencies(bundleDependencies);
}
this.tool.build(getBaseName(), getOutputDirectory());
}
Aggregations