added osgi-app plugin

This commit is contained in:
2021-10-30 19:29:37 +02:00
parent a39f2c21fb
commit 64ca4940c6
42 changed files with 1498 additions and 1138 deletions

66
osgi-app/build.gradle Normal file
View File

@@ -0,0 +1,66 @@
plugins {
id "java-gradle-plugin"
}
version = "0.1"
childProjects.forEach {name, child ->
child.with {
apply plugin: 'maven-publish'
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
publishing {
repositories {
maven {
url = woggioniMavenRepositoryUrl
}
}
publications {
maven(MavenPublication) {
from(components["java"])
}
}
}
}
}
evaluationDependsOnChildren()
configurations {
embedded {
transitive = false
visible = false
canBeConsumed = false
}
}
dependencies {
embedded project(path: "osgi-simple-bootstrapper", configuration: 'tar')
embedded project(path: "osgi-simple-bootstrapper-api")
embedded project(path: "osgi-simple-bootstrapper-application")
implementation group: 'biz.aQute.bnd', name: 'biz.aQute.bnd.gradle', version: getProperty('version.bnd')
implementation group: 'biz.aQute.bnd', name: 'biz.aQute.bndlib', version: getProperty('version.bnd')
['annotationProcessor', 'testCompileOnly', 'testAnnotationProcessor'].each { conf ->
add(conf, [group: "org.projectlombok", name: "lombok", version: getProperty('version.lombok')])
}
}
jar {
into("META-INF") {
from(configurations.embedded)
}
}
gradlePlugin {
plugins {
osgiAppPlugin {
id = 'net.woggioni.gradle.osgi-app'
implementationClass = 'net.woggioni.gradle.osgi.app.OsgiAppPlugin'
}
}
}

View File

@@ -0,0 +1,11 @@
plugins {
id 'java-library'
}
group = "net.woggioni.osgi"
version = "0.1"
dependencies {
compileOnly group: 'org.osgi', name: 'osgi.annotation', version: getProperty('version.osgi')
compileOnly group: 'org.osgi', name: 'osgi.core', version: getProperty('version.osgi')
}

View File

@@ -0,0 +1,5 @@
package net.woggioni.osgi.simple.bootstrapper.api;
public interface Application {
int run(String[] args);
}

View File

@@ -0,0 +1,7 @@
package net.woggioni.osgi.simple.bootstrapper.api;
public interface FrameworkService {
String getMainApplicationComponentName();
String[] getArgs();
void setExitCode(int exitCode);
}

View File

@@ -0,0 +1,4 @@
@Export
package net.woggioni.osgi.simple.bootstrapper.api;
import org.osgi.annotation.bundle.Export;

View File

@@ -0,0 +1,28 @@
plugins {
id 'java-library'
id 'biz.aQute.bnd.builder'
}
group = "net.woggioni.osgi"
version = "0.1"
dependencies {
compileOnly group: 'org.osgi', name: 'osgi.annotation', version: getProperty('version.osgi')
compileOnly group: 'org.osgi', name: 'osgi.core', version: getProperty('version.osgi')
compileOnly group: 'org.osgi', name: 'osgi.cmpn', version: getProperty('version.osgi')
compileOnly group: 'org.osgi',
name: 'org.osgi.service.component.annotations',
version: getProperty('version.osgi.service.component')
compileOnly project(":osgi-app:osgi-simple-bootstrapper-api")
runtimeOnly group: 'org.apache.felix', name: 'org.apache.felix.scr', version: getProperty('version.felix.scr')
runtimeOnly group: 'org.osgi', name: 'org.osgi.util.function', version: getProperty('version.osgi.function')
runtimeOnly group: 'org.osgi', name: 'org.osgi.util.promise', version: getProperty('version.osgi.promise')
}
jar {
bnd '''\
Import-Package: !lombok, *
'''
}

View File

@@ -0,0 +1,46 @@
package net.woggioni.osgi.simple.bootstrapper.application;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import net.woggioni.osgi.simple.bootstrapper.api.Application;
import net.woggioni.osgi.simple.bootstrapper.api.FrameworkService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ServiceScope;
import java.util.Objects;
import java.util.logging.Level;
@Log
@Component(scope = ServiceScope.SINGLETON)
public class ApplicationRunner {
private final Application application;
@Activate
@SneakyThrows
public ApplicationRunner(@Reference ServiceReference<Application> ref, BundleContext bundleContext, ComponentContext componentContext) {
application = bundleContext.getService(ref);
String componentName = (String) ref.getProperty("component.name");
ServiceReference<FrameworkService> frameworkServiceReference = bundleContext.getServiceReference(FrameworkService.class);
FrameworkService frameworkService = bundleContext.getService(frameworkServiceReference);
String mainApplicationComponentName = frameworkService.getMainApplicationComponentName();
if(mainApplicationComponentName == null || Objects.equals(mainApplicationComponentName, componentName)) {
Application application = bundleContext.getService(ref);
try {
frameworkService.setExitCode(application.run(frameworkService.getArgs()));
} catch(Exception ex) {
log.log(Level.SEVERE, ex, ex::getMessage);
frameworkService.setExitCode(1);
} finally {
bundleContext.getBundle(0).stop();
bundleContext.ungetService(ref);
}
}
}
}

View File

@@ -0,0 +1 @@
package net.woggioni.osgi.simple.bootstrapper.application;

View File

@@ -0,0 +1,36 @@
plugins {
id 'java-library'
}
group = "net.woggioni.osgi"
version = "0.1"
configurations {
tar {
visible = true
canBeConsumed = true
transitive = false
}
}
dependencies {
compileOnly group: 'org.osgi', name: 'osgi.annotation', version: getProperty('version.osgi')
compileOnly group: 'org.osgi', name: 'osgi.core', version: getProperty('version.osgi')
compileOnly group: 'org.osgi',
name: 'org.osgi.service.component.annotations',
version: getProperty('version.osgi.service.component')
compileOnly project(":osgi-app:osgi-simple-bootstrapper-api")
}
Provider<Tar> tarTaskProvider = tasks.register("tar", Tar) {
archiveFileName = "${project.name}.tar"
from(project.tasks.named(JavaPlugin.JAR_TASK_NAME)
.flatMap { it.archiveFile }
.map { it.getAsFile() }
.map(project.&zipTree))
}
artifacts {
tar tarTaskProvider
}

View File

@@ -0,0 +1,370 @@
package net.woggioni.osgi.simple.bootstrapper;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import net.woggioni.osgi.simple.bootstrapper.api.FrameworkService;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.function.Consumer;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@RequiredArgsConstructor
enum BundleState {
STARTING(Bundle.STARTING, "starting"),
INSTALLED(Bundle.INSTALLED, "installed"),
STOPPING(Bundle.STOPPING, "stopping"),
ACTIVE(Bundle.ACTIVE, "active"),
RESOLVED(Bundle.RESOLVED, "resolved"),
UNINSTALLED(Bundle.UNINSTALLED, "uninstalled");
@Getter
private final int code;
@Getter
private final String description;
public static BundleState fromCode(int code) {
return Arrays.stream(values())
.filter(it -> it.code == code)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown bundle state with code $code"));
}
}
@RequiredArgsConstructor
class FrameworkListener implements org.osgi.framework.FrameworkListener {
private static final Logger log = Logger.getLogger(FrameworkListener.class.getName());
private final Framework framework;
private static String eventMessage(FrameworkEvent evt) {
StringBuilder sb = new StringBuilder();
Bundle bundle =evt.getBundle();
sb.append("Bundle ");
sb.append(bundle.getSymbolicName());
sb.append("-");
sb.append(bundle.getVersion());
sb.append(':');
Optional.ofNullable(evt.getThrowable())
.map(Throwable::getMessage)
.ifPresent(sb::append);
return sb.toString();
}
@Override
public void frameworkEvent(FrameworkEvent evt) {
switch (evt.getType()) {
case FrameworkEvent.ERROR:
log.log(Level.SEVERE, evt.getThrowable(),
() -> eventMessage(evt));
break;
case FrameworkEvent.WARNING:
log.log(Level.WARNING, evt.getThrowable(), () -> eventMessage(evt));
break;
case FrameworkEvent.INFO:
log.log(Level.INFO, evt.getThrowable(), () -> eventMessage(evt));
break;
case FrameworkEvent.STARTED:
log.log(Level.INFO, () -> String.format("OSGI framework '%s' started",
framework.getClass().getName()));
break;
case FrameworkEvent.WAIT_TIMEDOUT:
log.log(Level.WARNING, () -> String.format("OSGI framework '%s' did not stop",
framework.getClass().getName()));
break;
case FrameworkEvent.STOPPED:
log.log(Level.INFO, () -> String.format("OSGI framework '%s' stopped",
framework.getClass().getName()));
break;
}
}
}
final class BundleListener implements org.osgi.framework.BundleListener {
private static final Logger log = Logger.getLogger(BundleListener.class.getName());
@Override
public void bundleChanged(BundleEvent evt) {
Bundle bundle = evt.getBundle();
log.fine(() -> String.format("Bundle-Location: %s, " +
"Bundle ID: %s, Bundle-SymbolicName: %s, Bundle-Version: %s, State: %s",
bundle.getLocation(),
bundle.getBundleId(),
bundle.getSymbolicName(),
bundle.getVersion(),
BundleState.fromCode(bundle.getState()).getDescription()));
}
}
class AllPolicy extends Policy {
private static final Logger log = Logger.getLogger(BundleListener.class.getName());
private static final PermissionCollection all = new PermissionCollection() {
private final List<Permission> PERMISSIONS = Collections.singletonList(new AllPermission());
{
setReadOnly();
}
@Override
public void add(Permission permission) {}
@Override
public Enumeration<Permission> elements() {
return Collections.enumeration(PERMISSIONS);
}
@Override
public boolean implies(Permission permission) {
return true;
}
};
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
if (codesource == null)
log.finest("Granting AllPermission to a bundle without codesource!");
else
log.finest(String.format("Granting AllPermission to %s", codesource.getLocation()));
return all;
}
@Override
public void refresh() {
log.finest("Policy refresh");
}
}
public class Bootstrapper implements AutoCloseable {
private static final String BUNDLE_LIST_FILE = "META-INF/bundles";
private static final String SYSTEM_PACKAGES_FILE = "META-INF/system_packages";
private static final String SYSTEM_PROPERTIES_FILE = "META-INF/system.properties";
private static final String FRAMEWORK_PROPERTIES_FILE = "META-INF/framework.properties";
private static final String MAIN_APPLICATION_COMPONENT_ATTRIBUTE = "Main-Application-Component";
private static final Logger log = Logger.getLogger(Bootstrapper.class.getName());
@SneakyThrows
private FrameworkFactory getFrameWorkFactory() {
ServiceLoader<FrameworkFactory> serviceLoader = ServiceLoader.load(FrameworkFactory.class);
for (FrameworkFactory frameworkFactory : serviceLoader) {
return frameworkFactory;
}
throw new IllegalStateException(String.format(
"No provider found for service '%s'", FrameworkFactory.class));
}
@SneakyThrows
private static String loadSystemPackages() {
URL resourceUrl = Bootstrapper.class.getClassLoader().getResource(SYSTEM_PACKAGES_FILE);
if(resourceUrl != null) {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(resourceUrl.openStream()))) {
return reader.lines().collect(Collectors.joining(","));
}
} else {
throw new IOException(String.format("'%s' not found", SYSTEM_PACKAGES_FILE));
}
}
private final String[] cliArgs;
private final Path storageDir;
private final Framework framework;
private final String mainApplicationComponentName;
@Getter(AccessLevel.PACKAGE)
private int exitCode = 0;
@SneakyThrows
private Bootstrapper(String[] cliArgs) {
this.cliArgs = cliArgs;
this.storageDir = Files.createTempDirectory("osgi-cache");
InputStream is = getClass().getClassLoader().getResourceAsStream(SYSTEM_PROPERTIES_FILE);
if(is != null) {
Properties props = new Properties();
try(Reader reader = new InputStreamReader(is)) {
props.load(reader);
}
props.forEach((key, value) -> System.getProperties().computeIfAbsent(key, k -> value));
}
Stream<Map.Entry<String,String>> entryStream = Stream.of(
new AbstractMap.SimpleEntry<>(Constants.FRAMEWORK_STORAGE, storageDir.toString()),
new AbstractMap.SimpleEntry<>(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT),
new AbstractMap.SimpleEntry<>(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, loadSystemPackages())
);
is = getClass().getClassLoader().getResourceAsStream(FRAMEWORK_PROPERTIES_FILE);
if(is != null) {
Properties props = new Properties();
try(Reader reader = new InputStreamReader(is)) {
props.load(reader);
}
entryStream = Stream.concat(entryStream,
props.entrySet().stream()
.map(it -> new AbstractMap.SimpleEntry<>((String) it.getKey(), (String) it.getValue())));
}
entryStream = Stream.concat(entryStream,
System.getProperties().entrySet().stream()
.map(it -> new AbstractMap.SimpleEntry<>((String) it.getKey(), (String) it.getValue())));
Map<String, String> frameworkPropertyMap = entryStream.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
framework = getFrameWorkFactory().newFramework(frameworkPropertyMap);
Manifest mf = new Manifest();
URL manifestURL = getClass().getClassLoader().getResource(JarFile.MANIFEST_NAME);
if(manifestURL != null) {
mf.read(manifestURL.openStream());
}
mainApplicationComponentName = mf.getMainAttributes().getValue(MAIN_APPLICATION_COMPONENT_ATTRIBUTE);
Policy.setPolicy(new AllPolicy());
}
@SneakyThrows
private void start() {
log.fine(() -> String.format("Starting OSGi framework %s %s",
framework.getClass().getName(), framework.getVersion()));
framework.start();
framework.getBundleContext().addFrameworkListener(new FrameworkListener(framework));
framework.getBundleContext().addBundleListener(new BundleListener());
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(BUNDLE_LIST_FILE);
BundleContext ctx = framework.getBundleContext();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
reader.lines().forEach(new Consumer<String>() {
@Override
@SneakyThrows
public void accept(String line) {
Enumeration<URL> it = getClass().getClassLoader().getResources(line);
while (it.hasMoreElements()) {
URL url = it.nextElement();
try (InputStream bundleInputStream = url.openStream()) {
ctx.installBundle(url.toString(), bundleInputStream);
}
}
}
});
}
ctx.registerService(FrameworkService.class, new FrameworkService() {
@Override
public String[] getArgs() {
return cliArgs;
}
@Override
public void setExitCode(int exitCode) {
Bootstrapper.this.exitCode = exitCode;
}
@Override
public String getMainApplicationComponentName() {
return mainApplicationComponentName;
}
}, null);
}
@SneakyThrows
private void activate(long ...bundleId) {
BundleContext ctx = framework.getBundleContext();
if(bundleId.length == 0) {
for(Bundle bundle : ctx.getBundles()) {
if(bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null &&
(bundle.getState() == BundleState.INSTALLED.getCode() || bundle.getState() == BundleState.RESOLVED.getCode())) {
bundle.start();
}
}
} else {
for(long id : bundleId) {
ctx.getBundle(id).start();
}
}
}
@Override
@SneakyThrows
public void close() {
if(framework.getState() == BundleState.ACTIVE.getCode() || framework.getState() == BundleState.STARTING.getCode()) {
framework.stop();
waitForStop();
Files.walk(storageDir)
.sorted(Comparator.reverseOrder())
.forEach(new Consumer<Path>() {
@Override
@SneakyThrows
public void accept(Path path) {
Files.delete(path);
}
});
}
}
private void waitForStop() {
waitForStop(5000L);
}
@SneakyThrows
private void waitForStop(long timeout) {
FrameworkEvent evt = framework.waitForStop(timeout);
switch (evt.getType()) {
case FrameworkEvent.ERROR:
log.log(Level.SEVERE, evt.getThrowable().getMessage(), evt.getThrowable());
throw evt.getThrowable();
case FrameworkEvent.WAIT_TIMEDOUT:
log.warning("OSGi framework shutdown timed out");
break;
case FrameworkEvent.STOPPED:
break;
default:
throw new IllegalStateException(String.format("Unknown event type %d", evt.getType()));
}
}
public static void main(String[] args) {
int exitCode;
Bootstrapper cnt = new Bootstrapper(args);
Runtime.getRuntime().addShutdownHook(new Thread(cnt::close));
try {
cnt.start();
cnt.activate();
cnt.waitForStop(0L);
} finally {
cnt.close();
}
exitCode = cnt.getExitCode();
System.exit(exitCode);
}
}

View File

@@ -0,0 +1,42 @@
package net.woggioni.osgi.simple.bootstrapper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JavaAgentLauncher {
@SneakyThrows
static void premain(String agentArguments, Instrumentation instrumentation) {
ClassLoader cl = JavaAgentLauncher.class.getClassLoader();
Enumeration<URL> it = cl.getResources("META-INF/javaAgents.properties");
while(it.hasMoreElements()) {
URL url = it.nextElement();
Properties properties = new Properties();
try(InputStream inputStream = url.openStream()) {
properties.load(inputStream);
}
for(Map.Entry<Object, Object> entry : properties.entrySet()) {
String agentClassName = (String) entry.getKey();
String agentArgs = (String) entry.getValue();
Class<?> agentClass = cl.loadClass(agentClassName);
Method premainMethod = agentClass.getMethod("premain", String.class, Instrumentation.class);
premainMethod.invoke(null, agentArgs, instrumentation);
}
}
}
static void agentmain(String agentArguments, Instrumentation instrumentation) {
premain(agentArguments, instrumentation);
}
}

View File

@@ -0,0 +1,69 @@
package net.woggioni.gradle.osgi.app;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import javax.annotation.Nonnull;
import lombok.SneakyThrows;
import org.gradle.api.resources.ReadableResource;
import org.gradle.api.resources.ResourceException;
abstract class EmbeddedResource implements ReadableResource {
private final URL url;
private final String baseName;
private final String extension;
protected EmbeddedResource(String baseName, String extension) {
this.baseName = baseName;
this.extension = extension;
url = getClass().getResource(String.format("/META-INF/%s.%s", baseName, extension));
}
@Override
@Nonnull
@SneakyThrows
public InputStream read() throws ResourceException {
return url.openStream();
}
@Override
public String getDisplayName() {
return getBaseName() + "." + extension;
}
@Override
@SneakyThrows
public URI getURI() {
return url.toURI();
}
@Override
public String getBaseName() {
return baseName;
}
}
final class BootstrapperResource extends EmbeddedResource {
static final ReadableResource instance = new BootstrapperResource();
private BootstrapperResource() {
super("osgi-simple-bootstrapper", "tar");
}
}
final class BootstrapperApiResource extends EmbeddedResource {
static final ReadableResource instance = new BootstrapperApiResource();
private BootstrapperApiResource() {
super("osgi-simple-bootstrapper-api", "jar");
}
}
final class BootstrapperApplicationResource extends EmbeddedResource {
static final ReadableResource instance = new BootstrapperApplicationResource();
private BootstrapperApplicationResource() {
super("osgi-simple-bootstrapper-application", "jar");
}
}

View File

@@ -0,0 +1,65 @@
package net.woggioni.gradle.osgi.app;
import aQute.bnd.osgi.Constants;
import groovy.lang.Tuple2;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.osgi.framework.Version;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
public class BundleFileTask extends DefaultTask {
private final File systemBundleFile;
private final List<File> bundles;
public BundleFileTask() {
systemBundleFile = new File(getTemporaryDir(), "bundles");
bundles = new ArrayList<>();
}
@OutputFile
public File getOutputFile() {
return systemBundleFile;
}
public void bundle(File file) {
bundles.add(file);
}
@TaskAction
@SneakyThrows
public void run() {
Map<Tuple2<String, Version>, String> map = new TreeMap<>();
for(File bundleFile : bundles) {
try(JarFile jarFile = new JarFile(bundleFile)) {
Attributes mainAttributes = jarFile.getManifest().getMainAttributes();
String bundleSymbolicName = mainAttributes.getValue(Constants.BUNDLE_SYMBOLICNAME);
String bundleVersion = mainAttributes.getValue(Constants.BUNDLE_VERSION);
if(bundleSymbolicName != null && bundleVersion != null) {
Tuple2<String, Version> key = new Tuple2<>(
bundleSymbolicName,
Version.parseVersion(bundleVersion));
map.put(key, bundleFile.getName());
}
}
}
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(systemBundleFile)))) {
for(Map.Entry<Tuple2<String, Version>, String> entry : map.entrySet()) {
writer.write("bundles/" + entry.getValue());
writer.newLine();
}
}
}
}

View File

@@ -0,0 +1,43 @@
package net.woggioni.gradle.osgi.app;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.Writer;
import java.nio.file.Files;
import java.util.Properties;
public class FrameworkPropertyFileTask extends DefaultTask {
@OutputFile
File getOutputFile() {
return new File(getTemporaryDir(), "framework.properties");
}
@Getter(onMethod_ = @Input)
final MapProperty<String, String> frameworkProperties;
@Inject
public FrameworkPropertyFileTask(ObjectFactory objects) {
frameworkProperties = objects.mapProperty(String.class, String.class);
}
@TaskAction
@SneakyThrows
void run() {
try(Writer writer = Files.newBufferedWriter(getOutputFile().toPath())) {
Properties properties = new Properties();
properties.putAll(frameworkProperties.get());
properties.store(writer, null);
}
}
}

View File

@@ -0,0 +1,42 @@
package net.woggioni.gradle.osgi.app;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Set;
@RequiredArgsConstructor(onConstructor_ = @Inject)
public class FrameworkRuntimeCheck extends DefaultTask {
@Getter(onMethod_ = @InputFiles)
private final Provider<Configuration> confProvider;
@TaskAction
@SneakyThrows
void run() {
Configuration conf = confProvider.get();
Set<File> files = conf.getFiles();
URL[] urls = new URL[files.size()];
int i = 0;
for(File file : files) {
urls[i++] = file.toURI().toURL();
}
try {
new URLClassLoader(urls).loadClass("org.osgi.framework.launch.Framework");
} catch (ClassNotFoundException cnfe) {
throw new GradleException(
String.format("No OSGi framework runtime found in '%s' configuration", conf.getName()));
}
}
}

View File

@@ -0,0 +1,9 @@
package net.woggioni.gradle.osgi.app;
import lombok.Data;
@Data
public class JavaAgent {
private final String className;
private final String args;
}

View File

@@ -0,0 +1,46 @@
package net.woggioni.gradle.osgi.app;
import lombok.Getter;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.Writer;
import java.nio.file.Files;
import java.util.Collections;
import java.util.Properties;
public class JavaAgentFileTask extends DefaultTask {
@OutputFile
public File getOutputFile() {
return new File(getTemporaryDir(), "javaAgents.properties");
}
@Getter(onMethod_ = @Input)
private final ListProperty<JavaAgent> javaAgents;
@Inject
public JavaAgentFileTask(ObjectFactory objects) {
javaAgents = objects.listProperty(JavaAgent.class)
.convention(getProject().provider(Collections::emptyList));
}
@TaskAction
@SneakyThrows
public void run() {
try(Writer writer = Files.newBufferedWriter(getOutputFile().toPath())) {
Properties props = new Properties();
for(JavaAgent javaAgent : javaAgents.get()) {
props.setProperty(javaAgent.getClassName(), javaAgent.getArgs());
}
props.store(writer, null);
}
}
}

View File

@@ -0,0 +1,31 @@
package net.woggioni.gradle.osgi.app;
import java.util.Collections;
import java.util.Map;
import java.util.function.Supplier;
public class MapBuilder<K, V, M extends Map<K, V>> {
public static <K, V, M extends Map<K, V>> MapBuilder<K, V, M> getInstance(Supplier<M> mapConstructor) {
return new MapBuilder<>(mapConstructor);
}
private final M map;
private MapBuilder(Supplier<M> mapConstructor) {
map = mapConstructor.get();
}
public MapBuilder<K, V, M> of(K key, V value) {
map.put(key, value);
return this;
}
public M build() {
return map;
}
public Map<K, V> buildImmutable() {
return Collections.unmodifiableMap(map);
}
}

View File

@@ -0,0 +1,72 @@
package net.woggioni.gradle.osgi.app;
import lombok.Getter;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Property;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class OsgiAppExtension {
public static final String BOOTSTRAPPER_GROUP = "net.woggioni.osgi";
public static final String BOOTSTRAPPER_NAME = "osgi-simple-bootstrapper";
public static final String BOOTSTRAPPER_API_NAME = "osgi-simple-bootstrapper-api";
public static final String BOOTSTRAPPER_APPLICATION_NAME = "osgi-simple-bootstrapper-application";
public static final String BOOTSTRAP_CLASSPATH_CONFIGURATION_NAME = "bootstrapClasspath";
public static final String BUNDLES_CONFIGURATION_NAME = "bundles";
public static final String SYSTEM_PACKAGES_CONFIGURATION_NAME = "systemPackages";
final List<JavaAgent> javaAgents = new ArrayList<>();
@Getter
private final MapProperty<String, String> frameworkProperties;
@Getter
private final MapProperty<String, String> systemProperties;
@Getter
private final Property<String> bootstrapperVersion;
@Getter
private final ListProperty<String> systemPackages;
@Getter
private final Property<String> mainApplicationComponent;
@Getter
private final Property<String> frameworkFactoryClass;
@Inject
public OsgiAppExtension(ObjectFactory objects) {
frameworkFactoryClass = objects.property(String.class)
.convention("org.apache.felix.framework.FrameworkFactory");
frameworkProperties = objects.mapProperty(String.class, String.class).convention(new HashMap<>());
systemProperties = objects.mapProperty(String.class, String.class).convention(new HashMap<>());
bootstrapperVersion = objects.property(String.class);
systemPackages = objects.listProperty(String.class).convention(
Stream.of(
"sun.net.www.protocol.jar",
"sun.nio.ch",
"sun.security.x509",
"sun.security.ssl",
"javax.servlet",
"javax.transaction.xa;version=1.1.0",
"javax.xml.stream;version=1.0",
"javax.xml.stream.events;version=1.0",
"javax.xml.stream.util;version=1.0").collect(Collectors.toList()));
mainApplicationComponent = objects.property(String.class);
}
public void agent(String className, String args) {
javaAgents.add(new JavaAgent(className, args));
}
}

View File

@@ -0,0 +1,289 @@
package net.woggioni.gradle.osgi.app;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ExternalDependency;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.attributes.LibraryElements;
import org.gradle.api.file.DuplicatesStrategy;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.plugins.BasePluginExtension;
import org.gradle.api.plugins.ExtraPropertiesExtension;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.provider.Provider;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.JavaExec;
import org.gradle.api.tasks.bundling.Jar;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Supplier;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
public class OsgiAppPlugin implements Plugin<Project> {
private static void applyDependencySubstitution(Configuration conf) {
conf.getResolutionStrategy().dependencySubstitution(dependencySubstitutions -> {
//Replace Kotlin stdlib
dependencySubstitutions.substitute(dependencySubstitutions.module("org.jetbrains.kotlin:kotlin-stdlib-common"))
.using(dependencySubstitutions.module("org.jetbrains.kotlin:kotlin-osgi-bundle:$kotlinVersion"));
dependencySubstitutions.substitute(dependencySubstitutions.module("org.jetbrains.kotlin:kotlin-stdlib"))
.using(dependencySubstitutions.module("org.jetbrains.kotlin:kotlin-osgi-bundle:$kotlinVersion"));
dependencySubstitutions.substitute(dependencySubstitutions.module("org.jetbrains.kotlin:kotlin-reflect"))
.using(dependencySubstitutions.module("org.jetbrains.kotlin:kotlin-osgi-bundle:$kotlinVersion"));
});
}
private static Map<String, String> createDependencyNotation(String group, String name, String version) {
Map<String, String> m = new TreeMap<>();
m.put("group", group);
m.put("name", name);
m.put("version", version);
return Collections.unmodifiableMap(m);
}
private static Dependency createProjectDependency(DependencyHandler handler, String path) {
return createProjectDependency(handler, path, null);
}
private static Dependency createProjectDependency(DependencyHandler handler, String path, String configuration) {
Map<String, String> m = new TreeMap<>();
m.put("path", path);
if(configuration != null) {
m.put("configuration", configuration);
}
return handler.project(m);
}
@Getter
@EqualsAndHashCode
@RequiredArgsConstructor
private static final class NameAndGroup {
private final String group;
private final String name;
}
private static void alignVersionsTo(ConfigurationContainer cc, String sourceConfigurationName, Configuration target) {
target.withDependencies(dependencies -> {
Map<NameAndGroup, String> modules = new HashMap<>();
cc.getByName(sourceConfigurationName).getIncoming().getResolutionResult().getAllComponents().forEach(resolvedComponentResult -> {
ModuleVersionIdentifier moduleVersionIdentifier = resolvedComponentResult.getModuleVersion();
modules.put(new NameAndGroup(moduleVersionIdentifier.getGroup(), moduleVersionIdentifier.getName()), moduleVersionIdentifier.getVersion());
});
dependencies.configureEach(dependency -> {
if(dependency instanceof ExternalDependency) {
NameAndGroup needle = new NameAndGroup(dependency.getGroup(), dependency.getName());
String constrainedVersion = modules.get(needle);
if(constrainedVersion != null) {
((ExternalDependency) dependency).version(versionConstraint -> {
versionConstraint.require(constrainedVersion);
});
}
}
});
});
}
@Override
@SneakyThrows
public void apply(Project project) {
project.getPlugins().apply("java-library");
project.getPlugins().apply("biz.aQute.bnd.builder");
OsgiAppExtension osgiAppExtension = project.getExtensions().create("osgiApp", OsgiAppExtension.class);
ExtraPropertiesExtension ext = project.getExtensions().getExtraProperties();
ConfigurationContainer cc = project.getConfigurations();
Provider<Configuration> runtimeClasspathConfiguration = cc.named(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME, conf -> {
conf.getAttributes()
.attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE,
project.getObjects().named(LibraryElements.class, LibraryElements.JAR));
});
Configuration systemPackagesConf = cc.create(OsgiAppExtension.SYSTEM_PACKAGES_CONFIGURATION_NAME);
systemPackagesConf.setCanBeConsumed(false);
systemPackagesConf.setTransitive(false);
applyDependencySubstitution(systemPackagesConf);
cc.named(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME, conf -> conf.extendsFrom(systemPackagesConf));
Provider<Configuration> bootstrapClasspathConf = cc.register(OsgiAppExtension.BOOTSTRAP_CLASSPATH_CONFIGURATION_NAME, conf -> {
conf.setCanBeConsumed(false);
conf.setTransitive(true);
conf.extendsFrom(systemPackagesConf);
applyDependencySubstitution(conf);
alignVersionsTo(project.getConfigurations(), JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME, conf);
});
Provider<Configuration> bundlesConf = cc.register(OsgiAppExtension.BUNDLES_CONFIGURATION_NAME, conf -> {
conf.setTransitive(true);
conf.setCanBeConsumed(false);
conf.extendsFrom(cc.getAt(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME));
conf.getAttributes().attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.getObjects().named(LibraryElements.class, LibraryElements.JAR));
applyDependencySubstitution(conf);
});
cc.named(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME, conf -> conf.extendsFrom(systemPackagesConf));
DependencyHandler dependencyHandler = project.getDependencies();
Provider<Map<String, String>> bootstrapperDependencyNotationProvider = project.provider(() ->
createDependencyNotation(
OsgiAppExtension.BOOTSTRAPPER_GROUP,
OsgiAppExtension.BOOTSTRAPPER_NAME,
osgiAppExtension.getBootstrapperVersion().get()));
Provider<Map<String, String>> bootstrapperApiDependencyNotationProvider = project.provider(() ->
createDependencyNotation(
OsgiAppExtension.BOOTSTRAPPER_GROUP,
OsgiAppExtension.BOOTSTRAPPER_API_NAME,
osgiAppExtension.getBootstrapperVersion().get()));
Provider<Map<String, String>> bootstrapperApplicationDependencyNotationProvider = project.provider(() ->
createDependencyNotation(
OsgiAppExtension.BOOTSTRAPPER_GROUP,
OsgiAppExtension.BOOTSTRAPPER_APPLICATION_NAME,
osgiAppExtension.getBootstrapperVersion().get()));
project.getDependencies().addProvider(OsgiAppExtension.BOOTSTRAP_CLASSPATH_CONFIGURATION_NAME,
bootstrapperDependencyNotationProvider,
it -> {});
project.getDependencies().addProvider(OsgiAppExtension.BUNDLES_CONFIGURATION_NAME,
bootstrapperApplicationDependencyNotationProvider,
it -> {});
project.getDependencies().addProvider(OsgiAppExtension.SYSTEM_PACKAGES_CONFIGURATION_NAME,
bootstrapperApiDependencyNotationProvider,
it -> {});
Provider<PropertyFileTask> frameworkPropertyFileTaskProvider = project.getTasks().register("frameworkPropertyFile", PropertyFileTask.class, task -> {
task.getFileName().set("framework.properties");
task.getProperties().set(osgiAppExtension.getFrameworkProperties());
});
Provider<PropertyFileTask> systemPropertyFileTaskProvider = project.getTasks().register("systemPropertyFile", PropertyFileTask.class, task -> {
task.getFileName().set("system.properties");
task.getProperties().set(osgiAppExtension.getSystemProperties());
});
Provider<JavaAgentFileTask> javaAgentFileTask = project.getTasks().register("javaAgentFile", JavaAgentFileTask.class, task -> {
task.getJavaAgents().set(osgiAppExtension.javaAgents);
});
Provider<Jar> jarFileTask = project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class);
Supplier<FileCollection> bundlesSupplier = () -> {
return bundlesConf.get()
.minus(systemPackagesConf).plus(project.files(jarFileTask.get().getArchiveFile()))
.filter(new Spec<File>() {
@Override
@SneakyThrows
public boolean isSatisfiedBy(File file) {
return OsgiAppUtils.isJar(file.getName());
}
});
};
Provider<SystemPackageExtraFileTask> systemPackageExtraFileTask =
project.getTasks().register("systemPackageExtraFile", SystemPackageExtraFileTask.class, t -> {
t.getExtraSystemPackages().set(osgiAppExtension.getSystemPackages());
});
Provider<BundleFileTask> bundleFileTask = project.getTasks()
.register("bundleFile", BundleFileTask.class, task -> {
task.getInputs().files(jarFileTask);
FileCollection bundles = bundlesSupplier.get();
task.getInputs().files(bundlesSupplier.get());
bundles.forEach(task::bundle);
});
Provider<Jar> osgiJar = project.getTasks().register("osgiJar", Jar.class, (Jar task) -> {
BasePluginExtension basePluginExtension = project.getExtensions()
.findByType(BasePluginExtension.class);
task.getDestinationDirectory().set(basePluginExtension.getDistsDirectory());
task.getArchiveClassifier().set("osgi");
FileCollection bundles = bundlesSupplier.get();
Provider<Jar> jarTaskProvider = project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class);
task.getInputs().files(bootstrapClasspathConf);
task.getInputs().files(bundles);
task.getInputs().files(systemPackagesConf);
// task.getInputs().file(jarTaskProvider);
task.exclude("META-INF/MANIFEST.MF");
task.exclude("META-INF/*.SF");
task.exclude("META-INF/*.DSA");
task.exclude("META-INF/*.RSA");
task.exclude("META-INF/*.EC");
task.exclude("META-INF/DEPENDENCIES");
task.exclude("META-INF/LICENSE");
task.exclude("META-INF/NOTICE");
task.exclude("module-info.class");
task.exclude("META-INF/versions/*/module-info.class");
task.setDuplicatesStrategy(DuplicatesStrategy.WARN);
MapBuilder<String, String, TreeMap<String,String>> mapBuilder = MapBuilder.getInstance(TreeMap<String,String>::new)
.of("Main-Class", "net.woggioni.osgi.simple.bootstrapper.Bootstrapper")
.of("Launcher-Agent-Class", "net.woggioni.osgi.simple.bootstrapper.JavaAgentLauncher")
.of("Can-Redefine-Classes", Boolean.toString(true))
.of("Can-Retransform-Classes", Boolean.toString(true));
if(osgiAppExtension.getMainApplicationComponent().isPresent()) {
mapBuilder.of("Main-Application-Component", osgiAppExtension.getMainApplicationComponent().get());
}
task.getManifest().attributes(mapBuilder.buildImmutable());
task.into("META-INF/", copySpec -> {
copySpec.from(javaAgentFileTask);
copySpec.from(bundleFileTask);
copySpec.from(frameworkPropertyFileTaskProvider);
copySpec.from(systemPropertyFileTaskProvider);
copySpec.from(systemPackageExtraFileTask);
});
task.from(bootstrapClasspathConf.get().getFiles().stream().map(it -> {
if(it.isDirectory()) {
return it;
} else {
return project.zipTree(it);
}
}).collect(Collectors.toList()));
task.into("bundles", copySpec -> {
copySpec.from(bundlesSupplier.get(), copySpec2 ->
copySpec2.eachFile(new Action<FileCopyDetails>() {
@Override
@SneakyThrows
public void execute(FileCopyDetails fcd) {
try (JarFile jarFile = new JarFile(fcd.getFile())) {
if (!OsgiAppUtils.isBundle(jarFile)) {
fcd.exclude();
}
}
}
})
);
});
});
project.getTasks().register("osgiRun", JavaExec.class, javaExec -> {
javaExec.setClasspath(project.files(osgiJar));
});
Provider<FrameworkRuntimeCheck> frameworkRuntimeCheckTaskProvider =
project.getTasks().register("frameworkRuntimeCheck",
FrameworkRuntimeCheck.class, bootstrapClasspathConf);
project.getTasks().named(JavaPlugin.CLASSES_TASK_NAME,
t -> t.dependsOn(frameworkRuntimeCheckTaskProvider));
}
}

View File

@@ -0,0 +1,22 @@
package net.woggioni.gradle.osgi.app;
import aQute.bnd.osgi.Constants;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import java.util.jar.JarFile;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class OsgiAppUtils {
@SneakyThrows
static boolean isBundle(JarFile jarFile) {
java.util.jar.Attributes mainAttributes = jarFile.getManifest().getMainAttributes();
return mainAttributes.getValue(Constants.BUNDLE_SYMBOLICNAME) != null && mainAttributes.getValue(Constants.BUNDLE_VERSION) != null;
}
static boolean isJar(String fileName) {
return fileName.endsWith(".jar");
}
}

View File

@@ -0,0 +1,48 @@
package net.woggioni.gradle.osgi.app;
import lombok.Getter;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.Writer;
import java.nio.file.Files;
import java.util.Properties;
public class PropertyFileTask extends DefaultTask {
@Getter(onMethod_ = @Input)
private final Property<String> fileName;
@OutputFile
Provider<File> getOutputFile() {
return fileName.map(name -> new File(getTemporaryDir(), name));
}
@Getter(onMethod_ = @Input)
final MapProperty<String, String> properties;
@Inject
public PropertyFileTask(ObjectFactory objects) {
fileName = objects.property(String.class);
properties = objects.mapProperty(String.class, String.class);
}
@TaskAction
@SneakyThrows
void run() {
try(Writer writer = Files.newBufferedWriter(getOutputFile().get().toPath())) {
Properties properties = new Properties();
properties.putAll(this.properties.get());
properties.store(writer, null);
}
}
}

View File

@@ -0,0 +1,99 @@
package net.woggioni.gradle.osgi.app;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import lombok.Getter;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.ArtifactCollection;
import org.gradle.api.artifacts.ResolvableDependencies;
import org.gradle.api.artifacts.result.ResolvedArtifactResult;
import org.gradle.api.file.FileCollection;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.jar.JarFile;
import static net.woggioni.gradle.osgi.app.OsgiAppUtils.isBundle;
import static net.woggioni.gradle.osgi.app.OsgiAppUtils.isJar;
public class SystemPackageExtraFileTask extends DefaultTask {
@Getter(onMethod_ = @Input)
private final ListProperty<String> extraSystemPackages;
final File systemPackagesExtraFile;
@Inject
public SystemPackageExtraFileTask(ObjectFactory objects) {
extraSystemPackages = objects.listProperty(String.class);
systemPackagesExtraFile = new File(getTemporaryDir(), "system_packages");
}
@InputFiles
FileCollection getInputFiles() {
return getProject().getConfigurations().getByName("systemPackages");
}
@OutputFile
File getOutputFile() {
return systemPackagesExtraFile;
}
@SneakyThrows
private NavigableSet<String> buildPackagesExtra(ArtifactCollection artifacts) {
TreeSet<String> result = new TreeSet<>();
for(ResolvedArtifactResult resolvedArtifactResult : artifacts.getArtifacts()) {
if(isJar(resolvedArtifactResult.getFile().getName())) {
try(JarFile jarFile = new JarFile(resolvedArtifactResult.getFile(), true, JarFile.OPEN_READ, JarFile.runtimeVersion())) {
if (isBundle(jarFile)) {
String exportPackages = jarFile.getManifest().getMainAttributes().getValue(org.osgi.framework.Constants.EXPORT_PACKAGE);
if(exportPackages != null) {
for (Map.Entry<String, Attrs> entry : OSGiHeader.parseHeader(exportPackages).entrySet()) {
String exportString = entry.getKey() + ";" + entry.getValue().toString();
result.add(exportString);
}
}
} else {
jarFile.versionedStream()
.filter(jarEntry -> jarEntry.getName().endsWith(".class"))
.forEach(jarEntry -> {
String entryName = jarEntry.getName();
int end = entryName.lastIndexOf('/');
if (end > 0) {
String export = entryName.substring(0, end).replace('/', '.');
result.add(export);
}
});
}
}
}
}
result.addAll(extraSystemPackages.get());
return result;
}
@TaskAction
@SneakyThrows
public void run() {
ResolvableDependencies resolvableDependencies = getProject().getConfigurations().getByName(OsgiAppExtension.SYSTEM_PACKAGES_CONFIGURATION_NAME).getIncoming();
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(systemPackagesExtraFile)))) {
for(String export : buildPackagesExtra(resolvableDependencies.getArtifacts())) {
writer.write(export);
writer.newLine();
}
}
}
}

View File

@@ -0,0 +1,42 @@
package net.woggioni.gradle.osgi.app;
import lombok.Getter;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.Writer;
import java.nio.file.Files;
import java.util.Properties;
public class SystemPropertyFileTask extends DefaultTask {
@OutputFile
File getOutputFile() {
return new File(getTemporaryDir(), "system.properties");
}
@Getter(onMethod_ = @Input)
final MapProperty<String, String> system;
@Inject
public SystemPropertyFileTask(ObjectFactory objects) {
system = objects.mapProperty(String.class, String.class);
}
@TaskAction
@SneakyThrows
void run() {
try(Writer writer = Files.newBufferedWriter(getOutputFile().toPath())) {
Properties properties = new Properties();
properties.putAll(system.get());
properties.store(writer, null);
}
}
}