Search in sources :

Example 1 with GenerableArtifact

use of com.devonfw.cobigen.api.to.GenerableArtifact in project cobigen by devonfw.

the class GenerateMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    CobiGen cobiGen = createCobiGenInstance();
    List<Object> inputs = collectInputs(cobiGen);
    if (inputs.isEmpty()) {
        getLog().info("No inputs specified for generation!");
        getLog().info("");
        return;
    }
    if ((this.templates == null || this.templates.isEmpty()) && (this.increments == null || this.increments.isEmpty())) {
        getLog().info("No templates/increments specified for generation!");
        getLog().info("");
        return;
    }
    List<GenerableArtifact> generableArtifacts = collectIncrements(cobiGen, inputs);
    generableArtifacts.addAll(collectTemplates(cobiGen, inputs));
    try {
        for (Object input : inputs) {
            getLog().debug("Invoke CobiGen for input of class " + input.getClass().getCanonicalName());
            GenerationReportTo report = cobiGen.generate(input, generableArtifacts, Paths.get(this.destinationRoot.toURI()), this.forceOverride, (task, progress) -> {
            });
            if (!report.isSuccessful()) {
                for (Throwable e : report.getErrors()) {
                    getLog().error(e.getMessage(), e);
                }
                throw new MojoFailureException("Generation not successfull", report.getErrors().get(0));
            }
            if (report.getGeneratedFiles().isEmpty() && this.failOnNothingGenerated) {
                throw new MojoFailureException("The execution '" + this.execution.getExecutionId() + "' of cobigen-maven-plugin resulted in no file to be generated!");
            }
        }
    } catch (CobiGenRuntimeException e) {
        getLog().error(e.getMessage(), e);
        throw new MojoFailureException(e.getMessage(), e);
    } catch (MojoFailureException e) {
        throw e;
    } catch (Throwable e) {
        getLog().error("An error occured while executing CobiGen: " + e.getMessage(), e);
        throw new MojoFailureException("An error occured while executing CobiGen: " + e.getMessage(), e);
    }
}
Also used : GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) MojoFailureException(org.apache.maven.plugin.MojoFailureException) CobiGen(com.devonfw.cobigen.api.CobiGen)

Example 2 with GenerableArtifact

use of com.devonfw.cobigen.api.to.GenerableArtifact in project cobigen by devonfw.

the class GenerationProcessorImpl method flatten.

/**
 * Flattens the {@link GenerableArtifact}s to a list of {@link TemplateTo}s also removing duplicates.
 *
 * @param generableArtifacts {@link List} of {@link GenerableArtifact}s to be flattened
 * @return {@link Collection} of collected {@link TemplateTo}s
 */
private Collection<TemplateTo> flatten(List<? extends GenerableArtifact> generableArtifacts) {
    // create Map to remove duplicates by ID
    Map<String, TemplateTo> templateIdToTemplateMap = Maps.newHashMap();
    for (GenerableArtifact artifact : generableArtifacts) {
        if (artifact instanceof TemplateTo) {
            TemplateTo template = (TemplateTo) artifact;
            checkAndAddToTemplateMap(templateIdToTemplateMap, template);
        } else if (artifact instanceof IncrementTo) {
            for (TemplateTo template : ((IncrementTo) artifact).getTemplates()) {
                checkAndAddToTemplateMap(templateIdToTemplateMap, template);
            }
        } else {
            throw new IllegalArgumentException("Unknown GenerableArtifact type '" + artifact.getClass().getCanonicalName() + "'.");
        }
    }
    return new TreeSet<>(templateIdToTemplateMap.values());
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) TreeSet(java.util.TreeSet) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 3 with GenerableArtifact

use of com.devonfw.cobigen.api.to.GenerableArtifact in project cobigen by devonfw.

the class GenerateCommand method search.

/**
 * Search for generable artifacts (increments or templates) matching the user input. Generable artifacts similar to
 * the given search string or containing it are returned.
 *
 * @param <T> The type of generable artifacts
 * @param userInput the user's wished increment or template
 * @param matching all increments or templates that are valid to the input file(s)
 * @param c class type, specifies whether Templates or Increments should be preprocessed
 * @return Increments or templates matching the search string
 */
private <T extends GenerableArtifact> List<T> search(String userInput, List<T> matching, Class<?> c) {
    boolean isIncrements = c.getSimpleName().equals(IncrementTo.class.getSimpleName());
    Map<T, Double> scores = new HashMap<>();
    for (int i = 0; i < matching.size(); i++) {
        if (!isIncrements) {
            String description = ((TemplateTo) matching.get(i)).getId();
            JaccardDistance distance = new JaccardDistance();
            scores.put(matching.get(i), distance.apply(description.toUpperCase(), userInput.toUpperCase()));
        } else {
            String description = ((IncrementTo) matching.get(i)).getDescription();
            String id = ((IncrementTo) matching.get(i)).getId();
            JaccardDistance distance = new JaccardDistance();
            double descriptionDistance = distance.apply(description.toUpperCase(), userInput.toUpperCase());
            double idDistance = distance.apply(id.toUpperCase(), userInput.toUpperCase());
            scores.put(matching.get(i), Math.min(idDistance, descriptionDistance));
        }
    }
    Map<T, Double> sorted = scores.entrySet().stream().sorted(comparingByValue()).collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, LinkedHashMap::new));
    List<T> chosen = new ArrayList<>();
    for (T artifact : sorted.keySet()) {
        T tmp = isIncrements ? artifact : artifact;
        if (!isIncrements) {
            String description = ((TemplateTo) artifact).getId();
            if (description.toUpperCase().contains(userInput.toUpperCase()) || sorted.get(artifact) <= this.SELECTION_THRESHOLD) {
                chosen.add(tmp);
            }
        } else {
            String description = ((IncrementTo) artifact).getDescription();
            String id = ((IncrementTo) artifact).getId();
            if (description.equalsIgnoreCase(userInput) || id.equalsIgnoreCase(userInput)) {
                chosen.add(tmp);
                return chosen;
            }
            if ((description.toUpperCase().contains(userInput.toUpperCase()) || id.toUpperCase().contains(userInput.toUpperCase())) || sorted.get(artifact) <= this.SELECTION_THRESHOLD) {
                chosen.add(tmp);
            }
        }
    }
    return chosen;
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException) Parameters(picocli.CommandLine.Parameters) LoggerFactory(org.slf4j.LoggerFactory) Entry.comparingByValue(java.util.Map.Entry.comparingByValue) HashMap(java.util.HashMap) InputMismatchException(java.util.InputMismatchException) CobiGen(com.devonfw.cobigen.api.CobiGen) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) CobiGenCLI(com.devonfw.cobigen.cli.CobiGenCLI) URI(java.net.URI) FormatterException(com.google.googlejavaformat.java.FormatterException) Command(picocli.CommandLine.Command) Path(java.nio.file.Path) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) ConfigurationFinder(com.devonfw.cobigen.impl.util.ConfigurationFinder) UserAbortException(com.devonfw.cobigen.cli.exceptions.UserAbortException) ValidationUtils(com.devonfw.cobigen.cli.utils.ValidationUtils) Logger(org.slf4j.Logger) Tuple(com.devonfw.cobigen.api.util.Tuple) Files(java.nio.file.Files) MavenUtil(com.devonfw.cobigen.api.util.MavenUtil) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ParsingUtils(com.devonfw.cobigen.cli.utils.ParsingUtils) StandardCharsets(java.nio.charset.StandardCharsets) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGenUtils(com.devonfw.cobigen.cli.utils.CobiGenUtils) List(java.util.List) Option(picocli.CommandLine.Option) MessagesConstants(com.devonfw.cobigen.cli.constants.MessagesConstants) Paths(java.nio.file.Paths) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) JaccardDistance(org.apache.commons.text.similarity.JaccardDistance) FileSystemUtil(com.devonfw.cobigen.impl.util.FileSystemUtil) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JaccardDistance(org.apache.commons.text.similarity.JaccardDistance) ArrayList(java.util.ArrayList) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 4 with GenerableArtifact

use of com.devonfw.cobigen.api.to.GenerableArtifact in project cobigen by devonfw.

the class GenerateCommand method generate.

/**
 * Generates new templates or increments using the inputFile from the inputProject.
 *
 * @param <T> type of generable artifacts to generate
 * @param inputFile input file to be selected by the user
 * @param input parsed by CobiGen read method
 * @param inputProject input project where the input file is located. We need this in order to build the classpath of
 *        the input file
 * @param generableArtifacts the list of increments or templates that the user is going to use for generation
 * @param cg Initialized CobiGen instance
 * @param c class type, specifies whether Templates or Increments should be preprocessed
 */
public <T extends GenerableArtifact> void generate(Path inputFile, Object input, Path inputProject, List<T> generableArtifacts, CobiGen cg, Class<T> c) {
    boolean isIncrements = c.getSimpleName().equals(IncrementTo.class.getSimpleName());
    if (this.outputRootPath == null) {
        // If user did not specify the output path of the generated files, we can use
        // the current project folder
        setOutputRootPath(inputProject);
    }
    GenerationReportTo report = null;
    LOG.info("Generating {} for input '{}, this can take a while...", isIncrements ? "increments" : "templates", inputFile);
    report = cg.generate(input, generableArtifacts, this.outputRootPath.toAbsolutePath(), false, (task, progress) -> {
    });
    ValidationUtils.checkGenerationReport(report);
    Set<Path> generatedJavaFiles = report.getGeneratedFiles().stream().filter(e -> e.getFileName().endsWith(".java")).collect(Collectors.toSet());
    if (!generatedJavaFiles.isEmpty()) {
        try {
            ParsingUtils.formatJavaSources(generatedJavaFiles);
        } catch (FormatterException e) {
            LOG.warn("Generation was successful but we were not able to format your code. Maybe you will see strange formatting.");
        }
    }
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException) Parameters(picocli.CommandLine.Parameters) LoggerFactory(org.slf4j.LoggerFactory) Entry.comparingByValue(java.util.Map.Entry.comparingByValue) HashMap(java.util.HashMap) InputMismatchException(java.util.InputMismatchException) CobiGen(com.devonfw.cobigen.api.CobiGen) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) CobiGenCLI(com.devonfw.cobigen.cli.CobiGenCLI) URI(java.net.URI) FormatterException(com.google.googlejavaformat.java.FormatterException) Command(picocli.CommandLine.Command) Path(java.nio.file.Path) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) ConfigurationFinder(com.devonfw.cobigen.impl.util.ConfigurationFinder) UserAbortException(com.devonfw.cobigen.cli.exceptions.UserAbortException) ValidationUtils(com.devonfw.cobigen.cli.utils.ValidationUtils) Logger(org.slf4j.Logger) Tuple(com.devonfw.cobigen.api.util.Tuple) Files(java.nio.file.Files) MavenUtil(com.devonfw.cobigen.api.util.MavenUtil) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ParsingUtils(com.devonfw.cobigen.cli.utils.ParsingUtils) StandardCharsets(java.nio.charset.StandardCharsets) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGenUtils(com.devonfw.cobigen.cli.utils.CobiGenUtils) List(java.util.List) Option(picocli.CommandLine.Option) MessagesConstants(com.devonfw.cobigen.cli.constants.MessagesConstants) Paths(java.nio.file.Paths) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) JaccardDistance(org.apache.commons.text.similarity.JaccardDistance) FileSystemUtil(com.devonfw.cobigen.impl.util.FileSystemUtil) Path(java.nio.file.Path) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) FormatterException(com.google.googlejavaformat.java.FormatterException) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo)

Example 5 with GenerableArtifact

use of com.devonfw.cobigen.api.to.GenerableArtifact in project cobigen by devonfw.

the class GenerateMojo method collectIncrements.

/**
 * Generates all increments for each input.
 *
 * @param cobiGen generator instance to be used for generation
 * @param inputs to be used for generation
 * @return the collected increments to be generated
 * @throws MojoFailureException if the maven configuration does not match cobigen configuration (context.xml)
 */
private List<GenerableArtifact> collectIncrements(CobiGen cobiGen, List<Object> inputs) throws MojoFailureException {
    List<GenerableArtifact> generableArtifacts = new ArrayList<>();
    if (this.increments != null && !this.increments.isEmpty()) {
        if (this.increments.contains(ALL)) {
            if (this.increments.size() > 1) {
                throw new MojoFailureException("You specified the 'ALL' increment to generate all available increments next to another increment, which was most probably not intended.");
            }
            for (Object input : inputs) {
                generableArtifacts.addAll(cobiGen.getMatchingIncrements(input));
            }
        } else {
            for (Object input : inputs) {
                List<IncrementTo> matchingIncrements = cobiGen.getMatchingIncrements(input);
                List<String> configuredIncrements = new LinkedList<>(this.increments);
                for (IncrementTo increment : matchingIncrements) {
                    if (this.increments.contains(increment.getId())) {
                        generableArtifacts.add(increment);
                        configuredIncrements.remove(increment.getId());
                    }
                }
                // error handling for increments not found
                if (!configuredIncrements.isEmpty()) {
                    throw new MojoFailureException("Increments with ids '" + configuredIncrements + "' not matched for input '" + getStringRepresentation(input) + "' by provided CobiGen configuration.");
                }
            }
        }
    }
    return generableArtifacts;
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) ArrayList(java.util.ArrayList) MojoFailureException(org.apache.maven.plugin.MojoFailureException) LinkedList(java.util.LinkedList)

Aggregations

GenerableArtifact (com.devonfw.cobigen.api.to.GenerableArtifact)6 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)4 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)4 ArrayList (java.util.ArrayList)4 CobiGen (com.devonfw.cobigen.api.CobiGen)3 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)3 MojoFailureException (org.apache.maven.plugin.MojoFailureException)3 InputReaderException (com.devonfw.cobigen.api.exception.InputReaderException)2 MavenUtil (com.devonfw.cobigen.api.util.MavenUtil)2 Tuple (com.devonfw.cobigen.api.util.Tuple)2 CobiGenCLI (com.devonfw.cobigen.cli.CobiGenCLI)2 MessagesConstants (com.devonfw.cobigen.cli.constants.MessagesConstants)2 UserAbortException (com.devonfw.cobigen.cli.exceptions.UserAbortException)2 CobiGenUtils (com.devonfw.cobigen.cli.utils.CobiGenUtils)2 ParsingUtils (com.devonfw.cobigen.cli.utils.ParsingUtils)2 ValidationUtils (com.devonfw.cobigen.cli.utils.ValidationUtils)2 ConfigurationFinder (com.devonfw.cobigen.impl.util.ConfigurationFinder)2 FileSystemUtil (com.devonfw.cobigen.impl.util.FileSystemUtil)2 FormatterException (com.google.googlejavaformat.java.FormatterException)2 IOException (java.io.IOException)2