Search in sources :

Example 6 with ArtifactGroup

use of org.apache.sling.provisioning.model.ArtifactGroup in project sling by apache.

the class ModelArchiveWriter method write.

/**
     * Create a model archive.
     * The output stream will not be closed by this method. The caller
     * must call {@link JarOutputStream#close()} or {@link JarOutputStream#finish()}
     * on the return output stream. The caller can add additional files through
     * the return stream.
     *
     * In order to create an archive for a model, each feature in the model must
     * have a name and a version and the model must be valid, therefore {@link ModelUtility#validateIncludingVersion(Model)}
     * is called first. If the model is invalid an {@code IOException} is thrown.
     *
     * @param out The output stream to write to
     * @param model The model to write
     * @param baseManifest Optional base manifest used for creating the manifest.
     * @param provider The artifact provider
     * @return The jar output stream.
     * @throws IOException If anything goes wrong
     */
public static JarOutputStream write(final OutputStream out, final Model model, final Manifest baseManifest, final ArtifactProvider provider) throws IOException {
    // check model
    final Map<Traceable, String> errors = ModelUtility.validate(model);
    if (errors != null) {
        throw new IOException("Model is not valid: " + errors);
    }
    // create manifest
    final Manifest manifest = (baseManifest == null ? new Manifest() : new Manifest(baseManifest));
    manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
    manifest.getMainAttributes().putValue(MANIFEST_HEADER, String.valueOf(ARCHIVE_VERSION));
    // create archive
    final JarOutputStream jos = new JarOutputStream(out, manifest);
    // write model first
    final JarEntry entry = new JarEntry(MODEL_NAME);
    jos.putNextEntry(entry);
    final Writer writer = new OutputStreamWriter(jos, "UTF-8");
    ModelWriter.write(writer, model);
    writer.flush();
    jos.closeEntry();
    final byte[] buffer = new byte[1024 * 1024 * 256];
    for (final Feature f : model.getFeatures()) {
        for (final RunMode rm : f.getRunModes()) {
            for (final ArtifactGroup g : rm.getArtifactGroups()) {
                for (final Artifact a : g) {
                    final JarEntry artifactEntry = new JarEntry(ARTIFACTS_PREFIX + a.getRepositoryPath());
                    jos.putNextEntry(artifactEntry);
                    try (final InputStream is = provider.getInputStream(a)) {
                        int l = 0;
                        while ((l = is.read(buffer)) > 0) {
                            jos.write(buffer, 0, l);
                        }
                    }
                    jos.closeEntry();
                }
            }
        }
    }
    return jos;
}
Also used : InputStream(java.io.InputStream) JarOutputStream(java.util.jar.JarOutputStream) IOException(java.io.IOException) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) Feature(org.apache.sling.provisioning.model.Feature) Artifact(org.apache.sling.provisioning.model.Artifact) RunMode(org.apache.sling.provisioning.model.RunMode) OutputStreamWriter(java.io.OutputStreamWriter) Traceable(org.apache.sling.provisioning.model.Traceable) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 7 with ArtifactGroup

use of org.apache.sling.provisioning.model.ArtifactGroup in project sling by apache.

the class ModelWriter method write.

/**
     * Writes the model to the writer.
     * The writer is not closed.
     * @param writer Writer
     * @param model Model
     * @throws IOException
     */
public static void write(final Writer writer, final Model model) throws IOException {
    final PrintWriter pw = new PrintWriter(writer);
    boolean firstFeature = true;
    // features
    for (final Feature feature : model.getFeatures()) {
        if (firstFeature) {
            firstFeature = false;
        } else {
            pw.println();
        }
        writeComment(pw, feature);
        pw.print("[feature name=");
        pw.print(feature.getName());
        if (!FeatureTypes.PLAIN.equals(feature.getType())) {
            pw.print(" type=");
            pw.print(feature.getType());
        }
        if (feature.getVersion() != null) {
            pw.print(" version=");
            pw.print(feature.getVersion());
        }
        pw.println("]");
        // variables
        if (!feature.getVariables().isEmpty()) {
            pw.println();
            writeComment(pw, feature.getVariables());
            pw.println("[variables]");
            for (final Map.Entry<String, String> entry : feature.getVariables()) {
                pw.print("  ");
                pw.print(entry.getKey());
                pw.print("=");
                pw.println(entry.getValue());
            }
        }
        // run modes
        for (final RunMode runMode : feature.getRunModes()) {
            // settings
            if (!runMode.getSettings().isEmpty()) {
                pw.println();
                writeComment(pw, runMode.getSettings());
                pw.print("[settings");
                writeRunMode(pw, runMode);
                pw.println("]");
                for (final Map.Entry<String, String> entry : runMode.getSettings()) {
                    pw.print("  ");
                    pw.print(entry.getKey());
                    pw.print("=");
                    pw.println(entry.getValue());
                }
            }
            // artifact groups
            for (final ArtifactGroup group : runMode.getArtifactGroups()) {
                // skip empty groups
                if (group.isEmpty()) {
                    continue;
                }
                pw.println();
                writeComment(pw, group);
                pw.print("[artifacts");
                if (group.getStartLevel() > 0) {
                    pw.print(" startLevel=");
                    pw.print(String.valueOf(group.getStartLevel()));
                }
                writeRunMode(pw, runMode);
                pw.println("]");
                // artifacts
                for (final Artifact ad : group) {
                    writeComment(pw, ad);
                    pw.print("  ");
                    pw.print(ad.toMvnUrl().substring(4));
                    if (!ad.getMetadata().isEmpty()) {
                        boolean first = true;
                        for (final Map.Entry<String, String> entry : ad.getMetadata().entrySet()) {
                            if (first) {
                                first = false;
                                pw.print(" [");
                            } else {
                                pw.print(", ");
                            }
                            pw.print(entry.getKey());
                            pw.print("=");
                            pw.print(entry.getValue());
                        }
                        pw.print("]");
                    }
                    pw.println();
                }
            }
            // configurations
            if (!runMode.getConfigurations().isEmpty()) {
                pw.println();
                writeComment(pw, runMode.getConfigurations());
                pw.print("[configurations");
                writeRunMode(pw, runMode);
                pw.println("]");
                boolean firstConfig = true;
                for (final Configuration config : runMode.getConfigurations()) {
                    if (firstConfig) {
                        firstConfig = false;
                    } else {
                        pw.println();
                    }
                    writeComment(pw, config);
                    final String raw = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED);
                    String format = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED_FORMAT);
                    if (format == null) {
                        format = ModelConstants.CFG_FORMAT_FELIX_CA;
                    }
                    String cfgMode = (String) config.getProperties().get(ModelConstants.CFG_UNPROCESSED_MODE);
                    if (cfgMode == null) {
                        cfgMode = ModelConstants.CFG_MODE_OVERWRITE;
                    }
                    pw.print("  ");
                    if (config.getFactoryPid() != null) {
                        pw.print(config.getFactoryPid());
                        pw.print("-");
                    }
                    pw.print(config.getPid());
                    final boolean isDefaultFormat = ModelConstants.CFG_FORMAT_FELIX_CA.equals(format);
                    final boolean isDefaultMode = ModelConstants.CFG_MODE_OVERWRITE.equals(cfgMode);
                    if (!isDefaultFormat || !isDefaultMode) {
                        pw.print(" [");
                        if (!isDefaultFormat) {
                            pw.print("format=");
                            pw.print(format);
                            if (!isDefaultMode) {
                                pw.print(",");
                            }
                        }
                        if (!isDefaultMode) {
                            pw.print("mode=");
                            pw.print(cfgMode);
                        }
                        pw.print("]");
                    }
                    pw.println();
                    final String configString;
                    if (raw != null) {
                        configString = raw;
                    } else if (config.isSpecial()) {
                        configString = config.getProperties().get(config.getPid()).toString();
                    } else {
                        final ByteArrayOutputStream os = new ByteArrayOutputStream();
                        try {
                            ConfigurationHandler.write(os, config.getProperties());
                        } finally {
                            os.close();
                        }
                        configString = new String(os.toByteArray(), "UTF-8");
                    }
                    // we have to read the configuration line by line to properly indent
                    final LineNumberReader lnr = new LineNumberReader(new StringReader(configString));
                    String line = null;
                    while ((line = lnr.readLine()) != null) {
                        if (line.trim().isEmpty()) {
                            continue;
                        }
                        pw.print("    ");
                        pw.println(line.trim());
                    }
                }
            }
        }
        // additional sections
        for (final Section section : feature.getAdditionalSections()) {
            pw.println();
            pw.print("  [:");
            pw.print(section.getName());
            for (final Map.Entry<String, String> entry : section.getAttributes().entrySet()) {
                pw.print(' ');
                pw.print(entry.getKey());
                pw.print('=');
                pw.print(entry.getValue());
            }
            pw.println("]");
            if (section.getContents() != null) {
                pw.println(section.getContents());
            }
        }
    }
}
Also used : Configuration(org.apache.sling.provisioning.model.Configuration) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Feature(org.apache.sling.provisioning.model.Feature) Section(org.apache.sling.provisioning.model.Section) Artifact(org.apache.sling.provisioning.model.Artifact) LineNumberReader(java.io.LineNumberReader) RunMode(org.apache.sling.provisioning.model.RunMode) StringReader(java.io.StringReader) Map(java.util.Map) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) PrintWriter(java.io.PrintWriter)

Example 8 with ArtifactGroup

use of org.apache.sling.provisioning.model.ArtifactGroup in project sling by apache.

the class ModelPreprocessor method searchSlingstartDependencies.

/**
     * Search for dependent slingstart/slingfeature artifacts and remove them from the effective model.
     * @throws MavenExecutionException
     */
private List<Model> searchSlingstartDependencies(final Environment env, final ProjectInfo info, final Model rawModel, final Model effectiveModel) throws MavenExecutionException {
    // slingstart or slingfeature
    final List<Model> dependencies = new ArrayList<>();
    for (final Feature feature : effectiveModel.getFeatures()) {
        for (final RunMode runMode : feature.getRunModes()) {
            for (final ArtifactGroup group : runMode.getArtifactGroups()) {
                final List<org.apache.sling.provisioning.model.Artifact> removeList = new ArrayList<>();
                for (final org.apache.sling.provisioning.model.Artifact a : group) {
                    if (a.getType().equals(BuildConstants.PACKAGING_SLINGSTART) || a.getType().equals(BuildConstants.PACKAGING_PARTIAL_SYSTEM)) {
                        final Dependency dep = new Dependency();
                        dep.setGroupId(a.getGroupId());
                        dep.setArtifactId(a.getArtifactId());
                        dep.setVersion(a.getVersion());
                        dep.setType(BuildConstants.PACKAGING_PARTIAL_SYSTEM);
                        if (a.getType().equals(BuildConstants.PACKAGING_SLINGSTART)) {
                            dep.setClassifier(BuildConstants.PACKAGING_PARTIAL_SYSTEM);
                        } else {
                            dep.setClassifier(a.getClassifier());
                        }
                        dep.setScope(Artifact.SCOPE_PROVIDED);
                        env.logger.debug("- adding dependency " + ModelUtils.toString(dep));
                        info.project.getDependencies().add(dep);
                        // if it's a project from the current reactor build, we can't resolve it right now
                        final String key = a.getGroupId() + ":" + a.getArtifactId();
                        final ProjectInfo depInfo = env.modelProjects.get(key);
                        if (depInfo != null) {
                            env.logger.debug("Found reactor " + a.getType() + " dependency : " + a);
                            final Model model = addDependencies(env, depInfo);
                            if (model == null) {
                                throw new MavenExecutionException("Recursive model dependency list including project " + info.project, (File) null);
                            }
                            dependencies.add(model);
                            info.includedModels.put(a, depInfo.localModel);
                        } else {
                            env.logger.debug("Found external " + a.getType() + " dependency: " + a);
                            // "external" dependency, we can already resolve it
                            final File modelFile = resolveSlingstartArtifact(env, info.project, dep);
                            FileReader r = null;
                            try {
                                r = new FileReader(modelFile);
                                final Model model = ModelReader.read(r, modelFile.getAbsolutePath());
                                info.includedModels.put(a, model);
                                final Map<Traceable, String> errors = ModelUtility.validate(model);
                                if (errors != null) {
                                    throw new MavenExecutionException("Unable to read model file from " + modelFile + " : " + errors, modelFile);
                                }
                                final Model fullModel = processSlingstartDependencies(env, info, dep, model);
                                dependencies.add(fullModel);
                            } catch (final IOException ioe) {
                                throw new MavenExecutionException("Unable to read model file from " + modelFile, ioe);
                            } finally {
                                try {
                                    if (r != null) {
                                        r.close();
                                    }
                                } catch (final IOException io) {
                                // ignore
                                }
                            }
                        }
                        removeList.add(a);
                    }
                }
                for (final org.apache.sling.provisioning.model.Artifact r : removeList) {
                    group.remove(r);
                    final Feature localModelFeature = rawModel.getFeature(feature.getName());
                    if (localModelFeature != null) {
                        final RunMode localRunMode = localModelFeature.getRunMode(runMode.getNames());
                        if (localRunMode != null) {
                            final ArtifactGroup localAG = localRunMode.getArtifactGroup(group.getStartLevel());
                            if (localAG != null) {
                                localAG.remove(r);
                            }
                        }
                    }
                }
            }
        }
    }
    return dependencies;
}
Also used : ArrayList(java.util.ArrayList) Dependency(org.apache.maven.model.Dependency) IOException(java.io.IOException) Feature(org.apache.sling.provisioning.model.Feature) Artifact(org.apache.maven.artifact.Artifact) DefaultArtifact(org.apache.maven.artifact.DefaultArtifact) MavenExecutionException(org.apache.maven.MavenExecutionException) RunMode(org.apache.sling.provisioning.model.RunMode) Model(org.apache.sling.provisioning.model.Model) FileReader(java.io.FileReader) Traceable(org.apache.sling.provisioning.model.Traceable) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) File(java.io.File)

Example 9 with ArtifactGroup

use of org.apache.sling.provisioning.model.ArtifactGroup in project sling by apache.

the class PreparePackageMojo method buildContentsMap.

/**
     * Build a list of all artifacts from this run mode
     */
private void buildContentsMap(final Model model, final RunMode runMode, final Map<String, File> contentsMap, final boolean isBoot) throws MojoExecutionException {
    for (final ArtifactGroup group : runMode.getArtifactGroups()) {
        for (final org.apache.sling.provisioning.model.Artifact a : group) {
            Artifact artifact = null;
            if (a.getGroupId().equals(this.project.getGroupId()) && a.getArtifactId().equals(this.project.getArtifactId()) && a.getVersion().equals(this.project.getVersion())) {
                for (final Artifact projectArtifact : this.project.getAttachedArtifacts()) {
                    if (projectArtifact.getClassifier().equals(a.getClassifier())) {
                        artifact = projectArtifact;
                        break;
                    }
                }
                // check if the artifact is bound already?
                if (project.getArtifact().getFile().exists()) {
                    if (a.getClassifier() != null) {
                        if (a.getClassifier().equals(project.getArtifact().getClassifier())) {
                            artifact = project.getArtifact();
                        } else {
                            throw new MojoExecutionException("Unable to find artifact from same project with the given classifier: " + a.toMvnUrl());
                        }
                    } else {
                        if (project.getArtifact().getClassifier() == null) {
                            artifact = project.getArtifact();
                        } else {
                            throw new MojoExecutionException("Unable to find artifact with no classifier from same project, because the main artifact is bound to classifier " + project.getArtifact().getClassifier());
                        }
                    }
                } else {
                    throw new MojoExecutionException("You must not reference artifact " + a.toMvnUrl() + " from the model which is not yet available in the phase '" + mojoExecution.getLifecyclePhase() + ". Make sure to execute this goal after phase 'package'");
                }
            } else {
                artifact = ModelUtils.getArtifact(this.project, this.mavenSession, this.artifactHandlerManager, this.resolver, a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getType(), a.getClassifier());
            }
            File artifactFile = artifact.getFile();
            String newBSN = a.getMetadata().get("bundle:rename-bsn");
            if (newBSN != null) {
                try {
                    getTmpDir().mkdirs();
                    artifactFile = new BSNRenamer(artifactFile, getTmpDir(), newBSN).process();
                } catch (IOException e) {
                    throw new MojoExecutionException("Unable to rename bundle BSN to " + newBSN + " for " + artifactFile, e);
                }
            }
            contentsMap.put(getPathForArtifact(group.getStartLevel(), artifactFile.getName(), runMode, isBoot), artifactFile);
        }
    }
    final File rootConfDir = new File(this.getTmpDir(), "global-config");
    boolean hasConfig = false;
    for (final Configuration config : runMode.getConfigurations()) {
        // skip special configurations
        if (config.isSpecial()) {
            continue;
        }
        final String configPath = getPathForConfiguration(config, runMode);
        final File configFile = new File(rootConfDir, configPath);
        getLog().debug(String.format("Creating configuration at %s", configFile.getPath()));
        configFile.getParentFile().mkdirs();
        try {
            final FileOutputStream os = new FileOutputStream(configFile);
            try {
                ConfigurationHandler.write(os, config.getProperties());
            } finally {
                os.close();
            }
        } catch (final IOException e) {
            throw new MojoExecutionException("Unable to write configuration to " + configFile, e);
        }
        hasConfig = true;
    }
    if (hasConfig) {
        contentsMap.put(BASE_DESTINATION, rootConfDir);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Configuration(org.apache.sling.provisioning.model.Configuration) IOException(java.io.IOException) Artifact(org.apache.maven.artifact.Artifact) FileOutputStream(java.io.FileOutputStream) BSNRenamer(org.apache.sling.commons.osgi.BSNRenamer) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) File(java.io.File)

Example 10 with ArtifactGroup

use of org.apache.sling.provisioning.model.ArtifactGroup in project sling by apache.

the class RepositoryMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    final File artifactDir = new File(this.project.getBuild().getDirectory(), DIR_NAME);
    this.getLog().info("Creating repository in '" + artifactDir.getPath() + "'...");
    // artifacts
    final Model model = ProjectHelper.getEffectiveModel(this.project, getResolverOptions());
    for (final Feature feature : model.getFeatures()) {
        for (final RunMode runMode : feature.getRunModes()) {
            for (final ArtifactGroup group : runMode.getArtifactGroups()) {
                for (final org.apache.sling.provisioning.model.Artifact artifact : group) {
                    copyArtifactToRepository(artifact, artifactDir);
                }
            }
        }
    }
    // base artifact - only if launchpad feature is available
    if (model.getFeature(ModelConstants.FEATURE_LAUNCHPAD) != null) {
        try {
            final org.apache.sling.provisioning.model.Artifact baseArtifact = ModelUtils.findBaseArtifact(model);
            final org.apache.sling.provisioning.model.Artifact appArtifact = new org.apache.sling.provisioning.model.Artifact(baseArtifact.getGroupId(), baseArtifact.getArtifactId(), baseArtifact.getVersion(), BuildConstants.CLASSIFIER_APP, BuildConstants.TYPE_JAR);
            copyArtifactToRepository(appArtifact, artifactDir);
        } catch (final MavenExecutionException mee) {
            throw new MojoExecutionException(mee.getMessage(), mee.getCause());
        }
    }
    // models
    Model rawModel = ProjectHelper.getRawModel(this.project);
    if (usePomVariables) {
        rawModel = ModelUtility.applyVariables(rawModel, new PomVariableResolver(project));
    }
    if (usePomDependencies) {
        rawModel = ModelUtility.applyArtifactVersions(rawModel, new PomArtifactVersionResolver(project, allowUnresolvedPomDependencies));
    }
    final String classifier = (project.getPackaging().equals(BuildConstants.PACKAGING_PARTIAL_SYSTEM) ? null : BuildConstants.PACKAGING_PARTIAL_SYSTEM);
    final org.apache.sling.provisioning.model.Artifact rawModelArtifact = new org.apache.sling.provisioning.model.Artifact(this.project.getGroupId(), this.project.getArtifactId(), this.project.getVersion(), classifier, BuildConstants.TYPE_TXT);
    final File rawModelFile = getRepositoryFile(artifactDir, rawModelArtifact);
    Writer writer = null;
    try {
        writer = new FileWriter(rawModelFile);
        ModelWriter.write(writer, rawModel);
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to write model to " + rawModelFile, e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
    // and write model to target
    writer = null;
    try {
        writer = new FileWriter(new File(this.project.getBuild().getDirectory(), repositoryModelName));
        ModelWriter.write(writer, rawModel);
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to write model to " + rawModelFile, e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
    for (final Map.Entry<String, String> entry : ProjectHelper.getDependencyModel(this.project).entrySet()) {
        final org.apache.sling.provisioning.model.Artifact modelDepArtifact = org.apache.sling.provisioning.model.Artifact.fromMvnUrl(entry.getKey());
        final String modelClassifier = (modelDepArtifact.getType().equals(BuildConstants.PACKAGING_SLINGSTART) ? BuildConstants.PACKAGING_PARTIAL_SYSTEM : modelDepArtifact.getClassifier());
        final org.apache.sling.provisioning.model.Artifact modelArtifact = new org.apache.sling.provisioning.model.Artifact(modelDepArtifact.getGroupId(), modelDepArtifact.getArtifactId(), modelDepArtifact.getVersion(), modelClassifier, BuildConstants.TYPE_TXT);
        final File modelFile = getRepositoryFile(artifactDir, modelArtifact);
        Writer modelWriter = null;
        try {
            modelWriter = new FileWriter(modelFile);
            modelWriter.write(entry.getValue());
        } catch (IOException e) {
            throw new MojoExecutionException("Unable to write model to " + modelFile, e);
        } finally {
            IOUtils.closeQuietly(modelWriter);
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileWriter(java.io.FileWriter) IOException(java.io.IOException) Feature(org.apache.sling.provisioning.model.Feature) Artifact(org.apache.maven.artifact.Artifact) MavenExecutionException(org.apache.maven.MavenExecutionException) RunMode(org.apache.sling.provisioning.model.RunMode) Model(org.apache.sling.provisioning.model.Model) File(java.io.File) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) Map(java.util.Map) FileWriter(java.io.FileWriter) ModelWriter(org.apache.sling.provisioning.model.io.ModelWriter) Writer(java.io.Writer)

Aggregations

ArtifactGroup (org.apache.sling.provisioning.model.ArtifactGroup)12 RunMode (org.apache.sling.provisioning.model.RunMode)11 Feature (org.apache.sling.provisioning.model.Feature)9 File (java.io.File)7 IOException (java.io.IOException)6 Artifact (org.apache.maven.artifact.Artifact)6 Artifact (org.apache.sling.provisioning.model.Artifact)5 Traceable (org.apache.sling.provisioning.model.Traceable)4 FileOutputStream (java.io.FileOutputStream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Manifest (java.util.jar.Manifest)3 MavenExecutionException (org.apache.maven.MavenExecutionException)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 Configuration (org.apache.sling.provisioning.model.Configuration)3 Model (org.apache.sling.provisioning.model.Model)3 InputStream (java.io.InputStream)2 StringReader (java.io.StringReader)2 Writer (java.io.Writer)2