Search in sources :

Example 1 with ContextConfigurationVersion

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

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

the class HealthCheckDialog method execute.

/**
 * Executes the simple health check, checking configuration project existence, validity of context configuration, as
 * well as validity of the current workbench selection as generation input.
 */
public void execute() {
    String firstStep = "1. CobiGen configuration project '" + ResourceConstants.CONFIG_PROJECT_NAME + "'... ";
    String secondStep = "\n2. CobiGen context configuration '" + ConfigurationConstants.CONTEXT_CONFIG_FILENAME + "'... ";
    String healthyCheckMessage = "";
    IProject generatorConfProj = null;
    try {
        // refresh and check context configuration
        ResourcesPluginUtil.refreshConfigurationProject();
        // check configuration project existence in workspace
        generatorConfProj = ResourcesPluginUtil.getGeneratorConfigurationProject();
        this.report = performHealthCheckReport();
        if (generatorConfProj != null && generatorConfProj.getLocationURI() != null) {
            CobiGenFactory.create(generatorConfProj.getLocationURI());
        } else {
            File templatesDirectory = CobiGenPaths.getTemplatesFolderPath().toFile();
            File jarPath = TemplatesJarUtil.getJarFile(false, templatesDirectory);
            boolean fileExists = jarPath.exists();
            if (!fileExists) {
                MessageDialog.openWarning(Display.getDefault().getActiveShell(), "Warning", "Not Downloaded the CobiGen Template Jar");
            }
        }
        healthyCheckMessage = firstStep + "OK.";
        healthyCheckMessage += secondStep;
        boolean healthyCheckWarning = false;
        if (this.report.getNumberOfErrors() == 0) {
            healthyCheckMessage += "OK.";
        } else {
            healthyCheckMessage += "INVALID.";
            healthyCheckWarning = true;
        }
        openSuccessDialog(healthyCheckMessage, healthyCheckWarning);
    } catch (GeneratorProjectNotExistentException e) {
        LOG.warn("Configuration project not found!", e);
        healthyCheckMessage = firstStep + "NOT FOUND!\n" + "=> Please import the configuration project into your workspace as stated in the " + "documentation of CobiGen or in the one of your project.";
        PlatformUIUtil.openErrorDialog(healthyCheckMessage, null);
    } catch (ConfigurationConflictException e) {
        healthyCheckMessage = "An unexpected error occurred! Templates were in a conflicted state.";
        healthyCheckMessage += "\n\nNo automatic upgrade of the context configuration possible.";
        PlatformUIUtil.openErrorDialog(healthyCheckMessage, e);
        LOG.error(healthyCheckMessage, e);
    } catch (InvalidConfigurationException e) {
        // Won't be reached anymore
        healthyCheckMessage = firstStep + "OK.";
        healthyCheckMessage += secondStep + "INVALID!";
        if (generatorConfProj != null && generatorConfProj.getLocationURI() != null) {
            Path configurationProject = Paths.get(generatorConfProj.getLocationURI());
            ContextConfigurationVersion currentVersion = new ContextConfigurationUpgrader().resolveLatestCompatibleSchemaVersion(configurationProject);
            if (currentVersion != null) {
                // upgrade possible
                healthyCheckMessage += "\n\nAutomatic upgrade of the context configuration available.\n" + "Detected: " + currentVersion + " / Currently Supported: " + ContextConfigurationVersion.getLatest();
                this.report = openErrorDialogWithContextUpgrade(healthyCheckMessage, configurationProject, BackupPolicy.ENFORCE_BACKUP);
                healthyCheckMessage = MessageUtil.enrichMsgIfMultiError(healthyCheckMessage, this.report);
                if (!this.report.containsError(RuntimeException.class)) {
                    // re-run Health Check
                    Display.getCurrent().asyncExec(new Runnable() {

                        @Override
                        public void run() {
                            execute();
                        }
                    });
                }
            } else {
                healthyCheckMessage += "\n\nNo automatic upgrade of the context configuration possible. " + "Maybe just a mistake in the context configuration?";
                healthyCheckMessage += "\n\n=> " + e.getMessage();
                healthyCheckMessage = MessageUtil.enrichMsgIfMultiError(healthyCheckMessage, this.report);
                PlatformUIUtil.openErrorDialog(healthyCheckMessage, null);
            }
        } else {
            healthyCheckMessage += "\n\nCould not find configuration.";
            PlatformUIUtil.openErrorDialog(healthyCheckMessage, null);
        }
        LOG.warn(healthyCheckMessage, e);
    } catch (Throwable e) {
        healthyCheckMessage = "An unexpected error occurred! Templates were not found.";
        if (this.report != null && healthyCheckMessage != null) {
            healthyCheckMessage = MessageUtil.enrichMsgIfMultiError(healthyCheckMessage, this.report);
        }
        PlatformUIUtil.openErrorDialog(healthyCheckMessage, e);
        LOG.error(healthyCheckMessage, e);
    }
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(java.nio.file.Path) ConfigurationConflictException(com.devonfw.cobigen.api.exception.ConfigurationConflictException) ContextConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.ContextConfigurationUpgrader) GeneratorProjectNotExistentException(com.devonfw.cobigen.eclipse.common.exceptions.GeneratorProjectNotExistentException) File(java.io.File) IProject(org.eclipse.core.resources.IProject) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) ContextConfigurationVersion(com.devonfw.cobigen.impl.config.constant.ContextConfigurationVersion)

Example 3 with ContextConfigurationVersion

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

the class ContextConfigurationUpgraderTest method testCorrectUpgrade_v2_0_TO_LATEST.

/**
 * Tests the valid upgrade of a context configuration from version v2.0 to latest version. Please make sure that
 * .../ContextConfigurationUpgraderTest/valid-latest_version exists
 *
 * @throws Exception test fails
 */
@Test
public void testCorrectUpgrade_v2_0_TO_LATEST() throws Exception {
    // preparation
    File tmpTargetConfig = this.tempFolder.newFile(ConfigurationConstants.CONTEXT_CONFIG_FILENAME);
    File sourceTestdata = new File(testFileRootPath + "valid-v2.0/" + ConfigurationConstants.CONTEXT_CONFIG_FILENAME);
    Files.copy(sourceTestdata, tmpTargetConfig);
    ContextConfigurationUpgrader sut = new ContextConfigurationUpgrader();
    ContextConfigurationVersion version = sut.resolveLatestCompatibleSchemaVersion(this.tempFolder.getRoot().toPath());
    assertThat(version).as("Source Version").isEqualTo(ContextConfigurationVersion.v2_0);
    sut.upgradeConfigurationToLatestVersion(this.tempFolder.getRoot().toPath(), BackupPolicy.ENFORCE_BACKUP);
    assertThat(tmpTargetConfig.toPath().resolveSibling("context.bak.xml").toFile()).exists().hasSameContentAs(sourceTestdata);
    version = sut.resolveLatestCompatibleSchemaVersion(this.tempFolder.getRoot().toPath());
    assertThat(version).as("Target version").isEqualTo(ContextConfigurationVersion.getLatest());
    XMLUnit.setIgnoreWhitespace(true);
    new XMLTestCase() {
    }.assertXMLEqual(new FileReader(testFileRootPath + "valid-" + ContextConfigurationVersion.getLatest() + "/" + ConfigurationConstants.CONTEXT_CONFIG_FILENAME), new FileReader(tmpTargetConfig));
}
Also used : ContextConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.ContextConfigurationUpgrader) XMLTestCase(org.custommonkey.xmlunit.XMLTestCase) FileReader(java.io.FileReader) File(java.io.File) ContextConfigurationVersion(com.devonfw.cobigen.impl.config.constant.ContextConfigurationVersion) Test(org.junit.Test) AbstractUnitTest(com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)

Example 4 with ContextConfigurationVersion

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

the class ContextConfigurationUpgraderTest method testCorrectLatestSchemaDetection.

/**
 * Tests if latest context configuration is compatible to latest schema version.
 *
 * @throws Exception test fails
 */
@Test
public void testCorrectLatestSchemaDetection() throws Exception {
    // preparation
    File targetConfig = new File(testFileRootPath + "valid-" + ContextConfigurationVersion.getLatest());
    ContextConfigurationVersion version = new ContextConfigurationUpgrader().resolveLatestCompatibleSchemaVersion(targetConfig.toPath());
    assertThat(version).isEqualTo(ContextConfigurationVersion.getLatest());
}
Also used : ContextConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.ContextConfigurationUpgrader) File(java.io.File) ContextConfigurationVersion(com.devonfw.cobigen.impl.config.constant.ContextConfigurationVersion) Test(org.junit.Test) AbstractUnitTest(com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)

Aggregations

ContextConfigurationVersion (com.devonfw.cobigen.impl.config.constant.ContextConfigurationVersion)4 ContextConfigurationUpgrader (com.devonfw.cobigen.impl.config.upgrade.ContextConfigurationUpgrader)3 File (java.io.File)3 InvalidConfigurationException (com.devonfw.cobigen.api.exception.InvalidConfigurationException)2 AbstractUnitTest (com.devonfw.cobigen.unittest.config.common.AbstractUnitTest)2 Path (java.nio.file.Path)2 Test (org.junit.Test)2 ConfigurationConflictException (com.devonfw.cobigen.api.exception.ConfigurationConflictException)1 GeneratorProjectNotExistentException (com.devonfw.cobigen.eclipse.common.exceptions.GeneratorProjectNotExistentException)1 ContextConfiguration (com.devonfw.cobigen.impl.config.entity.io.ContextConfiguration)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 StreamSource (javax.xml.transform.stream.StreamSource)1