Search in sources :

Example 1 with InvalidConfigurationException

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

the class XmlMatcher method matches.

@Override
public boolean matches(MatcherTo matcher) {
    try {
        MatcherType matcherType = Enum.valueOf(MatcherType.class, matcher.getType().toUpperCase());
        Object target = matcher.getTarget();
        switch(matcherType) {
            case NODENAME:
                if (target instanceof Document) {
                    String documentRootName = ((Document) target).getDocumentElement().getNodeName();
                    return documentRootName != null && !documentRootName.equals("") && matcher.getValue().matches(documentRootName);
                }
                break;
            case XPATH:
                Node targetNode = getDocElem(target, 1);
                XPath xPath = createXpathObject(target);
                String xpathExpression = matcher.getValue();
                try {
                    return (boolean) xPath.evaluate(xpathExpression, targetNode, XPathConstants.BOOLEAN);
                } catch (XPathExpressionException e) {
                    if (checkXPathSyntax(xpathExpression)) {
                        return false;
                    }
                    throw new InvalidConfigurationException(xpathExpression, "Invalid XPath expression", e);
                }
        }
    } catch (IllegalArgumentException e) {
        throw new CobiGenRuntimeException("Matcher type " + matcher.getType() + " not registered!", e);
    }
    return false;
}
Also used : XPath(javax.xml.xpath.XPath) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 2 with InvalidConfigurationException

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

the class ContextConfigurationReader method readConfiguration.

/**
 * Reads the context 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());
    }
    this.contextConfigurations = new HashMap<>();
    for (Path contextFile : this.contextFiles) {
        try (InputStream in = Files.newInputStream(contextFile)) {
            Unmarshaller unmarschaller = JAXBContext.newInstance(ContextConfiguration.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 ContextConfiguration) {
                BigDecimal configVersion = ((ContextConfiguration) rootNode).getVersion();
                if (configVersion == null) {
                    throw new InvalidConfigurationException(contextFile, "The required 'version' attribute of node \"contextConfiguration\" has not been set");
                } else {
                    VersionValidator validator = new VersionValidator(Type.CONTEXT_CONFIGURATION, MavenMetadata.VERSION);
                    validator.validate(configVersion.floatValue());
                }
            } else {
                throw new InvalidConfigurationException(contextFile, "Unknown Root Node. Use \"contextConfiguration\" 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);
            ContextConfigurationVersion latestConfigurationVersion = ContextConfigurationVersion.getLatest();
            try (InputStream schemaStream = getClass().getResourceAsStream("/schema/" + latestConfigurationVersion + "/contextConfiguration.xsd");
                InputStream configInputStream = Files.newInputStream(contextFile)) {
                Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
                unmarschaller.setSchema(schema);
                rootNode = unmarschaller.unmarshal(configInputStream);
                this.contextConfigurations.put(contextFile, (ContextConfiguration) 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(contextFile, "Could not parse configuration file:\n" + message, e);
        } catch (SAXException e) {
            // Should never occur. Programming error.
            throw new IllegalStateException("Could not parse context configuration schema. Please state this as a bug.");
        } catch (NumberFormatException e) {
            // So provide help
            throw new InvalidConfigurationException("Invalid version number defined. The version of the context configuration should consist of 'major.minor' version.");
        } catch (IOException e) {
            throw new InvalidConfigurationException(contextFile, "Could not read context configuration file.", e);
        } finally {
            Thread.currentThread().setContextClassLoader(orig);
        }
    }
}
Also used : Path(java.nio.file.Path) 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) 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) ContextConfiguration(com.devonfw.cobigen.impl.config.entity.io.ContextConfiguration) ContextConfigurationVersion(com.devonfw.cobigen.impl.config.constant.ContextConfigurationVersion)

Example 3 with InvalidConfigurationException

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

the class TemplatesConfigurationReader method getExternalTrigger.

/**
 * Tries to read the context.xml file for finding and returning an external trigger
 *
 * @param triggerToSearch string containing the name of the trigger to search
 * @return the found external trigger
 */
private Trigger getExternalTrigger(String triggerToSearch) {
    ContextConfigurationReader contextConfigurationReader = new ContextConfigurationReader(this.configurationHolder.readContextConfiguration().getConfigurationPath());
    Map<String, Trigger> triggers = contextConfigurationReader.loadTriggers();
    Trigger trig = triggers.get(triggerToSearch);
    if (trig == null) {
        throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Invalid external ref, no trigger '" + triggerToSearch + "' was found on your context.xml!");
    }
    return trig;
}
Also used : Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 4 with InvalidConfigurationException

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

the class TemplatesConfigurationReader method loadExternalIncrement.

/**
 * Tries to load an external increment. It loads the trigger of the external increment and all its increments for
 * finding the needed one
 *
 * @param ref incrementRef to load and store on the root increment
 * @return the referenced child increment
 */
private Increment loadExternalIncrement(IncrementRef ref) {
    Increment childPkg;
    String[] split = splitExternalRef(ref.getRef());
    String refTrigger = split[0];
    String refIncrement = split[1];
    com.devonfw.cobigen.impl.config.TemplatesConfiguration externalTemplatesConfiguration = loadExternalConfig(refTrigger);
    Map<String, Increment> externalIncrements = externalTemplatesConfiguration.getIncrements();
    childPkg = externalIncrements.get(refIncrement);
    if (childPkg == null) {
        throw new InvalidConfigurationException("No Increment found for ref=" + ref.getRef());
    }
    return childPkg;
}
Also used : Increment(com.devonfw.cobigen.impl.config.entity.Increment) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 5 with InvalidConfigurationException

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

the class TemplatesConfigurationReader method loadTemplates.

/**
 * Loads all templates of the static configuration into the local representation
 *
 * @param trigger {@link Trigger} for which the templates should be loaded
 * @return the mapping of template names to the corresponding {@link Template}
 * @throws UnknownContextVariableException if the destination path contains an undefined context variable
 * @throws UnknownExpressionException if there is an unknown variable modifier
 * @throws InvalidConfigurationException if there are multiple templates with the same name
 */
public Map<String, Template> loadTemplates(Trigger trigger) throws UnknownExpressionException, UnknownContextVariableException, InvalidConfigurationException {
    Map<String, Template> templates = new HashMap<>();
    Templates templatesNode = this.configNode.getTemplates();
    if (templatesNode != null) {
        for (com.devonfw.cobigen.impl.config.entity.io.Template t : templatesNode.getTemplate()) {
            if (templates.get(t.getName()) != null) {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Multiple template definitions found for ref='" + t.getName() + "'");
            }
            TemplatePath child = this.rootTemplateFolder.navigate(t.getTemplateFile());
            if ((child == null) || (child.isFolder())) {
                throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "no template file found for '" + t.getTemplateFile() + "'");
            }
            Template template = createTemplate((TemplateFile) child, t.getName(), t.getDestinationPath(), t.getMergeStrategy(), t.getTargetCharset(), null);
            templates.put(t.getName(), template);
        }
    }
    TemplateScans templateScans = this.configNode.getTemplateScans();
    if (templateScans != null) {
        List<TemplateScan> scans = templateScans.getTemplateScan();
        if (scans != null) {
            for (TemplateScan scan : scans) {
                scanTemplates(scan, templates, trigger);
            }
        }
    }
    // override existing templates with extension definitions
    Set<String> observedExtensionNames = Sets.newHashSet();
    if (templatesNode != null && templatesNode.getTemplateExtension() != null) {
        for (TemplateExtension ext : this.configNode.getTemplates().getTemplateExtension()) {
            // detection of duplicate templateExtensions
            if (observedExtensionNames.contains(ext.getRef())) {
                throw new InvalidConfigurationException("Two templateExtensions declared for ref='" + ext.getRef() + "'. Don't know what to do.");
            }
            observedExtensionNames.add(ext.getRef());
            // overriding properties if defined
            if (templates.containsKey(ext.getRef())) {
                Template template = templates.get(ext.getRef());
                if (ext.getDestinationPath() != null) {
                    template.setUnresolvedTargetPath(ext.getDestinationPath());
                }
                if (ext.getMergeStrategy() != null) {
                    template.setMergeStrategy(ext.getMergeStrategy());
                }
                if (ext.getTargetCharset() != null) {
                    template.setTargetCharset(ext.getTargetCharset());
                }
            } else {
                throw new InvalidConfigurationException("The templateExtension with ref='" + ext.getRef() + "' does not reference any template!");
            }
        }
    }
    return templates;
}
Also used : TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) HashMap(java.util.HashMap) Templates(com.devonfw.cobigen.impl.config.entity.io.Templates) TemplateScan(com.devonfw.cobigen.impl.config.entity.io.TemplateScan) Template(com.devonfw.cobigen.impl.config.entity.Template) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) TemplateScans(com.devonfw.cobigen.impl.config.entity.io.TemplateScans) TemplateExtension(com.devonfw.cobigen.impl.config.entity.io.TemplateExtension)

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