Search in sources :

Example 6 with InvalidConfigurationException

use of com.devonfw.cobigen.api.exception.InvalidConfigurationException in project cobigen by devonfw.

the class TemplatesConfigurationReader method loadIncrements.

/**
 * Loads all increments of the static configuration into the local representation.
 *
 * @return the mapping of increment names to the corresponding {@link Increment}
 * @param templates {@link Map} of all templates (see {@link TemplatesConfigurationReader#loadTemplates(Trigger)}
 * @param trigger {@link Trigger} for which the templates should be loaded
 * @throws InvalidConfigurationException if there is an invalid ref attribute
 */
public Map<String, Increment> loadIncrements(Map<String, Template> templates, Trigger trigger) throws InvalidConfigurationException {
    Map<String, Increment> increments = new HashMap<>();
    Increments incrementsNode = this.configNode.getIncrements();
    if (incrementsNode != null) {
        // Add first all increments informally be able to resolve recursive increment references
        for (com.devonfw.cobigen.impl.config.entity.io.Increment source : incrementsNode.getIncrement()) {
            if (!increments.containsKey(source.getName())) {
                increments.put(source.getName(), new Increment(source.getName(), source.getDescription(), trigger));
            } else {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Duplicate increment found with name='" + source.getName() + "'.");
            }
        }
        // Collect templates
        for (com.devonfw.cobigen.impl.config.entity.io.Increment p : this.configNode.getIncrements().getIncrement()) {
            Increment target = increments.get(p.getName());
            addAllTemplatesRecursively(target, p, templates, increments);
        }
    }
    return increments;
}
Also used : HashMap(java.util.HashMap) Increment(com.devonfw.cobigen.impl.config.entity.Increment) Increments(com.devonfw.cobigen.impl.config.entity.io.Increments) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 7 with InvalidConfigurationException

use of com.devonfw.cobigen.api.exception.InvalidConfigurationException in project cobigen by devonfw.

the class TemplatesConfigurationReader method loadSpecificIncrement.

/**
 * Loads an specific increment of the static configuration into the local representation. The return object must be a
 * map because maybe this increment references other increments
 *
 * @return the mapping of increment names to the corresponding {@link Increment}
 * @param templates {@link Map} of all templates (see {@link TemplatesConfigurationReader#loadTemplates(Trigger)}
 * @param trigger {@link Trigger} for which the templates should be loaded
 * @param incrementName the increment to search
 * @throws InvalidConfigurationException if there is an invalid ref attribute
 */
public Map<String, Increment> loadSpecificIncrement(Map<String, Template> templates, Trigger trigger, String incrementName) throws InvalidConfigurationException {
    Map<String, Increment> increments = new HashMap<>();
    Increments incrementsNode = this.configNode.getIncrements();
    if (incrementsNode != null) {
        // We only add the specific increment we want
        com.devonfw.cobigen.impl.config.entity.io.Increment source = getSpecificIncrement(incrementsNode.getIncrement(), incrementName);
        if (source == null) {
            throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No increment found with name='" + incrementName + "' on the external templates.xml folder.");
        }
        increments.put(source.getName(), new Increment(source.getName(), source.getDescription(), trigger));
        // Collect templates for our specific increment
        Increment target = increments.get(source.getName());
        addAllTemplatesRecursively(target, source, templates, increments);
    }
    return increments;
}
Also used : HashMap(java.util.HashMap) Increment(com.devonfw.cobigen.impl.config.entity.Increment) Increments(com.devonfw.cobigen.impl.config.entity.io.Increments) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 8 with InvalidConfigurationException

use of com.devonfw.cobigen.api.exception.InvalidConfigurationException in project cobigen by devonfw.

the class TemplatesConfigurationReader method addAllTemplatesRecursively.

/**
 * Adds all templates defined within the increment and sub increments recursively.
 *
 * @param rootIncrement the {@link Increment} on which the templates should be added
 * @param current the source {@link com.devonfw.cobigen.impl.config.entity.io.Increment} from which to retrieve the
 *        data
 * @param templates {@link Map} of all templates (see {@link TemplatesConfigurationReader#loadTemplates(Trigger)}
 * @param increments {@link Map} of all retrieved increments
 * @throws InvalidConfigurationException if there is an invalid ref attribute
 */
private void addAllTemplatesRecursively(Increment rootIncrement, com.devonfw.cobigen.impl.config.entity.io.Increment current, Map<String, Template> templates, Map<String, Increment> increments) throws InvalidConfigurationException {
    for (TemplateRef ref : current.getTemplateRefOrIncrementRefOrTemplateScanRef().stream().filter(e -> e instanceof TemplateRef).map(e -> (TemplateRef) e).collect(Collectors.toList())) {
        Template temp = templates.get(ref.getRef());
        if (temp == null) {
            if (isExternalRef(ref.getRef())) {
                rootIncrement.addTemplate(loadExternalTemplate(ref));
            } else {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No template found for ref='" + ref.getRef() + "'!");
            }
        } else {
            rootIncrement.addTemplate(temp);
        }
    }
    for (IncrementRef ref : current.getTemplateRefOrIncrementRefOrTemplateScanRef().stream().filter(e -> e instanceof IncrementRef).map(e -> (IncrementRef) e).collect(Collectors.toList())) {
        Increment parentPkg = increments.get(current.getName());
        Increment childPkg = increments.get(ref.getRef());
        if (childPkg == null) {
            // We try to find the increment inside our templates.xml file
            Increments incrementsNode = this.configNode.getIncrements();
            com.devonfw.cobigen.impl.config.entity.io.Increment source = null;
            if (incrementsNode != null) {
                // We only add the specific increment we want
                source = getSpecificIncrement(incrementsNode.getIncrement(), ref.getRef());
                if (source != null) {
                    addAllTemplatesRecursively(rootIncrement, source, templates, increments);
                } else // incrementRef contains "::". That would mean we have to search on another folder.
                if (isExternalRef(ref.getRef())) {
                    parentPkg.addIncrementDependency(loadExternalIncrement(ref));
                } else {
                    throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No increment found for ref='" + ref.getRef() + "'!");
                }
            }
        } else {
            parentPkg.addIncrementDependency(childPkg);
            com.devonfw.cobigen.impl.config.entity.io.Increment pkg = getIncrementDeclaration(ref);
            addAllTemplatesRecursively(rootIncrement, pkg, templates, increments);
        }
    }
    for (TemplateScanRef ref : current.getTemplateRefOrIncrementRefOrTemplateScanRef().stream().filter(e -> e instanceof TemplateScanRef).map(e -> (TemplateScanRef) e).collect(Collectors.toList())) {
        List<String> scannedTemplateNames = this.templateScanTemplates.get(ref.getRef());
        if (scannedTemplateNames == null) {
            throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "No templateScan found for ref='" + ref.getRef() + "'!");
        } else {
            for (String scannedTemplateName : scannedTemplateNames) {
                rootIncrement.addTemplate(templates.get(scannedTemplateName));
            }
        }
    }
}
Also used : TemplateScans(com.devonfw.cobigen.impl.config.entity.io.TemplateScans) Unmarshaller(jakarta.xml.bind.Unmarshaller) TemplatesConfigurationVersion(com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion) StringUtils(org.apache.commons.lang3.StringUtils) Type(com.devonfw.cobigen.impl.config.versioning.VersionValidator.Type) BigDecimal(java.math.BigDecimal) JvmUtil(com.devonfw.cobigen.api.util.JvmUtil) Map(java.util.Map) VersionValidator(com.devonfw.cobigen.impl.config.versioning.VersionValidator) Path(java.nio.file.Path) ExceptionUtil(com.devonfw.cobigen.api.util.ExceptionUtil) Increments(com.devonfw.cobigen.impl.config.entity.io.Increments) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) Set(java.util.Set) TemplateEngineRegistry(com.devonfw.cobigen.impl.extension.TemplateEngineRegistry) Collectors(java.util.stream.Collectors) Templates(com.devonfw.cobigen.impl.config.entity.io.Templates) UnknownContextVariableException(com.devonfw.cobigen.impl.exceptions.UnknownContextVariableException) Sets(com.google.common.collect.Sets) List(java.util.List) SAXException(org.xml.sax.SAXException) JXPathContext(org.apache.commons.jxpath.JXPathContext) ConfigurationConstants(com.devonfw.cobigen.api.constants.ConfigurationConstants) TemplatesConfiguration(com.devonfw.cobigen.impl.config.entity.io.TemplatesConfiguration) StreamSource(javax.xml.transform.stream.StreamSource) HashMap(java.util.HashMap) TemplateExtension(com.devonfw.cobigen.impl.config.entity.io.TemplateExtension) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) TemplateScan(com.devonfw.cobigen.impl.config.entity.io.TemplateScan) HashSet(java.util.HashSet) TemplateScanRef(com.devonfw.cobigen.impl.config.entity.io.TemplateScanRef) XMLConstants(javax.xml.XMLConstants) MavenMetadata(com.devonfw.cobigen.impl.config.constant.MavenMetadata) TemplateFolder(com.devonfw.cobigen.impl.config.entity.TemplateFolder) UnmarshalException(jakarta.xml.bind.UnmarshalException) Properties(java.util.Properties) SchemaFactory(javax.xml.validation.SchemaFactory) Iterator(java.util.Iterator) JAXBContext(jakarta.xml.bind.JAXBContext) Files(java.nio.file.Files) ConfigurationHolder(com.devonfw.cobigen.impl.config.ConfigurationHolder) IncrementRef(com.devonfw.cobigen.impl.config.entity.io.IncrementRef) TemplateRef(com.devonfw.cobigen.impl.config.entity.io.TemplateRef) UnknownExpressionException(com.devonfw.cobigen.api.exception.UnknownExpressionException) IOException(java.io.IOException) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) Template(com.devonfw.cobigen.impl.config.entity.Template) Maps(com.google.common.collect.Maps) Increment(com.devonfw.cobigen.impl.config.entity.Increment) SAXParseException(org.xml.sax.SAXParseException) JAXBException(jakarta.xml.bind.JAXBException) TemplateFile(com.devonfw.cobigen.impl.config.entity.TemplateFile) Paths(java.nio.file.Paths) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) InputStream(java.io.InputStream) IncrementRef(com.devonfw.cobigen.impl.config.entity.io.IncrementRef) Template(com.devonfw.cobigen.impl.config.entity.Template) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) TemplateScanRef(com.devonfw.cobigen.impl.config.entity.io.TemplateScanRef) Increment(com.devonfw.cobigen.impl.config.entity.Increment) Increments(com.devonfw.cobigen.impl.config.entity.io.Increments) TemplateRef(com.devonfw.cobigen.impl.config.entity.io.TemplateRef)

Example 9 with InvalidConfigurationException

use of com.devonfw.cobigen.api.exception.InvalidConfigurationException in project cobigen by devonfw.

the class TemplatesConfigurationReader method readConfiguration.

/**
 * Reads the templates configuration.
 */
private void readConfiguration() {
    // workaround to make JAXB work in OSGi context by
    // https://github.com/ControlSystemStudio/cs-studio/issues/2530#issuecomment-450991188
    final ClassLoader orig = Thread.currentThread().getContextClassLoader();
    if (JvmUtil.isRunningJava9OrLater()) {
        Thread.currentThread().setContextClassLoader(JAXBContext.class.getClassLoader());
    }
    try (InputStream in = Files.newInputStream(this.configFilePath)) {
        Unmarshaller unmarschaller = JAXBContext.newInstance(TemplatesConfiguration.class).createUnmarshaller();
        // Unmarshal without schema checks for getting the version attribute of the root node.
        // This is necessary to provide an automatic upgrade client later on
        Object rootNode = unmarschaller.unmarshal(in);
        if (rootNode instanceof TemplatesConfiguration) {
            BigDecimal configVersion = ((TemplatesConfiguration) rootNode).getVersion();
            if (configVersion == null) {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "The required 'version' attribute of node \"templatesConfiguration\" has not been set");
            } else {
                VersionValidator validator = new VersionValidator(Type.TEMPLATES_CONFIGURATION, MavenMetadata.VERSION);
                validator.validate(configVersion.floatValue());
            }
        } else {
            throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Unknown Root Node. Use \"templatesConfiguration\" as root Node");
        }
        // If we reach this point, the configuration version and root node has been validated.
        // Unmarshal with schema checks for checking the correctness and give the user more hints to
        // correct his failures
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        TemplatesConfigurationVersion latestConfigurationVersion = TemplatesConfigurationVersion.getLatest();
        try (InputStream schemaStream = getClass().getResourceAsStream("/schema/" + latestConfigurationVersion + "/templatesConfiguration.xsd");
            InputStream configInputStream = Files.newInputStream(this.configFilePath)) {
            Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
            unmarschaller.setSchema(schema);
            rootNode = unmarschaller.unmarshal(configInputStream);
            this.configNode = (TemplatesConfiguration) rootNode;
        }
    } catch (JAXBException e) {
        // try getting SAXParseException for better error handling and user support
        Throwable parseCause = ExceptionUtil.getCause(e, SAXParseException.class, UnmarshalException.class);
        String message = "";
        if (parseCause != null && parseCause.getMessage() != null) {
            message = parseCause.getMessage();
        }
        throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Could not parse configuration file:\n" + message, e);
    } catch (SAXException e) {
        // Should never occur. Programming error.
        throw new IllegalStateException("Could not parse templates configuration schema. Please state this as a bug.");
    } catch (NumberFormatException e) {
        // So provide help
        throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Invalid version number defined. The version of the templates configuration should consist of 'major.minor' version.", e);
    } catch (IOException e) {
        throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Could not read templates configuration file.", e);
    } finally {
        Thread.currentThread().setContextClassLoader(orig);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) JAXBException(jakarta.xml.bind.JAXBException) VersionValidator(com.devonfw.cobigen.impl.config.versioning.VersionValidator) JAXBContext(jakarta.xml.bind.JAXBContext) IOException(java.io.IOException) TemplatesConfiguration(com.devonfw.cobigen.impl.config.entity.io.TemplatesConfiguration) BigDecimal(java.math.BigDecimal) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) UnmarshalException(jakarta.xml.bind.UnmarshalException) Unmarshaller(jakarta.xml.bind.Unmarshaller) TemplatesConfigurationVersion(com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion)

Example 10 with InvalidConfigurationException

use of com.devonfw.cobigen.api.exception.InvalidConfigurationException in project cobigen by devonfw.

the class VersionValidator method validate.

/**
 * Validates the given version with the running instance of CobiGen.
 *
 * @param configVersion version to be validated
 */
public void validate(float configVersion) {
    Float currentCobiGenVersion;
    String currentCobiGenVersionStr = this.cobiGenVersion;
    currentCobiGenVersionStr = currentCobiGenVersionStr.substring(0, currentCobiGenVersionStr.lastIndexOf("."));
    currentCobiGenVersion = Float.parseFloat(currentCobiGenVersionStr);
    if (configVersion == currentCobiGenVersion) {
        // valid -> first version of CobiGen supporting this configuration
        LOG.debug("Compatible {} due to version declaration. CobiGen: {} / {}: {}", this.configName, currentCobiGenVersionStr, this.configName, configVersion);
        return;
    } else if (configVersion > currentCobiGenVersion) {
        LOG.error("CobiGen version to old for {} version. CobiGen: {} / {}: {}", this.configName, currentCobiGenVersionStr, this.configName, configVersion);
        throw new InvalidConfigurationException("The version '" + configVersion + "' of the " + this.configName + " is unknown to the current version of CobiGen '" + currentCobiGenVersionStr + "'. No automatic upgrade could be started. Please check your configuration or upgrade CobiGen first.");
    } else {
        // configVersion < currentCobiGenVersion
        for (Entry<Float, Boolean> versionStep : this.versionSteps.entrySet()) {
            // newer version step which is not backward compatible
            if (versionStep.getKey() > configVersion && versionStep.getKey() <= currentCobiGenVersion && !versionStep.getValue()) {
                LOG.warn("{} version too old for current CobiGen version. CobiGen: {} / {}: {}", this.configName, currentCobiGenVersionStr, this.configName, configVersion);
                throw new InvalidConfigurationException("The " + this.configName + " with version '" + configVersion + "' has to be upgraded to a compatible " + this.configName + " version.");
            }
        }
        LOG.debug("Compatible {} as no breaking changes found. CobiGen: {} / {}: {}", this.configName, currentCobiGenVersionStr, this.configName, configVersion);
    }
}
Also used : Entry(java.util.Map.Entry) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Aggregations

InvalidConfigurationException (com.devonfw.cobigen.api.exception.InvalidConfigurationException)25 Increment (com.devonfw.cobigen.impl.config.entity.Increment)5 Template (com.devonfw.cobigen.impl.config.entity.Template)5 VersionValidator (com.devonfw.cobigen.impl.config.versioning.VersionValidator)5 Path (java.nio.file.Path)5 HashMap (java.util.HashMap)5 TemplatePath (com.devonfw.cobigen.impl.config.entity.TemplatePath)4 IOException (java.io.IOException)4 CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)3 Increments (com.devonfw.cobigen.impl.config.entity.io.Increments)3 JAXBContext (jakarta.xml.bind.JAXBContext)3 JAXBException (jakarta.xml.bind.JAXBException)3 UnmarshalException (jakarta.xml.bind.UnmarshalException)3 Unmarshaller (jakarta.xml.bind.Unmarshaller)3 InputStream (java.io.InputStream)3 BigDecimal (java.math.BigDecimal)3 StreamSource (javax.xml.transform.stream.StreamSource)3 Schema (javax.xml.validation.Schema)3 SchemaFactory (javax.xml.validation.SchemaFactory)3 SAXException (org.xml.sax.SAXException)3