Search in sources :

Example 1 with TemplatesConfigurationVersion

use of com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion 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 2 with TemplatesConfigurationVersion

use of com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion in project cobigen by devonfw.

the class TemplateConfigurationUpgraderTest method testCorrectUpgrade_v1_2_TO_v2_1.

/**
 * Tests the valid upgrade of a templates configuration from version v1.2 to v2.1.
 *
 * @throws Exception test fails
 */
@Test
public void testCorrectUpgrade_v1_2_TO_v2_1() throws Exception {
    // preparation
    File tmpTargetConfig = this.tempFolder.newFile(ConfigurationConstants.TEMPLATES_CONFIG_FILENAME);
    File sourceTestdata = new File(testFileRootPath + "valid-v1.2/" + ConfigurationConstants.TEMPLATES_CONFIG_FILENAME);
    Files.copy(sourceTestdata, tmpTargetConfig);
    TemplateConfigurationUpgrader sut = new TemplateConfigurationUpgrader();
    TemplatesConfigurationVersion version = sut.resolveLatestCompatibleSchemaVersion(this.tempFolder.getRoot().toPath());
    assertThat(version).as("Source Version").isEqualTo(TemplatesConfigurationVersion.v1_2);
    sut.upgradeConfigurationToLatestVersion(this.tempFolder.getRoot().toPath(), BackupPolicy.ENFORCE_BACKUP);
    assertThat(tmpTargetConfig.toPath().resolveSibling("templates.bak.xml").toFile()).exists().hasSameContentAs(sourceTestdata);
    version = sut.resolveLatestCompatibleSchemaVersion(this.tempFolder.getRoot().toPath());
    assertThat(version).as("Target version").isEqualTo(TemplatesConfigurationVersion.v4_0);
    XMLUnit.setIgnoreWhitespace(true);
    try (FileReader vgl = new FileReader(testFileRootPath + "valid-v2.1/" + ConfigurationConstants.TEMPLATES_CONFIG_FILENAME);
        FileReader tmp = new FileReader(tmpTargetConfig)) {
        new XMLTestCase() {
        }.assertXMLEqual(vgl, tmp);
    }
}
Also used : TemplateConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.TemplateConfigurationUpgrader) XMLTestCase(org.custommonkey.xmlunit.XMLTestCase) FileReader(java.io.FileReader) TemplatesConfigurationVersion(com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion) File(java.io.File) Test(org.junit.Test) AbstractUnitTest(com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)

Example 3 with TemplatesConfigurationVersion

use of com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion in project cobigen by devonfw.

the class HealthCheckImpl method perform.

@Override
public HealthCheckReport perform(Path configurationPath) {
    // 1. Get configuration resources
    // determine expected template configurations to be defined
    ContextConfiguration contextConfiguration = new ContextConfiguration(configurationPath);
    List<String> expectedTemplatesConfigurations = Lists.newArrayList();
    Set<String> hasConfiguration = Sets.newHashSet();
    Set<String> isAccessible = Sets.newHashSet();
    Map<String, Path> upgradeableConfigurations = Maps.newHashMap();
    Set<String> upToDateConfigurations = Sets.newHashSet();
    Path pathForCobigenTemplates = null;
    for (Trigger t : contextConfiguration.getTriggers()) {
        expectedTemplatesConfigurations.add(t.getTemplateFolder());
    }
    // 2. Determine current state
    TemplateConfigurationUpgrader templateConfigurationUpgrader = new TemplateConfigurationUpgrader();
    pathForCobigenTemplates = configurationPath.resolve("src" + File.separator + "main" + File.separator + "templates");
    for (String expectedTemplateFolder : expectedTemplatesConfigurations) {
        if (Files.exists(pathForCobigenTemplates)) {
            String configPath = (configurationPath + File.separator + "src" + File.separator + "main" + File.separator + "templates").toString();
            hasConfiguration.add(configPath);
            isAccessible.add(configPath);
            Path expectedTemplateFolderForResolvedVer = pathForCobigenTemplates.resolve(expectedTemplateFolder.replace("/", File.separator).toString());
            TemplatesConfigurationVersion resolvedVersion = templateConfigurationUpgrader.resolveLatestCompatibleSchemaVersion(expectedTemplateFolderForResolvedVer);
            if (resolvedVersion != null) {
                if (resolvedVersion != TemplatesConfigurationVersion.getLatest()) {
                    upgradeableConfigurations.put(expectedTemplateFolder, pathForCobigenTemplates);
                } else {
                    upToDateConfigurations.add(expectedTemplateFolder);
                }
            }
        } else {
            Path templateFolder = configurationPath.resolve(expectedTemplateFolder);
            Path templatesConfigurationPath = templateFolder.resolve(ConfigurationConstants.TEMPLATES_CONFIG_FILENAME);
            File templatesConfigurationFile = templatesConfigurationPath.toFile();
            if (templatesConfigurationFile.exists()) {
                hasConfiguration.add(expectedTemplateFolder);
                if (templatesConfigurationFile.canWrite()) {
                    isAccessible.add(expectedTemplateFolder);
                    TemplatesConfigurationVersion resolvedVersion = templateConfigurationUpgrader.resolveLatestCompatibleSchemaVersion(templateFolder);
                    if (resolvedVersion != null) {
                        if (resolvedVersion != TemplatesConfigurationVersion.getLatest()) {
                            upgradeableConfigurations.put(expectedTemplateFolder, templateFolder);
                        } else {
                            upToDateConfigurations.add(expectedTemplateFolder);
                        }
                    }
                }
            }
        }
    }
    this.healthCheckReport.setExpectedTemplatesConfigurations(expectedTemplatesConfigurations);
    this.healthCheckReport.setHasConfiguration(hasConfiguration);
    this.healthCheckReport.setIsAccessible(isAccessible);
    this.healthCheckReport.setUpgradeableConfigurations(upgradeableConfigurations);
    this.healthCheckReport.setUpToDateConfigurations(upToDateConfigurations);
    return this.healthCheckReport;
}
Also used : Path(java.nio.file.Path) TemplateConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.TemplateConfigurationUpgrader) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) ContextConfiguration(com.devonfw.cobigen.impl.config.ContextConfiguration) TemplatesConfigurationVersion(com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion) File(java.io.File)

Example 4 with TemplatesConfigurationVersion

use of com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion in project cobigen by devonfw.

the class TemplateConfigurationUpgraderTest method testCorrectV2_1SchemaDetection.

/**
 * Tests the valid upgrade of a templates configuration from version v1.2 to v2.1.
 *
 * @throws Exception test fails
 */
@Test
public void testCorrectV2_1SchemaDetection() throws Exception {
    // preparation
    File targetConfig = new File(testFileRootPath + "valid-v2.1");
    TemplatesConfigurationVersion version = new TemplateConfigurationUpgrader().resolveLatestCompatibleSchemaVersion(targetConfig.toPath());
    assertThat(version).isEqualTo(TemplatesConfigurationVersion.v4_0);
}
Also used : TemplateConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.TemplateConfigurationUpgrader) TemplatesConfigurationVersion(com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion) File(java.io.File) Test(org.junit.Test) AbstractUnitTest(com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)

Aggregations

TemplatesConfigurationVersion (com.devonfw.cobigen.impl.config.constant.TemplatesConfigurationVersion)4 TemplateConfigurationUpgrader (com.devonfw.cobigen.impl.config.upgrade.TemplateConfigurationUpgrader)3 File (java.io.File)3 AbstractUnitTest (com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)2 Test (org.junit.Test)2 InvalidConfigurationException (com.devonfw.cobigen.api.exception.InvalidConfigurationException)1 ContextConfiguration (com.devonfw.cobigen.impl.config.ContextConfiguration)1 Trigger (com.devonfw.cobigen.impl.config.entity.Trigger)1 TemplatesConfiguration (com.devonfw.cobigen.impl.config.entity.io.TemplatesConfiguration)1 VersionValidator (com.devonfw.cobigen.impl.config.versioning.VersionValidator)1 JAXBContext (jakarta.xml.bind.JAXBContext)1 JAXBException (jakarta.xml.bind.JAXBException)1 UnmarshalException (jakarta.xml.bind.UnmarshalException)1 Unmarshaller (jakarta.xml.bind.Unmarshaller)1 FileReader (java.io.FileReader)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 BigDecimal (java.math.BigDecimal)1 Path (java.nio.file.Path)1 StreamSource (javax.xml.transform.stream.StreamSource)1