Search in sources :

Example 21 with CobiGenRuntimeException

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

the class MavenUtil method runCommand.

/**
 * Execute any command in the given execution directory with the given arguments
 *
 * @param execDir the execution directory the command should run in
 * @param args the maven arguments to execute
 * @return the process output
 */
private static String runCommand(Path execDir, List<String> args) {
    // https://stackoverflow.com/a/66801171
    args.add("-Djansi.force=true");
    args.add("-Djansi.passthrough=true");
    args.add("-B");
    args.add("-q");
    args.add("-Dorg.slf4j.simpleLogger.defaultLogLevel=" + (LOG.isDebugEnabled() ? "DEBUG" : "INFO"));
    args.add("-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN");
    try {
        StartedProcess process = new ProcessExecutor().readOutput(true).destroyOnExit().directory(execDir.toFile()).environment("MAVEN_OPTS", replaceAllUnixPathsOnWin(System.getenv("MAVEN_OPTS"))).environment("M2_REPO", replaceAllUnixPathsOnWin(System.getenv("M2_REPO"))).command(args).redirectError(Slf4jStream.of(LoggerFactory.getLogger(MavenUtil.class.getName() + "." + "dep-build")).asError()).redirectOutput(Slf4jStream.of(LoggerFactory.getLogger(MavenUtil.class.getName() + "." + "dep-build")).asInfo()).start();
        Future<ProcessResult> future = process.getFuture();
        ProcessResult processResult = future.get();
        if (processResult.getExitValue() != 0) {
            LOG.error("Error while getting all the needed transitive dependencies. Please check your internet connection.");
            throw new CobiGenRuntimeException("Unable to build cobigen dependencies");
        }
        return processResult.getOutput().getString("UTF-8");
    } catch (InterruptedException | ExecutionException | IOException e) {
        throw new CobiGenRuntimeException("Unable to build cobigen dependencies", e);
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) ProcessResult(org.zeroturnaround.exec.ProcessResult) IOException(java.io.IOException) ProcessExecutor(org.zeroturnaround.exec.ProcessExecutor) ExecutionException(java.util.concurrent.ExecutionException) StartedProcess(org.zeroturnaround.exec.StartedProcess)

Example 22 with CobiGenRuntimeException

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

the class SystemUtil method determineMvnPath.

/**
 * @return the absolute path of the mvn executable if available, otherwise null
 */
public static Path determineMvnPath() {
    if (MVN_EXEC != null) {
        return MVN_EXEC;
    }
    ProcessBuilder processBuilder = new ProcessBuilder();
    if (OS.contains("win")) {
        processBuilder.command("where", "mvn");
    } else {
        processBuilder.command("which", "mvn");
    }
    String mvnExecPath = null;
    try {
        Process process = processBuilder.start();
        try (InputStream in = process.getInputStream();
            InputStreamReader inr = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(inr)) {
            List<String> foundEntries = reader.lines().collect(Collectors.toList());
            LOG.debug("Found following executables: ");
            foundEntries.forEach(e -> LOG.debug("  - {}", e));
            if (foundEntries.size() > 0) {
                if (foundEntries.size() > 1 && OS.contains("win")) {
                    Pattern p = Pattern.compile(".+mvn\\.(bat|cmd)");
                    Optional<String> foundPath = foundEntries.stream().filter(path -> p.matcher(path).matches()).findFirst();
                    if (foundPath.isPresent()) {
                        mvnExecPath = foundPath.get();
                        LOG.debug("Taking {} instead of first entry as detected windows OS", mvnExecPath);
                    }
                }
                if (mvnExecPath == null) {
                    mvnExecPath = foundEntries.get(0);
                }
            }
            int retVal = process.waitFor();
            if (retVal == 0 && StringUtils.isNotEmpty(mvnExecPath)) {
                LOG.info("Determined mvn executable to be located in {}", mvnExecPath);
                MVN_EXEC = Paths.get(mvnExecPath);
            } else {
                LOG.warn("Could not determine mvn executable location. 'which mvn' returned {}", retVal);
            }
        }
    } catch (InterruptedException | IOException e) {
        LOG.warn("Could not determine mvn executable location, trying to look for environment variables for maven home.", e);
    }
    if (MVN_EXEC == null) {
        String m2Home = System.getenv().get("MAVEN_HOME");
        if (m2Home == null) {
            m2Home = System.getenv().get("M2_HOME");
            if (m2Home == null) {
                if ("true".equals(System.getenv("TRAVIS"))) {
                    // just travis
                    m2Home = "/usr/local/maven";
                } else {
                    throw new CobiGenRuntimeException("Could not determine maven home from environment variables MAVEN_HOME or M2_HOME!");
                }
            }
        }
        MVN_EXEC = getMvnExecutable(m2Home);
        LOG.info("Determined maven executable at {}", MVN_EXEC);
    } else {
        LOG.debug("Detected to run on OS {}", OS);
        MVN_EXEC = convertUnixPathToWinOnWin(mvnExecPath);
    }
    return MVN_EXEC;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) Logger(org.slf4j.Logger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) List(java.util.List) Matcher(java.util.regex.Matcher) Paths(java.nio.file.Paths) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) Pattern(java.util.regex.Pattern) Path(java.nio.file.Path) InputStream(java.io.InputStream) Pattern(java.util.regex.Pattern) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) InputStreamReader(java.io.InputStreamReader) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader)

Example 23 with CobiGenRuntimeException

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

the class OpenAPIInputReader method extractParameters.

/**
 * @param operationOverlay overlay of the operation to get all parameters from
 * @return a list of {@link ParameterDef} from a collection of parameters of an operation
 */
private List<ParameterDef> extractParameters(Overlay<Operation> operationOverlay) {
    Collection<? extends Parameter> parameters = operationOverlay.get().getParameters();
    Collection<String> tags = operationOverlay.get().getTags();
    RequestBody requestBody = operationOverlay.get().getRequestBody();
    List<ParameterDef> parametersList = new LinkedList<>();
    ParameterDef parameter;
    for (Parameter param : parameters) {
        parameter = new ParameterDef();
        parameter.setIsBody(false);
        switch(param.getIn()) {
            case "path":
                parameter.setInPath(true);
                break;
            case "query":
                parameter.setInQuery(true);
                break;
            case "header":
                parameter.setInHeader(true);
                break;
        }
        parameter.setName(param.getName());
        Schema schema = param.getSchema();
        Map<String, Object> constraints = extractConstraints(schema);
        if (param.isRequired()) {
            constraints.put(ModelConstant.NOTNULL, true);
        } else {
            constraints.put(ModelConstant.NOTNULL, false);
        }
        parameter.setConstraints(constraints);
        parameter.setDescription(param.getDescription());
        if (schema.getType().equals(Constants.ARRAY)) {
            parameter.setIsCollection(true);
            if (schema.getItemsSchema() != null) {
                parameter.setIsEntity(true);
            }
        }
        try {
            if (Overlay.isReference(operationOverlay.getOverlay(), param.getKey())) {
                parameter.setIsEntity(true);
                parameter.setType(schema.getName());
            } else {
                parameter.setType(schema.getType());
                parameter.setFormat(schema.getFormat());
            }
        } catch (NullPointerException e) {
            throw new CobiGenRuntimeException("Error at parameter " + param.getName() + ". Invalid OpenAPI file, path parameters need to have a schema defined.");
        }
        parametersList.add(parameter);
    }
    if (requestBody != null) {
        Schema mediaSchema;
        for (String media : requestBody.getContentMediaTypes().keySet()) {
            parameter = new ParameterDef();
            parameter.setIsBody(true);
            parameter.setMediaType(media);
            if (tags.contains(Constants.SEARCH_CRITERIA) || tags.contains(Constants.SEARCH_CRITERIA.toLowerCase())) {
                parameter.setIsSearchCriteria(true);
                parameter.setName("criteria");
            }
            if (requestBody.getContentMediaTypes().get(media).getSchema() != null) {
                mediaSchema = requestBody.getContentMediaTypes().get(media).getSchema();
                parameter.setIsEntity(true);
                parameter.setType(requestBody.getContentMediaType(media).getSchema().getName());
                if (!parameter.getIsSearchCriteria()) {
                    char[] c = mediaSchema.getName().toCharArray();
                    c[0] = Character.toLowerCase(c[0]);
                    parameter.setName(new String(c));
                }
            }
            if (parameter.getType() != null) {
                Map<String, Object> constraints = new HashMap<>();
                constraints.put(ModelConstant.NOTNULL, true);
                parameter.setConstraints(constraints);
                parametersList.add(parameter);
            }
        }
    }
    return parametersList;
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) ParameterDef(com.devonfw.cobigen.openapiplugin.model.ParameterDef) HashMap(java.util.HashMap) Schema(com.reprezen.kaizen.oasparser.model3.Schema) LinkedList(java.util.LinkedList) Parameter(com.reprezen.kaizen.oasparser.model3.Parameter) RequestBody(com.reprezen.kaizen.oasparser.model3.RequestBody)

Example 24 with CobiGenRuntimeException

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

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

the class FreeMarkerTemplateEngine method process.

@Override
public void process(TextTemplate template, Map<String, Object> model, Writer out, String outputEncoding) {
    Template fmTemplate = null;
    try {
        fmTemplate = this.freeMarkerConfig.getTemplate(template.getRelativeTemplatePath());
    } catch (ParseException e) {
        throw new CobiGenRuntimeException("Could not parse FreeMarker template: " + template.getAbsoluteTemplatePath() + ". (FreeMarker v" + FreemarkerMetadata.VERSION + " )", e);
    } catch (Throwable e) {
        throw new CobiGenRuntimeException("An error occured while retrieving the FreeMarker template: " + template.getAbsoluteTemplatePath() + " from the FreeMarker configuration. (FreeMarker v" + FreemarkerMetadata.VERSION + " )", e);
    }
    if (fmTemplate != null) {
        try {
            Environment env = fmTemplate.createProcessingEnvironment(model, out);
            env.setOutputEncoding(outputEncoding);
            // no duplicate logging
            env.setLogTemplateExceptions(false);
            env.process();
        } catch (TemplateException e) {
            throw new CobiGenRuntimeException("An error occurred while generating the template: " + template.getAbsoluteTemplatePath() + " (FreeMarker v" + FreemarkerMetadata.VERSION + ")", e);
        } catch (Throwable e) {
            throw new CobiGenRuntimeException("An unkonwn error occurred while generating the template: " + template.getAbsoluteTemplatePath() + " (FreeMarker v" + FreemarkerMetadata.VERSION + ")", e);
        }
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) TemplateException(freemarker.template.TemplateException) Environment(freemarker.core.Environment) ParseException(freemarker.core.ParseException) TextTemplate(com.devonfw.cobigen.api.extension.TextTemplate) Template(freemarker.template.Template)

Aggregations

CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)43 IOException (java.io.IOException)22 Path (java.nio.file.Path)15 File (java.io.File)8 LoggerFactory (org.slf4j.LoggerFactory)5 InvalidConfigurationException (com.devonfw.cobigen.api.exception.InvalidConfigurationException)4 TextTemplateEngine (com.devonfw.cobigen.api.extension.TextTemplateEngine)4 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)4 Trigger (com.devonfw.cobigen.impl.config.entity.Trigger)4 InputStream (java.io.InputStream)4 URL (java.net.URL)4 URLClassLoader (java.net.URLClassLoader)4 CobiGen (com.devonfw.cobigen.api.CobiGen)3 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)3 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)3 BackupFailedException (com.devonfw.cobigen.impl.exceptions.BackupFailedException)3 Paths (java.nio.file.Paths)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Logger (org.slf4j.Logger)3