Search in sources :

Example 1 with ConfigFile

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

the class AbstractFeatureMojo method resolveFeatures.

protected Set<Feature> resolveFeatures() throws MojoExecutionException {
    Set<Feature> featuresSet = new HashSet<>();
    try {
        Set<String> artifactsToCopy = new HashSet<>();
        Map<String, Feature> featuresMap = new HashMap<>();
        for (String uri : descriptors) {
            retrieveDescriptorsRecursively(uri, artifactsToCopy, featuresMap);
        }
        // no features specified, handle all of them
        if (features == null) {
            features = new ArrayList<>(featuresMap.keySet());
        }
        addFeatures(features, featuresSet, featuresMap, addTransitiveFeatures);
        getLog().info("Using local repository at: " + localRepo.getUrl());
        for (Feature feature : featuresSet) {
            try {
                for (Bundle bundle : feature.getBundle()) {
                    resolveArtifact(bundle.getLocation());
                }
                for (Conditional conditional : feature.getConditional()) {
                    for (BundleInfo bundle : conditional.getBundles()) {
                        if (ignoreDependencyFlag || (!ignoreDependencyFlag && !bundle.isDependency())) {
                            resolveArtifact(bundle.getLocation());
                        }
                    }
                }
                for (ConfigFile configfile : feature.getConfigfile()) {
                    resolveArtifact(configfile.getLocation());
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("Error resolving feature " + feature.getName() + "/" + feature.getVersion(), e);
            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error populating repository", e);
    }
    return featuresSet;
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) Bundle(org.apache.karaf.features.internal.model.Bundle) Conditional(org.apache.karaf.features.Conditional) Feature(org.apache.karaf.features.internal.model.Feature) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) BundleInfo(org.apache.karaf.features.BundleInfo) HashSet(java.util.HashSet)

Example 2 with ConfigFile

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

the class AddToRepositoryMojo method copyConfigFilesToDestRepository.

private void copyConfigFilesToDestRepository(List<? extends ConfigFile> artifactRefs) throws MojoExecutionException {
    for (ConfigFile artifactRef : artifactRefs) {
        Artifact artifact = resourceToArtifact(artifactRef.getLocation(), skipNonMavenProtocols);
        // Avoid getting NPE on artifact.getFile in some cases
        resolveArtifact(artifact, remoteRepos);
        if (artifact != null) {
            copy(artifact, repository);
        }
    }
}
Also used : ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) Artifact(org.apache.maven.artifact.Artifact)

Example 3 with ConfigFile

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

the class VerifyMojo method doExecute.

protected void doExecute() throws MojoExecutionException, MojoFailureException {
    System.setProperty("karaf.home", "target/karaf");
    System.setProperty("karaf.data", "target/karaf/data");
    Hashtable<String, String> properties = new Hashtable<>();
    if (additionalMetadata != null) {
        try (Reader reader = new FileReader(additionalMetadata)) {
            Properties metadata = new Properties();
            metadata.load(reader);
            for (Enumeration<?> e = metadata.propertyNames(); e.hasMoreElements(); ) {
                Object key = e.nextElement();
                Object val = metadata.get(key);
                properties.put(key.toString(), val.toString());
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Unable to load additional metadata from " + additionalMetadata, e);
        }
    }
    Set<String> allDescriptors = new LinkedHashSet<>();
    if (descriptors == null) {
        if (framework == null) {
            framework = Collections.singleton("framework");
        }
        descriptors = new LinkedHashSet<>();
        if (framework.contains("framework")) {
            allDescriptors.add("mvn:org.apache.karaf.features/framework/" + getVersion("org.apache.karaf.features:framework") + "/xml/features");
        }
        allDescriptors.add("file:" + project.getBuild().getDirectory() + "/feature/feature.xml");
    } else {
        allDescriptors.addAll(descriptors);
        if (framework != null && framework.contains("framework")) {
            allDescriptors.add("mvn:org.apache.karaf.features/framework/" + getVersion("org.apache.karaf.features:framework") + "/xml/features");
        }
    }
    // TODO: allow using external configuration ?
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(8);
    DownloadManager manager = new CustomDownloadManager(resolver, executor);
    final Map<String, Features> repositories;
    Map<String, List<Feature>> allFeatures = new HashMap<>();
    try {
        repositories = loadRepositories(manager, allDescriptors);
        for (String repoUri : repositories.keySet()) {
            List<Feature> features = repositories.get(repoUri).getFeature();
            // Ack features to inline configuration files urls
            for (Feature feature : features) {
                for (org.apache.karaf.features.internal.model.Bundle bi : feature.getBundle()) {
                    String loc = bi.getLocation();
                    String nloc = null;
                    if (loc.contains("file:")) {
                        for (ConfigFile cfi : feature.getConfigfile()) {
                            if (cfi.getFinalname().substring(1).equals(loc.substring(loc.indexOf("file:") + "file:".length()))) {
                                nloc = cfi.getLocation();
                            }
                        }
                    }
                    if (nloc != null) {
                        Field field = bi.getClass().getDeclaredField("location");
                        field.setAccessible(true);
                        field.set(bi, loc.substring(0, loc.indexOf("file:")) + nloc);
                    }
                }
            }
            allFeatures.put(repoUri, features);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to load features descriptors", e);
    }
    List<Feature> featuresToTest = new ArrayList<>();
    if (verifyTransitive) {
        for (List<Feature> features : allFeatures.values()) {
            featuresToTest.addAll(features);
        }
    } else {
        for (String uri : descriptors) {
            featuresToTest.addAll(allFeatures.get(uri));
        }
    }
    if (features != null && !features.isEmpty()) {
        Pattern pattern = getPattern(features);
        for (Iterator<Feature> iterator = featuresToTest.iterator(); iterator.hasNext(); ) {
            Feature feature = iterator.next();
            String id = feature.getName() + "/" + feature.getVersion();
            if (!pattern.matcher(id).matches()) {
                iterator.remove();
            }
        }
    }
    for (String fmk : framework) {
        properties.put("feature.framework." + fmk, fmk);
    }
    List<Exception> failures = new ArrayList<>();
    for (Feature feature : featuresToTest) {
        try {
            String id = feature.getName() + "/" + feature.getVersion();
            verifyResolution(new CustomDownloadManager(resolver, executor), repositories, Collections.singleton(id), properties);
            getLog().info("Verification of feature " + id + " succeeded");
        } catch (Exception e) {
            if (e.getCause() instanceof ResolutionException) {
                getLog().warn(e.getMessage());
            } else {
                getLog().warn(e);
            }
            failures.add(e);
            if ("first".equals(fail)) {
                throw e;
            }
        }
        for (Conditional cond : feature.getConditional()) {
            Set<String> ids = new LinkedHashSet<>();
            ids.add(feature.getId());
            ids.addAll(cond.getCondition());
            try {
                verifyResolution(manager, repositories, ids, properties);
                getLog().info("Verification of feature " + ids + " succeeded");
            } catch (Exception e) {
                if (ignoreMissingConditions && e.getCause() instanceof ResolutionException) {
                    boolean ignore = true;
                    Collection<Requirement> requirements = ((ResolutionException) e.getCause()).getUnresolvedRequirements();
                    for (Requirement req : requirements) {
                        ignore &= (IdentityNamespace.IDENTITY_NAMESPACE.equals(req.getNamespace()) && ResourceUtils.TYPE_FEATURE.equals(req.getAttributes().get("type")) && cond.getCondition().contains(req.getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE).toString()));
                    }
                    if (ignore) {
                        getLog().warn("Feature resolution failed for " + ids + "\nMessage: " + e.getCause().getMessage());
                        continue;
                    }
                }
                if (e.getCause() instanceof ResolutionException) {
                    getLog().warn(e.getMessage());
                } else {
                    getLog().warn(e);
                }
                failures.add(e);
                if ("first".equals(fail)) {
                    throw e;
                }
            }
        }
    }
    if ("end".equals(fail) && !failures.isEmpty()) {
        throw new MojoExecutionException("Verification failures", new MultiException("Verification failures", failures));
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Reader(java.io.Reader) FileReader(java.io.FileReader) Conditional(org.apache.karaf.features.internal.model.Conditional) Properties(java.util.Properties) CustomDownloadManager(org.apache.karaf.profile.assembly.CustomDownloadManager) DownloadManager(org.apache.karaf.features.internal.download.DownloadManager) Feature(org.apache.karaf.features.internal.model.Feature) Field(java.lang.reflect.Field) FileReader(java.io.FileReader) Features(org.apache.karaf.features.internal.model.Features) List(java.util.List) ArrayList(java.util.ArrayList) Pattern(java.util.regex.Pattern) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ConfigFile(org.apache.karaf.features.internal.model.ConfigFile) Hashtable(java.util.Hashtable) IOException(java.io.IOException) MultiException(org.apache.karaf.features.internal.util.MultiException) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ResolutionException(org.osgi.service.resolver.ResolutionException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ResolutionException(org.osgi.service.resolver.ResolutionException) BundleRequirement(org.osgi.framework.wiring.BundleRequirement) Requirement(org.osgi.resource.Requirement) Collection(java.util.Collection) CustomDownloadManager(org.apache.karaf.profile.assembly.CustomDownloadManager) MultiException(org.apache.karaf.features.internal.util.MultiException)

Example 4 with ConfigFile

use of org.apache.karaf.features.internal.model.ConfigFile 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 5 with ConfigFile

use of org.apache.karaf.features.internal.model.ConfigFile 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)

Aggregations

ConfigFile (org.apache.karaf.features.internal.model.ConfigFile)7 Feature (org.apache.karaf.features.internal.model.Feature)6 HashMap (java.util.HashMap)4 Bundle (org.apache.karaf.features.internal.model.Bundle)4 Features (org.apache.karaf.features.internal.model.Features)4 HashSet (java.util.HashSet)3 LinkedHashSet (java.util.LinkedHashSet)3 Downloader (org.apache.karaf.features.internal.download.Downloader)3 Conditional (org.apache.karaf.features.internal.model.Conditional)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 File (java.io.File)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Config (org.apache.karaf.features.internal.model.Config)2 Dependency (org.apache.karaf.features.internal.model.Dependency)2 Profile (org.apache.karaf.profile.Profile)2 MojoFailureException (org.apache.maven.plugin.MojoFailureException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1