Search in sources :

Example 11 with InvalidConfigurationException

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

the class OpenAPIInputReader method extractComponents.

/**
 * Get a list of entities defined at an OpenaApi3 file returning a list of {@link EntityDef}'s
 *
 * @param openApi the model for an OpenApi3 file
 * @return list of entities
 */
private List<EntityDef> extractComponents(OpenApi3 openApi) {
    HeaderDef header = new HeaderDef();
    header.setServers(extractServers(openApi));
    header.setInfo(extractInfo(openApi));
    List<EntityDef> objects = new LinkedList<>();
    this.components = new LinkedList<>();
    for (String key : openApi.getSchemas().keySet()) {
        EntityDef entityDef = new EntityDef();
        entityDef.setName(key);
        entityDef.setDescription(openApi.getSchema(key).getDescription());
        ComponentDef componentDef = new ComponentDef();
        entityDef.setProperties(extractProperties(openApi, key));
        // If no x-component tag was found on the input file, throw invalid configuration
        if (openApi.getSchema(key).getExtensions().get(Constants.COMPONENT_EXT) == null) {
            throw new InvalidConfigurationException("Your Swagger file is not correctly formatted, it lacks of x-component tags.\n\n" + "Go to the documentation " + "(https://github.com/devonfw/cobigen/wiki/cobigen-openapiplugin#full-example) " + "to check how to correctly format it." + " If it is still not working, check your file indentation!");
        }
        String componentName = openApi.getSchema(key).getExtensions().get(Constants.COMPONENT_EXT).toString();
        entityDef.setComponentName(componentName);
        // If the path's tag was not found on the input file, throw invalid configuration
        if (openApi.getPaths().size() == 0) {
            throw new InvalidConfigurationException("Your Swagger file is not correctly formatted, it lacks of the correct path syntax.\n\n" + "Go to the documentation (https://github.com/devonfw/cobigen" + "/wiki/cobigen-openapiplugin#paths) to check how to correctly format it." + " If it is still not working, check your file indentation!");
        }
        // Sets a Map containing all the extensions of the info part of the OpenAPI file
        if (Overlay.isPresent((JsonOverlay<?>) openApi.getInfo())) {
            entityDef.setUserPropertiesMap(openApi.getInfo().getExtensions());
        }
        // Traverse the extensions of the entity for setting those attributes to the Map
        Iterator<String> it = openApi.getSchema(key).getExtensions().keySet().iterator();
        while (it.hasNext()) {
            String keyMap = it.next();
            entityDef.setUserProperty(keyMap, openApi.getSchema(key).getExtensions().get(keyMap).toString());
        }
        componentDef.setPaths(extractPaths(openApi.getPaths(), componentName));
        componentDef.setName(componentName);
        this.components.add(componentDef);
        entityDef.setComponent(componentDef);
        entityDef.setHeader(header);
        objects.add(entityDef);
    }
    return objects;
}
Also used : ComponentDef(com.devonfw.cobigen.openapiplugin.model.ComponentDef) HeaderDef(com.devonfw.cobigen.openapiplugin.model.HeaderDef) LinkedList(java.util.LinkedList) EntityDef(com.devonfw.cobigen.openapiplugin.model.EntityDef) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 12 with InvalidConfigurationException

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

the class OpenAPIMatcher method resolveVariables.

@Override
public Map<String, String> resolveVariables(MatcherTo matcher, List<VariableAssignmentTo> variableAssignments, GenerationReportTo report) throws InvalidConfigurationException {
    Map<String, String> resolvedVariables = new HashMap<>();
    VariableType variableType = null;
    for (VariableAssignmentTo va : variableAssignments) {
        try {
            variableType = Enum.valueOf(VariableType.class, va.getType().toUpperCase());
        } catch (InvalidConfigurationException e) {
            throw new CobiGenRuntimeException("Matcher or VariableAssignment type " + matcher.getType() + " not registered!", e);
        }
        switch(variableType) {
            case CONSTANT:
                resolvedVariables.put(va.getVarName(), va.getValue());
                break;
            case EXTENSION:
                Class<?> targetObject = matcher.getTarget().getClass();
                try {
                    Field field = targetObject.getDeclaredField("extensionProperties");
                    field.setAccessible(true);
                    Object extensionProperties = field.get(matcher.getTarget());
                    String attributeValue = getExtendedProperty((Map<String, Object>) extensionProperties, va.getValue());
                    resolvedVariables.put(va.getVarName(), attributeValue);
                } catch (NoSuchFieldException | SecurityException e) {
                    if (va.isMandatory()) {
                        String errorMessage = Constants.getMandatoryMessage(true, va.getValue());
                        report.addError(new CobiGenRuntimeException(errorMessage));
                        LOG.error(errorMessage);
                    } else {
                        String warningMessage = Constants.getMandatoryMessage(false, va.getValue());
                        report.addWarning(warningMessage);
                        resolvedVariables.put(va.getVarName(), "");
                        LOG.warn(warningMessage);
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new CobiGenRuntimeException("This is a programming error, please report an issue on github", e);
                }
                break;
            case PROPERTY:
                Class<?> target = matcher.getTarget().getClass();
                try {
                    Field field = target.getDeclaredField(va.getValue());
                    field.setAccessible(true);
                    Object o = field.get(matcher.getTarget());
                    resolvedVariables.put(va.getVarName(), o.toString());
                } catch (NoSuchFieldException | SecurityException e) {
                    LOG.warn("The property {} was requested in a variable assignment although the input does not provide this property. Setting it to empty", matcher.getValue());
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new CobiGenRuntimeException("This is a programming error, please report an issue on github", e);
                }
                break;
        }
    }
    return resolvedVariables;
}
Also used : VariableAssignmentTo(com.devonfw.cobigen.api.to.VariableAssignmentTo) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) HashMap(java.util.HashMap) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) Field(java.lang.reflect.Field)

Example 13 with InvalidConfigurationException

use of com.devonfw.cobigen.api.exception.InvalidConfigurationException 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 14 with InvalidConfigurationException

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

the class JavaMatcher method resolveRegexValue.

/**
 * Resolves the variable assignments of type {@link VariableType#REGEX}
 *
 * @param matcherType type of the matcher
 * @param matcherValue value of the matcher
 * @param stringToMatch string to match
 * @param va {@link VariableAssignmentTo} to be resolved
 * @return the resolved variable
 * @throws InvalidConfigurationException thrown if the matcher type and matcher value does not work in combination
 * @author mbrunnli (08.04.2014)
 */
private String resolveRegexValue(MatcherType matcherType, String matcherValue, String stringToMatch, VariableAssignmentTo va) throws InvalidConfigurationException {
    Pattern p = Pattern.compile(matcherValue);
    Matcher m = p.matcher(stringToMatch);
    if (m != null) {
        if (m.matches()) {
            try {
                String value = m.group(Integer.parseInt(va.getValue()));
                // thrown when value == null
                return value;
            } catch (NumberFormatException e) {
                LOG.error("The VariableAssignment '{}' of Matcher of type '{}' should have an integer as value" + " representing a regular expression group.\nCurrent value: '{}'", va.getType().toUpperCase(), matcherType.toString(), va.getValue(), e);
                throw new InvalidConfigurationException("The VariableAssignment '" + va.getType().toUpperCase() + "' of Matcher of type '" + matcherType.toString() + "' should have an integer as value representing a regular expression group.\nCurrent value: '" + va.getValue() + "'");
            } catch (IndexOutOfBoundsException e) {
                LOG.error("The VariableAssignment '{}' of Matcher of type '{}' declares a regular expression" + " group not in range.\nCurrent value: '{}'", va.getType().toUpperCase(), matcherType.toString(), va.getValue(), e);
                throw new InvalidConfigurationException("The VariableAssignment '" + va.getType().toUpperCase() + "' of Matcher of type '" + matcherType.toString() + "' declares a regular expression group not in range.\nCurrent value: '" + va.getValue() + "'");
            }
        }
    // else should not occur as #matches(...) will be called beforehand
    } else {
        throw new InvalidConfigurationException("The VariableAssignment type 'REGEX' can only be combined with matcher type 'FQN' or 'PACKAGE'");
    }
    // should not occur
    return null;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 15 with InvalidConfigurationException

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

the class TypeScriptMatcher method resolveRegexValue.

/**
 * Resolves the variable assignments of type {@link VariableType#REGEX}
 *
 * @param matcherType type of the matcher
 * @param matcherValue value of the matcher
 * @param stringToMatch string to match
 * @param va {@link VariableAssignmentTo} to be resolved
 * @return the resolved variable
 * @throws InvalidConfigurationException thrown if the matcher type and matcher value does not work in combination
 * @author mbrunnli (08.04.2014)
 */
private String resolveRegexValue(MatcherType matcherType, String matcherValue, String stringToMatch, VariableAssignmentTo va) throws InvalidConfigurationException {
    Pattern p = Pattern.compile(matcherValue);
    Matcher m = p.matcher(stringToMatch);
    if (m != null) {
        if (m.matches()) {
            try {
                String value = m.group(Integer.parseInt(va.getValue()));
                // thrown when value == null
                return value;
            } catch (NumberFormatException e) {
                throw new InvalidConfigurationException("The VariableAssignment '" + va.getType().toUpperCase() + "' of Matcher of type '" + matcherType.toString() + "' should have an integer as value representing a regular expression group.\nCurrent value: '" + va.getValue() + "'", e);
            } catch (IndexOutOfBoundsException e) {
                throw new InvalidConfigurationException("The VariableAssignment '" + va.getType().toUpperCase() + "' of Matcher of type '" + matcherType.toString() + "' declares a regular expression group not in range.\nCurrent value: '" + va.getValue() + "'", e);
            }
        }
    // else should not occur as #matches(...) will be called beforehand
    } else {
        throw new InvalidConfigurationException("The VariableAssignment type 'REGEX' can only be combined with matcher type 'FQN' or 'PACKAGE'");
    }
    // should not occur
    return null;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) 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