Search in sources :

Example 76 with Properties

use of org.apache.felix.utils.properties.Properties in project karaf by apache.

the class PropertiesLoader method loadSystemProperties.

/**
 * <p>
 * Loads the properties in the system property file associated with the
 * framework installation into <tt>System.setProperty()</tt>. These properties
 * are not directly used by the framework in anyway. By default, the system
 * property file is located in the <tt>conf/</tt> directory of the Felix
 * installation directory and is called "<tt>system.properties</tt>". The
 * installation directory of Felix is assumed to be the parent directory of
 * the <tt>felix.jar</tt> file as found on the system class path property.
 * The precise file from which to load system properties can be set by
 * initializing the "<tt>felix.system.properties</tt>" system property to an
 * arbitrary URL.
 * </p>
 *
 * @param file the Karaf base folder.
 * @throws IOException if the system file can't be loaded.
 */
public static void loadSystemProperties(File file) throws IOException {
    Properties props = null;
    try {
        URL configPropURL = file.toURI().toURL();
        props = loadPropertiesFile(configPropURL, true);
    } catch (Exception ex) {
        // Ignore
        return;
    }
    InterpolationHelper.SubstitutionCallback callback = new InterpolationHelper.BundleContextSubstitutionCallback(null);
    for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements(); ) {
        String name = (String) e.nextElement();
        if (name.startsWith(OVERRIDE_PREFIX)) {
            String overrideName = name.substring(OVERRIDE_PREFIX.length());
            String value = props.getProperty(name);
            System.setProperty(overrideName, substVars(value, name, null, props, callback));
        } else {
            String value = System.getProperty(name, props.getProperty(name));
            System.setProperty(name, substVars(value, name, null, props, callback));
        }
    }
}
Also used : InterpolationHelper(org.apache.felix.utils.properties.InterpolationHelper) Properties(org.apache.felix.utils.properties.Properties) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 77 with Properties

use of org.apache.felix.utils.properties.Properties 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) IOException(java.io.IOException)

Example 78 with Properties

use of org.apache.felix.utils.properties.Properties in project karaf by apache.

the class Builder method bootStage.

private Set<Feature> bootStage(Profile bootProfile, Profile startupEffective, FeaturesProcessor processor) 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
    LOGGER.info("   Loading boot repositories");
    Map<String, Features> bootRepositories = loadRepositories(manager, bootEffective.getRepositories(), true, processor);
    // 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 nameOrPattern : bootEffective.getFeatures()) {
        // KARAF-5273: feature may be a pattern
        for (String dependency : FeatureSelector.getMatchingFeatures(nameOrPattern, bootRepositories.values())) {
            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
    FeatureSelector selector = new FeatureSelector(allBootFeatures);
    Set<Feature> bootFeatures = selector.getMatching(singletonList(generated.getName()));
    for (Feature feature : bootFeatures) {
        if (feature.isBlacklisted()) {
            LOGGER.info("   Feature " + feature.getId() + " is blacklisted, ignoring");
            continue;
        }
        LOGGER.info("   Feature " + feature.getId() + " is defined as a boot feature");
        // add the feature in the system folder
        Set<BundleInfo> bundleInfos = new HashSet<>();
        for (Bundle bundle : feature.getBundle()) {
            if (!ignoreDependencyFlag || !bundle.isDependency()) {
                bundleInfos.add(bundle);
            }
        }
        for (Conditional cond : feature.getConditional()) {
            if (cond.isBlacklisted()) {
                LOGGER.info("   Conditionial " + cond.getConditionId() + " is blacklisted, ignoring");
            }
            for (Bundle bundle : cond.getBundle()) {
                if (!ignoreDependencyFlag || !bundle.isDependency()) {
                    bundleInfos.add(bundle);
                }
            }
        }
        // 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:", Collections.singletonList("wrap"));
        prereqs.put("war:", Collections.singletonList("war"));
        ArtifactInstaller installer = new ArtifactInstaller(systemDirectory, downloader, blacklist);
        for (BundleInfo bundleInfo : bundleInfos) {
            installer.installArtifact(bundleInfo);
            for (Map.Entry<String, List<String>> entry : prereqs.entrySet()) {
                if (bundleInfo.getLocation().trim().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);
                    }
                }
            }
        }
        new ConfigInstaller(etcDirectory, pidsToExtract).installConfigs(feature, downloader, installer);
        // 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) 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) BundleInfo(org.apache.karaf.features.BundleInfo) Features(org.apache.karaf.features.internal.model.Features) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Path(java.nio.file.Path) Bundle(org.apache.karaf.features.internal.model.Bundle) Dependency(org.apache.karaf.features.internal.model.Dependency) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) 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)

Example 79 with Properties

use of org.apache.felix.utils.properties.Properties in project karaf by apache.

the class Builder method startupStage.

private Profile startupStage(Profile startupProfile, FeaturesProcessor processor) throws Exception {
    LOGGER.info("Startup stage");
    // 
    // Compute startup
    // 
    Profile startupOverlay = Profiles.getOverlay(startupProfile, allProfiles, environment);
    Profile startupEffective = Profiles.getEffective(startupOverlay, false);
    // Load startup repositories
    LOGGER.info("   Loading startup repositories");
    Map<String, Features> startupRepositories = loadRepositories(manager, startupEffective.getRepositories(), false, processor);
    // 
    // Resolve
    // 
    LOGGER.info("   Resolving startup features and bundles");
    LOGGER.info("      Features: " + startupEffective.getFeatures().stream().collect(Collectors.joining(", ")));
    LOGGER.info("      Bundles: " + startupEffective.getBundles().stream().collect(Collectors.joining(", ")));
    Map<String, Integer> bundles = resolve(manager, resolver, startupRepositories.values(), startupEffective.getFeatures(), startupEffective.getBundles(), startupEffective.getOptionals(), processor);
    // 
    // Generate startup.properties
    // 
    Properties startup = new Properties();
    startup.setHeader(Collections.singletonList("# Bundles to be started on startup, with startlevel"));
    Map<Integer, Set<String>> invertedStartupBundles = MapUtils.invert(bundles);
    for (Map.Entry<Integer, Set<String>> entry : new TreeMap<>(invertedStartupBundles).entrySet()) {
        String startLevel = Integer.toString(entry.getKey());
        for (String location : new TreeSet<>(entry.getValue())) {
            if (useReferenceUrls) {
                if (location.startsWith("mvn:")) {
                    location = "file:" + Parser.pathFromMaven(location);
                }
                if (location.startsWith("file:")) {
                    location = "reference:" + location;
                }
            }
            if (location.startsWith("file:") && karafVersion == KarafVersion.v24) {
                location = location.substring("file:".length());
            }
            startup.put(location, startLevel);
        }
    }
    Path startupProperties = etcDirectory.resolve("startup.properties");
    startup.save(startupProperties.toFile());
    return startupEffective;
}
Also used : Path(java.nio.file.Path) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Properties(org.apache.felix.utils.properties.Properties) Profile(org.apache.karaf.profile.Profile) TreeSet(java.util.TreeSet) Features(org.apache.karaf.features.internal.model.Features) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 80 with Properties

use of org.apache.felix.utils.properties.Properties in project karaf by apache.

the class Builder method getSystemBundle.

/**
 * Prepares {@link BundleRevision} that represents System Bundle (a.k.a. <em>bundle 0</em>)
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
private BundleRevision getSystemBundle() throws Exception {
    Path configPropPath = etcDirectory.resolve("config.properties");
    Properties configProps = PropertiesLoader.loadPropertiesOrFail(configPropPath.toFile());
    configProps.put("java.specification.version", javase.version);
    configProps.substitute();
    Attributes attributes = new Attributes();
    attributes.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
    attributes.putValue(Constants.BUNDLE_SYMBOLICNAME, "system.bundle");
    attributes.putValue(Constants.BUNDLE_VERSION, "0.0.0");
    String exportPackages = configProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES, "");
    if ("".equals(exportPackages.trim())) {
        throw new IllegalArgumentException("\"org.osgi.framework.system.packages\" property should specify system bundle" + " packages. It can't be empty, please check etc/config.properties of the assembly.");
    }
    if (configProps.containsKey(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA)) {
        exportPackages += "," + configProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
    }
    exportPackages = exportPackages.replaceAll(",\\s*,", ",");
    attributes.putValue(Constants.EXPORT_PACKAGE, exportPackages);
    String systemCaps = configProps.getProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES, "");
    attributes.putValue(Constants.PROVIDE_CAPABILITY, systemCaps);
    final Hashtable<String, String> headers = new Hashtable<>();
    for (Map.Entry attr : attributes.entrySet()) {
        headers.put(attr.getKey().toString(), attr.getValue().toString());
    }
    return new FakeBundleRevision(headers, "system-bundle", 0L);
}
Also used : Path(java.nio.file.Path) Hashtable(java.util.Hashtable) Attributes(java.util.jar.Attributes) Properties(org.apache.felix.utils.properties.Properties) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Aggregations

Properties (org.apache.felix.utils.properties.Properties)95 IOException (java.io.IOException)35 File (java.io.File)33 Test (org.junit.Test)27 Subject (javax.security.auth.Subject)25 NamePasswordCallbackHandler (org.apache.karaf.jaas.modules.NamePasswordCallbackHandler)21 Path (java.nio.file.Path)13 HashMap (java.util.HashMap)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)9 FileInputStream (java.io.FileInputStream)8 URL (java.net.URL)8 MalformedURLException (java.net.MalformedURLException)7 HashSet (java.util.HashSet)6 Hashtable (java.util.Hashtable)6 LinkedHashMap (java.util.LinkedHashMap)6 TreeMap (java.util.TreeMap)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 FileNotFoundException (java.io.FileNotFoundException)5 LoginException (javax.security.auth.login.LoginException)5