Search in sources :

Example 16 with InvalidConfigurationException

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

the class ContextConfigurationReader method loadContextFilesInSubfolder.

/**
 * search for configuration Files in the subfolders of configRoot
 *
 * @param configRoot root directory of the configuration
 * @throws InvalidConfigurationException if the configuration is not valid against its xsd specification
 */
private List<Path> loadContextFilesInSubfolder(Path configRoot) {
    List<Path> contextPaths = new ArrayList<>();
    List<Path> templateDirectories = new ArrayList<>();
    try (Stream<Path> files = Files.list(configRoot)) {
        files.forEach(path -> {
            if (Files.isDirectory(path)) {
                templateDirectories.add(path);
            }
        });
    } catch (IOException e) {
        throw new InvalidConfigurationException(configRoot, "Could not read configuration root directory.", e);
    }
    for (Path file : templateDirectories) {
        Path contextPath = file.resolve(ConfigurationConstants.CONTEXT_CONFIG_FILENAME);
        if (Files.exists(contextPath)) {
            contextPaths.add(contextPath);
        }
    }
    return contextPaths;
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 17 with InvalidConfigurationException

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

the class TemplatesConfigurationReader method loadExternalTemplate.

/**
 * Tries to load an external template, returning the reference template
 *
 * @param ref The reference to the template
 * @return the referenced template
 */
private Template loadExternalTemplate(TemplateRef ref) {
    String[] split = splitExternalRef(ref.getRef());
    String refTrigger = split[0];
    String refTemplate = split[1];
    com.devonfw.cobigen.impl.config.TemplatesConfiguration externalTemplatesConfiguration = loadExternalConfig(refTrigger);
    Template template = externalTemplatesConfiguration.getTemplate(refTemplate);
    if (template == null) {
        throw new InvalidConfigurationException("No Template found for ref=" + ref.getRef());
    }
    return template;
}
Also used : Template(com.devonfw.cobigen.impl.config.entity.Template) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 18 with InvalidConfigurationException

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

the class TemplatesConfigurationReader method scanTemplates.

/**
 * Recursively scans the templates specified by the given {@link TemplateScan} and adds them to the given
 * <code>templates</code> {@link Map}.
 *
 * @param templateFolder the {@link TemplateFolder} pointing to the current directory to scan.
 * @param currentPath the current path relative to the top-level directory where we started the scan.
 * @param scan is the {@link TemplateScan} configuration.
 * @param templates is the {@link Map} where to add the templates.
 * @param trigger the templates are from
 * @param observedTemplateNames observed template name during template scan. Needed for conflict detection
 */
private void scanTemplates(TemplateFolder templateFolder, String currentPath, TemplateScan scan, Map<String, Template> templates, Trigger trigger, HashSet<String> observedTemplateNames) {
    String currentPathWithSlash = currentPath;
    if (!currentPathWithSlash.isEmpty()) {
        currentPathWithSlash = currentPathWithSlash + "/";
    }
    for (TemplatePath child : templateFolder.getChildren()) {
        if (child.isFolder()) {
            scanTemplates((TemplateFolder) child, currentPathWithSlash + child.getFileName(), scan, templates, trigger, observedTemplateNames);
        } else {
            String templateFileName = child.getFileName();
            if (StringUtils.isEmpty(currentPath) && templateFileName.equals("templates.xml")) {
                continue;
            }
            String templateNameWithoutExtension = stripTemplateFileending(templateFileName);
            TextTemplateEngine templateEngine = TemplateEngineRegistry.getEngine(getTemplateEngine());
            if (!StringUtils.isEmpty(templateEngine.getTemplateFileEnding()) && templateFileName.endsWith(templateEngine.getTemplateFileEnding())) {
                templateNameWithoutExtension = templateFileName.substring(0, templateFileName.length() - templateEngine.getTemplateFileEnding().length());
            }
            String templateName = (scan.getTemplateNamePrefix() != null ? scan.getTemplateNamePrefix() : "") + templateNameWithoutExtension;
            if (observedTemplateNames.contains(templateName)) {
                throw new InvalidConfigurationException("TemplateScan has detected two files with the same file name (" + child + ") and thus with the same " + "template name. Continuing would result in an indeterministic behavior.\n" + "For now, multiple files with the same name are not supported to be automatically " + "configured with templateScans.");
            }
            observedTemplateNames.add(templateName);
            if (!templates.containsKey(templateName)) {
                String destinationPath = "";
                if (!StringUtils.isEmpty(scan.getDestinationPath())) {
                    destinationPath = scan.getDestinationPath() + "/";
                }
                destinationPath += currentPathWithSlash + templateNameWithoutExtension;
                String mergeStratgey = scan.getMergeStrategy();
                Template template = createTemplate((TemplateFile) child, templateName, destinationPath, mergeStratgey, scan.getTargetCharset(), scan.getTemplatePath());
                templates.put(templateName, template);
                if (this.templateScanTemplates.get(scan.getName()) != null) {
                    this.templateScanTemplates.get(scan.getName()).add(templateName);
                }
            }
        }
    }
}
Also used : TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) Template(com.devonfw.cobigen.impl.config.entity.Template)

Example 19 with InvalidConfigurationException

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

the class TemplatesConfigurationReader method scanTemplates.

/**
 * Scans the templates specified by the given {@link TemplateScan} and adds them to the given <code>templates</code>
 * {@link Map}.
 *
 * @param scan is the {@link TemplateScan} configuration.
 * @param templates is the {@link Map} where to add the templates.
 * @param trigger the templates are from
 */
private void scanTemplates(TemplateScan scan, Map<String, Template> templates, Trigger trigger) {
    String templatePath = scan.getTemplatePath();
    TemplatePath templateFolder = this.rootTemplateFolder.navigate(templatePath);
    if ((templateFolder == null) || templateFolder.isFile()) {
        throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "The templatePath '" + templatePath + "' of templateScan with name '" + scan.getName() + "' does not describe a directory.");
    }
    if (scan.getName() != null) {
        if (this.templateScanTemplates.containsKey(scan.getName())) {
            throw new InvalidConfigurationException(this.configFilePath.toUri().toString(), "Two templateScan nodes have been defined with the same @name by mistake.");
        } else {
            this.templateScanTemplates.put(scan.getName(), new ArrayList<String>());
        }
    }
    scanTemplates((TemplateFolder) templateFolder, "", scan, templates, trigger, Sets.<String>newHashSet());
}
Also used : TemplatePath(com.devonfw.cobigen.impl.config.entity.TemplatePath) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 20 with InvalidConfigurationException

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

the class AbstractConfigurationUpgrader method upgradeConfigurationToLatestVersion.

/**
 * Upgrades the configuration to the latest supported version.
 *
 * @param configurationRoot the root folder containing the configuration with the specified
 *        {@link #configurationFilename}. See {@link #AbstractConfigurationUpgrader(Enum, Class, String)} for more
 *        information.
 * @param backupPolicy the {@link BackupPolicy} to choose if a backup is necessary or not.
 * @return if manual adoptions has to be performed after upgrading
 * @throws BackupFailedException if the backup could not be created
 */
public boolean upgradeConfigurationToLatestVersion(Path configurationRoot, BackupPolicy backupPolicy) {
    boolean manualAdoptionsNecessary = false;
    VERSIONS_TYPE currentVersion = resolveLatestCompatibleSchemaVersion(configurationRoot);
    Path configurationFile = configurationRoot.resolve(this.configurationFilename);
    if (currentVersion == null) {
        throw new InvalidConfigurationException(configurationFile.toUri().toString(), StringUtils.capitalize(this.configurationName) + " does not match any current or legacy schema definitions.");
    } else {
        VERSIONS_TYPE latestVersion = this.versions[this.versions.length - 1];
        // increasing iteration of versions
        for (int i = 0; i < this.versions.length; i++) {
            if (currentVersion == latestVersion) {
                // already up to date
                break;
            }
            if (currentVersion == this.versions[i]) {
                LOG.info("Upgrading {} '{}' from version {} to {}...", this.configurationName, configurationFile.toUri(), this.versions[i], this.versions[i + 1]);
                Object rootNode;
                try {
                    Class<?> jaxbConfigurationClass = getJaxbConfigurationClass(this.versions[i]);
                    rootNode = unmarshallConfiguration(configurationFile, this.versions[i], jaxbConfigurationClass);
                    createBackup(configurationFile, backupPolicy);
                    // NotYetSupportedException
                    ConfigurationUpgradeResult result = performNextUpgradeStep(this.versions[i], rootNode);
                    manualAdoptionsNecessary |= result.areManualAdoptionsNecessary();
                    try (OutputStream out = Files.newOutputStream(configurationFile)) {
                        JAXB.marshal(result.getResultConfigurationJaxbRootNode(), out);
                    }
                    // implicitly check upgrade step
                    currentVersion = resolveLatestCompatibleSchemaVersion(configurationRoot);
                } catch (NotYetSupportedException | BackupFailedException e) {
                    throw e;
                } catch (Throwable e) {
                    throw new CobiGenRuntimeException("An unexpected exception occurred while upgrading the " + this.configurationName + " from version '" + this.versions[i] + "' to '" + this.versions[i + 1] + "'.", e);
                }
                // if CobiGen does not understand the upgraded file... throw exception
                if (currentVersion == null) {
                    throw new CobiGenRuntimeException("An error occurred while upgrading " + this.configurationName + " from version " + this.versions[i] + " to " + this.versions[i + 1] + ".");
                }
            }
        }
    }
    return manualAdoptionsNecessary;
}
Also used : Path(java.nio.file.Path) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) BackupFailedException(com.devonfw.cobigen.impl.exceptions.BackupFailedException) OutputStream(java.io.OutputStream) NotYetSupportedException(com.devonfw.cobigen.api.exception.NotYetSupportedException) 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