Search in sources :

Example 1 with Section

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

the class PreparePackageMojo method createSubsystemManifest.

// This manifest will be used as the basis for the OSGI-INF/SUBSYSTEM.MF file when the real
// .esa file is generated. However since some contents of that file depend on the actual
// runmode that is being executed, additional information will be added to the SUBSYSTEM.MF
// file at startup time before it's finalized (example: Subsystem-Content).
private int createSubsystemManifest(Feature feature, Map<String, Integer> startOrderMap, ZipOutputStream os) throws IOException {
    int subsystemStartLevel = -1;
    ZipEntry ze = new ZipEntry("SUBSYSTEM-MANIFEST-BASE.MF");
    try {
        os.putNextEntry(ze);
        Manifest mf = new Manifest();
        Attributes attributes = mf.getMainAttributes();
        // Manifest does not work without this value
        attributes.putValue("Manifest-Version", "1.0");
        attributes.putValue("Subsystem-SymbolicName", feature.getName());
        // Version must be an integer (cannot be a long), TODO better idea?
        attributes.putValue("Subsystem-Version", "1");
        attributes.putValue("Subsystem-Type", feature.getType());
        for (Section section : feature.getAdditionalSections("subsystem-manifest")) {
            String sl = section.getAttributes().get("startLevel");
            try {
                subsystemStartLevel = Integer.parseInt(sl);
            } catch (NumberFormatException nfe) {
            // Not a valid start level
            }
            BufferedReader br = new BufferedReader(new StringReader(section.getContents()));
            String line = null;
            while ((line = br.readLine()) != null) {
                int idx = line.indexOf(':');
                if (idx > 0) {
                    String key = line.substring(0, idx);
                    String value;
                    idx++;
                    if (line.length() > idx)
                        value = line.substring(idx);
                    else
                        value = "";
                    attributes.putValue(key.trim(), value.trim());
                }
            }
        }
        mf.write(os);
    } finally {
        os.closeEntry();
    }
    return subsystemStartLevel;
}
Also used : ZipEntry(java.util.zip.ZipEntry) Attributes(java.util.jar.Attributes) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) Manifest(java.util.jar.Manifest) Section(org.apache.sling.provisioning.model.Section)

Example 2 with Section

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

the class InstallModelTask method collectArtifacts.

private Map<Traceable, String> collectArtifacts(final Model effectiveModel, final List<ArtifactDescription> files, final File baseDir) {
    final RepositoryAccess repo = new RepositoryAccess();
    final Map<Traceable, String> errors = new HashMap<>();
    for (final Feature f : effectiveModel.getFeatures()) {
        if (f.isSpecial()) {
            continue;
        }
        for (final Section section : f.getAdditionalSections()) {
            final ArtifactDescription desc = new ArtifactDescription();
            desc.section = section;
            files.add(desc);
        }
        for (final RunMode mode : f.getRunModes()) {
            if (mode.isSpecial()) {
                continue;
            }
            if (mode.isActive(this.activeRunModes)) {
                for (final ArtifactGroup group : mode.getArtifactGroups()) {
                    for (final Artifact artifact : group) {
                        File file = (baseDir == null ? null : new File(baseDir, artifact.getRepositoryPath().replace('/', File.separatorChar)));
                        if (file == null || !file.exists()) {
                            file = repo.get(artifact);
                        }
                        if (file == null) {
                            errors.put(artifact, "Artifact " + artifact.toMvnUrl() + " not found.");
                        } else {
                            final ArtifactDescription desc = new ArtifactDescription();
                            desc.artifactFile = file;
                            desc.startLevel = group.getStartLevel();
                            files.add(desc);
                        }
                    }
                }
                for (final Configuration cfg : mode.getConfigurations()) {
                    if (cfg.isSpecial()) {
                        continue;
                    }
                    final ArtifactDescription desc = new ArtifactDescription();
                    desc.cfg = cfg;
                    files.add(desc);
                }
            }
        }
    }
    return errors.isEmpty() ? null : errors;
}
Also used : Configuration(org.apache.sling.provisioning.model.Configuration) HashMap(java.util.HashMap) Feature(org.apache.sling.provisioning.model.Feature) Section(org.apache.sling.provisioning.model.Section) Artifact(org.apache.sling.provisioning.model.Artifact) RunMode(org.apache.sling.provisioning.model.RunMode) Traceable(org.apache.sling.provisioning.model.Traceable) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) File(java.io.File)

Example 3 with Section

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

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

the class RepoinitTextProvider method extractFromModel.

private String extractFromModel(String sourceInfo, String rawText, String modelSection) throws IOException {
    final StringReader reader = new StringReader(rawText);
    final Model model = ModelReader.read(reader, sourceInfo);
    final StringBuilder sb = new StringBuilder();
    if (modelSection == null) {
        throw new IllegalStateException("Model section name is null, cannot read model");
    }
    for (final Feature feature : model.getFeatures()) {
        for (final Section section : feature.getAdditionalSections(modelSection)) {
            sb.append("# ").append(modelSection).append(" from ").append(feature.getName()).append("\n");
            sb.append("# ").append(section.getComment()).append("\n");
            sb.append(section.getContents()).append("\n");
        }
    }
    return sb.toString();
}
Also used : StringReader(java.io.StringReader) Model(org.apache.sling.provisioning.model.Model) Feature(org.apache.sling.provisioning.model.Feature) Section(org.apache.sling.provisioning.model.Section)

Example 5 with Section

use of org.apache.sling.provisioning.model.Section 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)

Aggregations

Section (org.apache.sling.provisioning.model.Section)5 StringReader (java.io.StringReader)3 Artifact (org.apache.sling.provisioning.model.Artifact)3 Feature (org.apache.sling.provisioning.model.Feature)3 LineNumberReader (java.io.LineNumberReader)2 ArtifactGroup (org.apache.sling.provisioning.model.ArtifactGroup)2 Configuration (org.apache.sling.provisioning.model.Configuration)2 RunMode (org.apache.sling.provisioning.model.RunMode)2 BufferedReader (java.io.BufferedReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Attributes (java.util.jar.Attributes)1 Manifest (java.util.jar.Manifest)1 ZipEntry (java.util.zip.ZipEntry)1 Model (org.apache.sling.provisioning.model.Model)1 Traceable (org.apache.sling.provisioning.model.Traceable)1