Search in sources :

Example 11 with Artifact

use of org.apache.sling.provisioning.model.Artifact 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 12 with Artifact

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

the class AttachModelArchive method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Model model = ProjectHelper.getRawModel(this.project);
    if (usePomVariables) {
        model = ModelUtility.applyVariables(model, new PomVariableResolver(project));
    }
    if (usePomDependencies) {
        model = ModelUtility.applyArtifactVersions(model, new PomArtifactVersionResolver(project, allowUnresolvedPomDependencies));
    }
    // write the model archive
    final File outputFile = new File(this.project.getBuild().getDirectory() + File.separatorChar + modelArchiveName + "." + ModelArchiveWriter.DEFAULT_EXTENSION);
    outputFile.getParentFile().mkdirs();
    try (final FileOutputStream fos = new FileOutputStream(outputFile)) {
        // TODO provide base manifest
        final JarOutputStream jos = ModelArchiveWriter.write(fos, model, null, new ModelArchiveWriter.ArtifactProvider() {

            @Override
            public InputStream getInputStream(final Artifact artifact) throws IOException {
                try {
                    final org.apache.maven.artifact.Artifact a = ModelUtils.getArtifact(project, mavenSession, artifactHandlerManager, resolver, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), artifact.getClassifier());
                    return new FileInputStream(a.getFile());
                } catch (MojoExecutionException e) {
                    throw (IOException) new IOException("Unable to get artifact: " + artifact.toMvnUrl()).initCause(e);
                }
            }
        });
        // handle license etc.
        final File classesDir = new File(this.project.getBuild().getOutputDirectory());
        if (classesDir.exists()) {
            final File metaInfDir = new File(classesDir, "META-INF");
            for (final String name : new String[] { "LICENSE", "NOTICE", "DEPENDENCIES" }) {
                final File f = new File(metaInfDir, name);
                if (f.exists()) {
                    final JarEntry artifactEntry = new JarEntry("META-INF/" + name);
                    jos.putNextEntry(artifactEntry);
                    final byte[] buffer = new byte[8192];
                    try (final InputStream is = new FileInputStream(f)) {
                        int l = 0;
                        while ((l = is.read(buffer)) > 0) {
                            jos.write(buffer, 0, l);
                        }
                    }
                    jos.closeEntry();
                }
            }
        }
        jos.finish();
    } catch (final IOException e) {
        throw new MojoExecutionException("Unable to write model archive to " + outputFile + " : " + e.getMessage(), e);
    }
    // attach it as an additional artifact
    projectHelper.attachArtifact(project, ModelArchiveWriter.DEFAULT_EXTENSION, BuildConstants.CLASSIFIER_MAR, outputFile);
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ModelArchiveWriter(org.apache.sling.provisioning.model.io.ModelArchiveWriter) JarOutputStream(java.util.jar.JarOutputStream) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) Artifact(org.apache.sling.provisioning.model.Artifact) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) Model(org.apache.sling.provisioning.model.Model) File(java.io.File)

Example 13 with Artifact

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

the class ModelReader method readModel.

private Model readModel(final Reader reader) throws IOException {
    boolean global = true;
    lineNumberReader = new LineNumberReader(reader);
    String line;
    while ((line = lineNumberReader.readLine()) != null) {
        // trim the line
        line = line.trim();
        // ignore empty line
        if (line.isEmpty()) {
            if (this.mode == CATEGORY.ADDITIONAL) {
                if (this.additionalSection.getContents() == null) {
                    this.additionalSection.setContents(line);
                } else {
                    this.additionalSection.setContents(this.additionalSection.getContents() + '\n' + line);
                }
                continue;
            }
            checkConfig();
            continue;
        }
        // comment?
        if (line.startsWith("#")) {
            if (config != null) {
                configBuilder.append(line);
                configBuilder.append('\n');
                continue;
            }
            if (this.mode == CATEGORY.ADDITIONAL) {
                if (this.additionalSection.getContents() == null) {
                    this.additionalSection.setContents(line);
                } else {
                    this.additionalSection.setContents(this.additionalSection.getContents() + '\n' + line);
                }
                continue;
            }
            final String c = line.substring(1).trim();
            if (comment == null) {
                comment = c;
            } else {
                comment = comment + "\n" + c;
            }
            continue;
        }
        if (global) {
            global = false;
            if (!line.startsWith("[feature ")) {
                throw new IOException(exceptionPrefix + " Model file must start with a feature category.");
            }
        }
        if (line.startsWith("[")) {
            additionalSection = null;
            if (!line.endsWith("]")) {
                throw new IOException(exceptionPrefix + "Illegal category definition in line " + this.lineNumberReader.getLineNumber() + ": " + line);
            }
            int pos = 1;
            while (line.charAt(pos) != ']' && !Character.isWhitespace(line.charAt(pos))) {
                pos++;
            }
            final String category = line.substring(1, pos);
            CATEGORY found = null;
            for (CATEGORY c : CATEGORY.values()) {
                if (category.equals(c.name)) {
                    found = c;
                    break;
                }
            }
            if (found == null) {
                // additional section
                if (!category.startsWith(":")) {
                    throw new IOException(exceptionPrefix + "Unknown category in line " + this.lineNumberReader.getLineNumber() + ": " + category);
                }
                found = CATEGORY.ADDITIONAL;
            }
            this.mode = found;
            Map<String, String> parameters = Collections.emptyMap();
            if (line.charAt(pos) != ']') {
                final String parameterLine = line.substring(pos + 1, line.length() - 1).trim();
                parameters = parseParameters(parameterLine, this.mode.parameters);
            }
            switch(this.mode) {
                // this can never happen
                case NONE:
                    break;
                // this can never happen
                case CONFIG:
                    break;
                case FEATURE:
                    final String name = parameters.get("name");
                    if (name == null) {
                        throw new IOException(exceptionPrefix + "Feature name missing in line " + this.lineNumberReader.getLineNumber() + ": " + line);
                    }
                    if (model.getFeature(name) != null) {
                        throw new IOException(exceptionPrefix + "Duplicate feature in line " + this.lineNumberReader.getLineNumber() + ": " + line);
                    }
                    this.feature = model.getOrCreateFeature(name);
                    this.feature.setType(parameters.get("type"));
                    this.feature.setVersion(parameters.get("version"));
                    this.init(this.feature);
                    this.runMode = null;
                    this.artifactGroup = null;
                    break;
                case VARIABLES:
                    checkFeature();
                    this.init(this.feature.getVariables());
                    break;
                case SETTINGS:
                    checkFeature();
                    checkRunMode(parameters);
                    this.init(this.runMode.getSettings());
                    break;
                case ARTIFACTS:
                    checkFeature();
                    checkRunMode(parameters);
                    int startLevel = 0;
                    String level = parameters.get("startLevel");
                    if (level != null) {
                        try {
                            startLevel = Integer.valueOf(level);
                        } catch (final NumberFormatException nfe) {
                            throw new IOException(exceptionPrefix + "Invalid start level in line " + this.lineNumberReader.getLineNumber() + ": " + line + ":" + level);
                        }
                    }
                    if (this.runMode.getArtifactGroup(startLevel) != null) {
                        throw new IOException(exceptionPrefix + "Duplicate artifact group in line " + this.lineNumberReader.getLineNumber() + ": " + line);
                    }
                    this.artifactGroup = this.runMode.getOrCreateArtifactGroup(startLevel);
                    this.init(this.artifactGroup);
                    break;
                case CONFIGURATIONS:
                    checkFeature();
                    checkRunMode(parameters);
                    this.init(this.runMode.getConfigurations());
                    break;
                case ADDITIONAL:
                    checkFeature();
                    this.runMode = null;
                    this.artifactGroup = null;
                    this.additionalSection = new Section(category.substring(1));
                    this.init(this.additionalSection);
                    this.feature.getAdditionalSections().add(this.additionalSection);
                    this.additionalSection.getAttributes().putAll(parameters);
            }
        } else {
            switch(this.mode) {
                case NONE:
                    break;
                case VARIABLES:
                    final String[] vars = parseProperty(line);
                    feature.getVariables().put(vars[0], vars[1]);
                    break;
                case SETTINGS:
                    final String[] settings = parseProperty(line);
                    runMode.getSettings().put(settings[0], settings[1]);
                    break;
                case FEATURE:
                    this.runMode = this.feature.getOrCreateRunMode(null);
                    this.artifactGroup = this.runMode.getOrCreateArtifactGroup(0);
                // no break, we continue with ARTIFACT
                case ARTIFACTS:
                    String artifactUrl = line;
                    Map<String, String> parameters = Collections.emptyMap();
                    if (line.endsWith("]")) {
                        final int startPos = line.indexOf("[");
                        if (startPos != -1) {
                            artifactUrl = line.substring(0, startPos).trim();
                            parameters = parseParameters(line.substring(startPos + 1, line.length() - 1).trim(), null);
                        }
                    }
                    try {
                        final Artifact artifact = Artifact.fromMvnUrl("mvn:" + artifactUrl);
                        this.init(artifact);
                        this.artifactGroup.add(artifact);
                        artifact.getMetadata().putAll(parameters);
                    } catch (final IllegalArgumentException iae) {
                        throw new IOException(exceptionPrefix + iae.getMessage() + " in line " + this.lineNumberReader.getLineNumber(), iae);
                    }
                    break;
                case CONFIGURATIONS:
                    String configId = line;
                    Map<String, String> cfgPars = Collections.emptyMap();
                    if (line.endsWith("]")) {
                        final int startPos = line.indexOf("[");
                        if (startPos != -1) {
                            configId = line.substring(0, startPos).trim();
                            cfgPars = parseParameters(line.substring(startPos + 1, line.length() - 1).trim(), new String[] { "format", "mode" });
                        }
                    }
                    String format = cfgPars.get("format");
                    if (format != null) {
                        if (!ModelConstants.CFG_FORMAT_FELIX_CA.equals(format) && !ModelConstants.CFG_FORMAT_PROPERTIES.equals(format)) {
                            throw new IOException(exceptionPrefix + "Unknown format configuration parameter in line " + this.lineNumberReader.getLineNumber() + ": " + line);
                        }
                    } else {
                        format = ModelConstants.CFG_FORMAT_FELIX_CA;
                    }
                    String cfgMode = cfgPars.get("mode");
                    if (cfgMode != null) {
                        if (!ModelConstants.CFG_MODE_OVERWRITE.equals(cfgMode) && !ModelConstants.CFG_MODE_MERGE.equals(cfgMode)) {
                            throw new IOException(exceptionPrefix + "Unknown mode configuration parameter in line " + this.lineNumberReader.getLineNumber() + ": " + line);
                        }
                    } else {
                        cfgMode = ModelConstants.CFG_MODE_OVERWRITE;
                    }
                    final String pid;
                    final String factoryPid;
                    final int factoryPos = configId.indexOf('-');
                    if (factoryPos == -1) {
                        pid = configId;
                        factoryPid = null;
                    } else {
                        pid = configId.substring(factoryPos + 1);
                        factoryPid = configId.substring(0, factoryPos);
                    }
                    if (runMode.getConfiguration(pid, factoryPid) != null) {
                        throw new IOException(exceptionPrefix + "Duplicate configuration in line " + this.lineNumberReader.getLineNumber());
                    }
                    config = runMode.getOrCreateConfiguration(pid, factoryPid);
                    this.init(config);
                    config.getProperties().put(ModelConstants.CFG_UNPROCESSED_FORMAT, format);
                    config.getProperties().put(ModelConstants.CFG_UNPROCESSED_MODE, cfgMode);
                    configBuilder = new StringBuilder();
                    mode = CATEGORY.CONFIG;
                    break;
                case CONFIG:
                    configBuilder.append(line);
                    configBuilder.append('\n');
                    break;
                case ADDITIONAL:
                    if (this.additionalSection.getContents() == null) {
                        this.additionalSection.setContents(line);
                    } else {
                        this.additionalSection.setContents(this.additionalSection.getContents() + '\n' + line);
                    }
                    break;
            }
        }
    }
    checkConfig();
    if (comment != null) {
        throw new IOException(exceptionPrefix + "Comment not allowed at the end of file");
    }
    return model;
}
Also used : IOException(java.io.IOException) Section(org.apache.sling.provisioning.model.Section) Artifact(org.apache.sling.provisioning.model.Artifact) LineNumberReader(java.io.LineNumberReader)

Example 14 with Artifact

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

the class Launcher method getClasspathURLs.

/** Convert a Model feature to a set of URLs meant to setup
     *  an URLClassLoader.
     */
List<URL> getClasspathURLs(Model m, String featureName) throws MalformedURLException {
    final List<URL> result = new ArrayList<URL>();
    // Add all URLs from the special feature to our classpath
    final Feature f = m.getFeature(featureName);
    if (f == null) {
        log.warn("No {} feature found in provisioning model, nothing to add to our classpath", featureName);
    } else {
        for (RunMode rm : f.getRunModes()) {
            for (ArtifactGroup g : rm.getArtifactGroups()) {
                for (Artifact a : g) {
                    final String url = MavenResolver.mvnUrl(a);
                    try {
                        result.add(new URL(url));
                    } catch (MalformedURLException e) {
                        final MalformedURLException up = new MalformedURLException("Invalid URL [" + url + "]");
                        up.initCause(e);
                        throw up;
                    }
                }
            }
        }
    }
    return result;
}
Also used : MalformedURLException(java.net.MalformedURLException) RunMode(org.apache.sling.provisioning.model.RunMode) ArrayList(java.util.ArrayList) Feature(org.apache.sling.provisioning.model.Feature) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) URL(java.net.URL) Artifact(org.apache.sling.provisioning.model.Artifact)

Aggregations

Artifact (org.apache.sling.provisioning.model.Artifact)14 IOException (java.io.IOException)8 Model (org.apache.sling.provisioning.model.Model)7 File (java.io.File)6 Feature (org.apache.sling.provisioning.model.Feature)6 InputStream (java.io.InputStream)5 ArtifactGroup (org.apache.sling.provisioning.model.ArtifactGroup)5 RunMode (org.apache.sling.provisioning.model.RunMode)5 Map (java.util.Map)4 Traceable (org.apache.sling.provisioning.model.Traceable)4 ModelReader (org.apache.sling.provisioning.model.io.ModelReader)4 InputStreamReader (java.io.InputStreamReader)3 Reader (java.io.Reader)3 HashMap (java.util.HashMap)3 JarEntry (java.util.jar.JarEntry)3 Section (org.apache.sling.provisioning.model.Section)3 Sets (com.google.common.collect.Sets)2 BufferedReader (java.io.BufferedReader)2 StringReader (java.io.StringReader)2 StringWriter (java.io.StringWriter)2