Search in sources :

Example 21 with Feature

use of org.apache.karaf.features.internal.model.Feature in project karaf by apache.

the class AssemblyDeployCallback method installConfigs.

@Override
public void installConfigs(org.apache.karaf.features.Feature feature) throws IOException, InvalidSyntaxException {
    assertNotBlacklisted(feature);
    // Install
    Downloader downloader = manager.createDownloader();
    for (Config config : ((Feature) feature).getConfig()) {
        if (config.isExternal()) {
            downloader.download(config.getValue().trim(), provider -> {
                Path input = provider.getFile().toPath();
                byte[] data = Files.readAllBytes(input);
                Path configFile = etcDirectory.resolve(config.getName() + ".cfg");
                LOGGER.info("      adding config file: {}", homeDirectory.relativize(configFile));
                if (!Files.exists(configFile)) {
                    Files.write(configFile, data);
                } else if (config.isAppend()) {
                    Files.write(configFile, data, StandardOpenOption.APPEND);
                }
            });
        } else {
            byte[] data = config.getValue().getBytes();
            Path configFile = etcDirectory.resolve(config.getName() + ".cfg");
            LOGGER.info("      adding config file: {}", homeDirectory.relativize(configFile));
            if (!Files.exists(configFile)) {
                Files.write(configFile, data);
            } else if (config.isAppend()) {
                Files.write(configFile, data, StandardOpenOption.APPEND);
            }
        }
    }
    for (final ConfigFile configFile : ((Feature) feature).getConfigfile()) {
        downloader.download(configFile.getLocation(), provider -> {
            Path input = provider.getFile().toPath();
            String path = configFile.getFinalname();
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            path = substFinalName(path);
            Path output = homeDirectory.resolve(path);
            LOGGER.info("      adding config file: {}", path);
            Files.copy(input, output, StandardCopyOption.REPLACE_EXISTING);
        });
    }
}
Also used : Path(java.nio.file.Path) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) Config(org.apache.karaf.features.internal.model.Config) Downloader(org.apache.karaf.features.internal.download.Downloader) Feature(org.apache.karaf.features.internal.model.Feature)

Example 22 with Feature

use of org.apache.karaf.features.internal.model.Feature in project karaf by apache.

the class AssemblyDeployCallback method installLibraries.

@Override
public void installLibraries(org.apache.karaf.features.Feature feature) throws IOException {
    assertNotBlacklisted(feature);
    Downloader downloader = manager.createDownloader();
    List<String> libraries = new ArrayList<>();
    for (Library library : ((Feature) feature).getLibraries()) {
        String lib = library.getLocation() + ";type:=" + library.getType() + ";export:=" + library.isExport() + ";delegate:=" + library.isDelegate();
        libraries.add(lib);
    }
    if (!libraries.isEmpty()) {
        Path configPropertiesPath = etcDirectory.resolve("config.properties");
        Properties configProperties = new Properties(configPropertiesPath.toFile());
        builder.downloadLibraries(downloader, configProperties, libraries, "   ");
    }
    try {
        downloader.await();
    } catch (Exception e) {
        throw new IOException("Error downloading configuration files", e);
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) Downloader(org.apache.karaf.features.internal.download.Downloader) Library(org.apache.karaf.features.internal.model.Library) IOException(java.io.IOException) Properties(org.apache.felix.utils.properties.Properties) Feature(org.apache.karaf.features.internal.model.Feature) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException)

Example 23 with Feature

use of org.apache.karaf.features.internal.model.Feature in project karaf by apache.

the class Builder method addFeatures.

private void addFeatures(Set<Feature> allFeatures, String feature, Set<Feature> features, boolean mandatory) {
    String name;
    VersionRange range;
    int idx = feature.indexOf('/');
    if (idx > 0) {
        name = feature.substring(0, idx);
        String version = feature.substring(idx + 1);
        version = version.trim();
        if (version.equals(org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)) {
            range = new VersionRange(Version.emptyVersion);
        } else {
            range = new VersionRange(version, true, true);
        }
    } else {
        name = feature;
        range = new VersionRange(Version.emptyVersion);
    }
    Set<Feature> set = allFeatures.stream().filter(f -> f.getName().equals(name) && range.contains(VersionTable.getVersion(f.getVersion()))).collect(Collectors.toSet());
    if (mandatory && set.isEmpty()) {
        throw new IllegalStateException("Could not find matching feature for " + feature);
    }
    for (Feature f : set) {
        features.add(f);
        for (Dependency dep : f.getFeature()) {
            addFeatures(allFeatures, dep.toString(), features, !dep.isDependency() && !dep.isPrerequisite());
        }
    }
}
Also used : Manifest(java.util.jar.Manifest) Dependency(org.apache.karaf.features.internal.model.Dependency) Profile(org.apache.karaf.profile.Profile) Arrays(java.util.Arrays) Constants(org.osgi.framework.Constants) KarafPropertiesEditor(org.apache.karaf.tools.utils.KarafPropertiesEditor) LoggerFactory(org.slf4j.LoggerFactory) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) FeaturesService(org.apache.karaf.features.FeaturesService) java.nio.file(java.nio.file) DownloadManagerHelper(org.apache.karaf.features.internal.download.impl.DownloadManagerHelper) Clause(org.apache.felix.utils.manifest.Clause) ByteArrayInputStream(java.io.ByteArrayInputStream) JaxbUtil(org.apache.karaf.features.internal.model.JaxbUtil) Map(java.util.Map) URI(java.net.URI) VersionTable(org.apache.felix.utils.version.VersionTable) ZipEntry(java.util.zip.ZipEntry) BundleRevision(org.osgi.framework.wiring.BundleRevision) EnumSet(java.util.EnumSet) MavenResolver(org.ops4j.pax.url.mvn.MavenResolver) Blacklist(org.apache.karaf.features.internal.service.Blacklist) Deployer(org.apache.karaf.features.internal.service.Deployer) MapUtils(org.apache.karaf.features.internal.util.MapUtils) Collection(java.util.Collection) Set(java.util.Set) MANIFEST_NAME(java.util.jar.JarFile.MANIFEST_NAME) UUID(java.util.UUID) Library(org.apache.karaf.features.Library) Version(org.osgi.framework.Version) Attributes(java.util.jar.Attributes) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) VersionRange(org.apache.felix.utils.version.VersionRange) List(java.util.List) PropertiesLoader(org.apache.karaf.util.config.PropertiesLoader) Properties(org.apache.felix.utils.properties.Properties) Pattern(java.util.regex.Pattern) DownloadManager(org.apache.karaf.features.internal.download.DownloadManager) Features(org.apache.karaf.features.internal.model.Features) Dictionary(java.util.Dictionary) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DownloadCallback(org.apache.karaf.features.internal.download.DownloadCallback) HashMap(java.util.HashMap) ResourceBuilder(org.apache.karaf.features.internal.resolver.ResourceBuilder) Kar(org.apache.karaf.kar.internal.Kar) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) StreamProvider(org.apache.karaf.features.internal.download.StreamProvider) ProfileBuilder(org.apache.karaf.profile.ProfileBuilder) Parser(org.apache.karaf.util.maven.Parser) BaseRepository(org.apache.karaf.features.internal.repository.BaseRepository) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Bundle(org.apache.karaf.features.internal.model.Bundle) MavenResolvers(org.ops4j.pax.url.mvn.MavenResolvers) VersionUtils(org.apache.karaf.profile.versioning.VersionUtils) Downloader(org.apache.karaf.features.internal.download.Downloader) TYPE_REPOSITORY(org.apache.karaf.features.internal.service.Blacklist.TYPE_REPOSITORY) Content(org.apache.karaf.features.internal.model.Content) Hashtable(java.util.Hashtable) LinkedHashSet(java.util.LinkedHashSet) Logger(org.slf4j.Logger) Profiles(org.apache.karaf.profile.impl.Profiles) MalformedURLException(java.net.MalformedURLException) Conditional(org.apache.karaf.features.internal.model.Conditional) Resource(org.osgi.resource.Resource) IOException(java.io.IOException) ResolverImpl(org.apache.felix.resolver.ResolverImpl) Resolver(org.osgi.service.resolver.Resolver) KarafPropertyEdits(org.apache.karaf.tools.utils.model.KarafPropertyEdits) File(java.io.File) TreeMap(java.util.TreeMap) Feature(org.apache.karaf.features.internal.model.Feature) Config(org.apache.karaf.features.internal.model.Config) Startup(org.apache.karaf.profile.assembly.Builder.Stage.Startup) Collections(java.util.Collections) InputStream(java.io.InputStream) VersionRange(org.apache.felix.utils.version.VersionRange) Dependency(org.apache.karaf.features.internal.model.Dependency) Feature(org.apache.karaf.features.internal.model.Feature)

Example 24 with Feature

use of org.apache.karaf.features.internal.model.Feature in project karaf by apache.

the class Builder method installStage.

private void installStage(Profile installedProfile, Set<Feature> allBootFeatures) throws Exception {
    LOGGER.info("Install stage");
    //
    // Handle installed profiles
    //
    Profile installedOverlay = Profiles.getOverlay(installedProfile, allProfiles, environment);
    Profile installedEffective = Profiles.getEffective(installedOverlay, false);
    Downloader downloader = manager.createDownloader();
    // Load startup repositories
    Map<String, Features> installedRepositories = loadRepositories(manager, installedEffective.getRepositories(), true);
    // Compute startup feature dependencies
    Set<Feature> allInstalledFeatures = new HashSet<>();
    for (Features repo : installedRepositories.values()) {
        allInstalledFeatures.addAll(repo.getFeature());
    }
    Set<Feature> installedFeatures = new LinkedHashSet<>();
    // Add boot features for search
    allInstalledFeatures.addAll(allBootFeatures);
    for (String feature : installedEffective.getFeatures()) {
        addFeatures(allInstalledFeatures, feature, installedFeatures, true);
    }
    for (Feature feature : installedFeatures) {
        LOGGER.info("   Feature {} is defined as an installed feature", feature.getId());
        for (Bundle bundle : feature.getBundle()) {
            if (!ignoreDependencyFlag || !bundle.isDependency()) {
                installArtifact(downloader, bundle.getLocation().trim());
            }
        }
        // Install config files
        for (ConfigFile configFile : feature.getConfigfile()) {
            installArtifact(downloader, configFile.getLocation().trim());
        }
        for (Conditional cond : feature.getConditional()) {
            for (Bundle bundle : cond.getBundle()) {
                if (!ignoreDependencyFlag || !bundle.isDependency()) {
                    installArtifact(downloader, bundle.getLocation().trim());
                }
            }
        }
    }
    for (String location : installedEffective.getBundles()) {
        installArtifact(downloader, location);
    }
    downloader.await();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) Bundle(org.apache.karaf.features.internal.model.Bundle) Downloader(org.apache.karaf.features.internal.download.Downloader) Features(org.apache.karaf.features.internal.model.Features) Conditional(org.apache.karaf.features.internal.model.Conditional) Feature(org.apache.karaf.features.internal.model.Feature) Profile(org.apache.karaf.profile.Profile) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 25 with Feature

use of org.apache.karaf.features.internal.model.Feature in project karaf by apache.

the class Builder method bootStage.

private Set<Feature> bootStage(Profile bootProfile, Profile startupEffective) throws Exception {
    LOGGER.info("Boot stage");
    //
    // Handle boot profiles
    //
    Profile bootOverlay = Profiles.getOverlay(bootProfile, allProfiles, environment);
    Profile bootEffective = Profiles.getEffective(bootOverlay, false);
    // Load startup repositories
    Map<String, Features> bootRepositories = loadRepositories(manager, bootEffective.getRepositories(), true);
    // Compute startup feature dependencies
    Set<Feature> allBootFeatures = new HashSet<>();
    for (Features repo : bootRepositories.values()) {
        allBootFeatures.addAll(repo.getFeature());
    }
    // Generate a global feature
    Map<String, Dependency> generatedDep = new HashMap<>();
    Feature generated = new Feature();
    generated.setName(UUID.randomUUID().toString());
    // Add feature dependencies
    for (String dependency : bootEffective.getFeatures()) {
        Dependency dep = generatedDep.get(dependency);
        if (dep == null) {
            dep = createDependency(dependency);
            generated.getFeature().add(dep);
            generatedDep.put(dep.getName(), dep);
        }
        dep.setDependency(false);
    }
    // Add bundles
    for (String location : bootEffective.getBundles()) {
        location = location.replace("profile:", "file:etc/");
        Bundle bun = new Bundle();
        bun.setLocation(location);
        generated.getBundle().add(bun);
    }
    Features rep = new Features();
    rep.setName(UUID.randomUUID().toString());
    rep.getRepository().addAll(bootEffective.getRepositories());
    rep.getFeature().add(generated);
    allBootFeatures.add(generated);
    Downloader downloader = manager.createDownloader();
    // Compute startup feature dependencies
    Set<Feature> bootFeatures = new HashSet<>();
    addFeatures(allBootFeatures, generated.getName(), bootFeatures, true);
    for (Feature feature : bootFeatures) {
        // the feature is a startup feature, updating startup.properties file
        LOGGER.info("   Feature " + feature.getId() + " is defined as a boot feature");
        // add the feature in the system folder
        Set<String> locations = new HashSet<>();
        for (Bundle bundle : feature.getBundle()) {
            if (!ignoreDependencyFlag || !bundle.isDependency()) {
                locations.add(bundle.getLocation().trim());
            }
        }
        for (Conditional cond : feature.getConditional()) {
            for (Bundle bundle : cond.getBundle()) {
                if (!ignoreDependencyFlag || !bundle.isDependency()) {
                    locations.add(bundle.getLocation().trim());
                }
            }
        }
        // Build optional features and known prerequisites
        Map<String, List<String>> prereqs = new HashMap<>();
        prereqs.put("blueprint:", Arrays.asList("deployer", "aries-blueprint"));
        prereqs.put("spring:", Arrays.asList("deployer", "spring"));
        prereqs.put("wrap:", Arrays.asList("wrap"));
        prereqs.put("war:", Arrays.asList("war"));
        for (String location : locations) {
            installArtifact(downloader, location);
            for (Map.Entry<String, List<String>> entry : prereqs.entrySet()) {
                if (location.startsWith(entry.getKey())) {
                    for (String prereq : entry.getValue()) {
                        Dependency dep = generatedDep.get(prereq);
                        if (dep == null) {
                            dep = new Dependency();
                            dep.setName(prereq);
                            generated.getFeature().add(dep);
                            generatedDep.put(dep.getName(), dep);
                        }
                        dep.setPrerequisite(true);
                    }
                }
            }
        }
        List<Content> contents = new ArrayList<>();
        contents.add(feature);
        contents.addAll(feature.getConditional());
        for (Content content : contents) {
            // Install config files
            for (Config config : content.getConfig()) {
                if (config.isExternal()) {
                    installArtifact(downloader, config.getValue().trim());
                }
            }
            for (ConfigFile configFile : content.getConfigfile()) {
                installArtifact(downloader, configFile.getLocation().trim());
            }
            // Extract configs
            for (Config config : content.getConfig()) {
                if (pidMatching(config.getName())) {
                    Path configFile = etcDirectory.resolve(config.getName() + ".cfg");
                    LOGGER.info("      adding config file: {}", homeDirectory.relativize(configFile));
                    if (config.isExternal()) {
                        downloader.download(config.getValue().trim(), provider -> {
                            synchronized (provider) {
                                Files.copy(provider.getFile().toPath(), configFile, StandardCopyOption.REPLACE_EXISTING);
                            }
                        });
                    } else {
                        Files.write(configFile, config.getValue().getBytes());
                    }
                }
            }
        }
        // Install libraries
        List<String> libraries = new ArrayList<>();
        for (Library library : feature.getLibraries()) {
            String lib = library.getLocation() + ";type:=" + library.getType() + ";export:=" + library.isExport() + ";delegate:=" + library.isDelegate();
            libraries.add(lib);
        }
        Path configPropertiesPath = etcDirectory.resolve("config.properties");
        Properties configProperties = new Properties(configPropertiesPath.toFile());
        downloadLibraries(downloader, configProperties, libraries, "   ");
        downloader.await();
        // Reformat clauses
        reformatClauses(configProperties, Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
        reformatClauses(configProperties, Constants.FRAMEWORK_BOOTDELEGATION);
        configProperties.save();
    }
    // If there are bundles to install, we can't use the boot features only
    // so keep the generated feature
    Path featuresCfgFile = etcDirectory.resolve("org.apache.karaf.features.cfg");
    if (!generated.getBundle().isEmpty()) {
        File output = etcDirectory.resolve(rep.getName() + ".xml").toFile();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JaxbUtil.marshal(rep, baos);
        ByteArrayInputStream bais;
        String repoUrl;
        if (karafVersion == KarafVersion.v24) {
            String str = baos.toString();
            str = str.replace("http://karaf.apache.org/xmlns/features/v1.3.0", "http://karaf.apache.org/xmlns/features/v1.2.0");
            str = str.replaceAll(" dependency=\".*?\"", "");
            str = str.replaceAll(" prerequisite=\".*?\"", "");
            for (Feature f : rep.getFeature()) {
                for (Dependency d : f.getFeature()) {
                    if (d.isPrerequisite()) {
                        if (!startupEffective.getFeatures().contains(d.getName())) {
                            LOGGER.warn("Feature " + d.getName() + " is a prerequisite and should be installed as a startup feature.");
                        }
                    }
                }
            }
            bais = new ByteArrayInputStream(str.getBytes());
            repoUrl = "file:etc/" + output.getName();
        } else {
            bais = new ByteArrayInputStream(baos.toByteArray());
            repoUrl = "file:${karaf.home}/etc/" + output.getName();
        }
        Files.copy(bais, output.toPath());
        Properties featuresProperties = new Properties(featuresCfgFile.toFile());
        featuresProperties.put(FEATURES_REPOSITORIES, repoUrl);
        featuresProperties.put(FEATURES_BOOT, generated.getName());
        featuresProperties.save();
    } else {
        String repos = getRepos(rep);
        String boot = getBootFeatures(generatedDep);
        Properties featuresProperties = new Properties(featuresCfgFile.toFile());
        featuresProperties.put(FEATURES_REPOSITORIES, repos);
        featuresProperties.put(FEATURES_BOOT, boot);
        reformatClauses(featuresProperties, FEATURES_REPOSITORIES);
        reformatClauses(featuresProperties, FEATURES_BOOT);
        featuresProperties.save();
    }
    downloader.await();
    return allBootFeatures;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Config(org.apache.karaf.features.internal.model.Config) ArrayList(java.util.ArrayList) Downloader(org.apache.karaf.features.internal.download.Downloader) Conditional(org.apache.karaf.features.internal.model.Conditional) Properties(org.apache.felix.utils.properties.Properties) Feature(org.apache.karaf.features.internal.model.Feature) Profile(org.apache.karaf.profile.Profile) Features(org.apache.karaf.features.internal.model.Features) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) Bundle(org.apache.karaf.features.internal.model.Bundle) Dependency(org.apache.karaf.features.internal.model.Dependency) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Content(org.apache.karaf.features.internal.model.Content) Library(org.apache.karaf.features.Library) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) File(java.io.File)

Aggregations

Feature (org.apache.karaf.features.internal.model.Feature)25 Features (org.apache.karaf.features.internal.model.Features)16 ArrayList (java.util.ArrayList)10 Bundle (org.apache.karaf.features.internal.model.Bundle)9 ConfigFile (org.apache.karaf.features.internal.model.ConfigFile)8 HashMap (java.util.HashMap)7 Downloader (org.apache.karaf.features.internal.download.Downloader)6 Dependency (org.apache.karaf.features.internal.model.Dependency)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)6 IOException (java.io.IOException)5 HashSet (java.util.HashSet)5 File (java.io.File)4 URL (java.net.URL)4 LinkedHashSet (java.util.LinkedHashSet)4 Properties (org.apache.felix.utils.properties.Properties)4 Conditional (org.apache.karaf.features.internal.model.Conditional)4 Profile (org.apache.karaf.profile.Profile)4 Test (org.junit.Test)4 Hashtable (java.util.Hashtable)3 LinkedHashMap (java.util.LinkedHashMap)3