Search in sources :

Example 31 with CobiGen

use of com.devonfw.cobigen.api.CobiGen in project cobigen by devonfw.

the class InputReaderMatcherTest method testVariableAssignment_propertyName.

/**
 * Tests variable assignment resolution of PROPERTY type at the example of the component version
 *
 * @throws Exception test fails
 */
@Test
public void testVariableAssignment_propertyName() throws Exception {
    CobiGen cobigen = CobiGenFactory.create(Paths.get(testdataRoot, "templates").toUri());
    Object openApiFile = cobigen.read(Paths.get(testdataRoot, "one-component.yaml"), TestConstants.UTF_8);
    List<Object> inputObjects = cobigen.resolveContainers(openApiFile);
    String templateName = "testVariableAssignment_propertyName.txt";
    TemplateTo template = findTemplate(cobigen, inputObjects.get(0), templateName);
    File targetFolder = this.tmpFolder.newFolder();
    GenerationReportTo report = cobigen.generate(inputObjects.get(0), template, targetFolder.toPath());
    assertThat(report).isSuccessful();
    assertThat(targetFolder.toPath().resolve("testVariableAssignment_propertyName.txt").toFile()).exists().hasContent("Table");
}
Also used : GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGen(com.devonfw.cobigen.api.CobiGen) File(java.io.File) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) Test(org.junit.Test)

Example 32 with CobiGen

use of com.devonfw.cobigen.api.CobiGen in project cobigen by devonfw.

the class InputReaderMatcherTest method testBasicElementMatcher_twoComponents.

/**
 * Tests the correct basic retrieval of ComponentDef inputs
 *
 * @throws Exception test fails
 */
@Test
public void testBasicElementMatcher_twoComponents() throws Exception {
    CobiGen cobigen = CobiGenFactory.create(Paths.get(testdataRoot, "templates").toUri());
    Object openApiFile = cobigen.read(Paths.get(testdataRoot, "two-components.yaml"), TestConstants.UTF_8);
    assertThat(openApiFile).isNotNull();
    List<Object> inputObjects = cobigen.resolveContainers(openApiFile);
    assertThat(inputObjects).isNotNull().hasSize(2);
}
Also used : CobiGen(com.devonfw.cobigen.api.CobiGen) Test(org.junit.Test)

Example 33 with CobiGen

use of com.devonfw.cobigen.api.CobiGen in project cobigen by devonfw.

the class InputReaderMatcherTest method testVariableAssignment_noAttributeFound.

/**
 * Tests the case when <b>no</b> ATTRIBUTE was found on the OpenAPI input file for one entity. Therefore an empty
 * string should be assigned.<br>
 * <br>
 * The input test file contains two entities, one has an attribute and the other one does not. We are testing here
 * that the first entity gets his attribute and the second entity gets an empty string
 *
 * @throws Exception test fails
 */
@Test
public void testVariableAssignment_noAttributeFound() throws Exception {
    CobiGen cobigen = CobiGenFactory.create(Paths.get(testdataRoot, "templates").toUri());
    Object openApiFile = cobigen.read(Paths.get(testdataRoot, "two-components-no-attribute.yaml"), TestConstants.UTF_8);
    // Previous version: List<Object> inputObjects = cobigen.getInputObjects(openApiFile,
    // TestConstants.UTF_8);
    List<Object> inputObjects = cobigen.resolveContainers(openApiFile);
    String templateName = "testVariableAssignment_attribute.txt";
    TemplateTo template = findTemplate(cobigen, inputObjects.get(0), templateName);
    File targetFolder = this.tmpFolder.newFolder();
    GenerationReportTo report = cobigen.generate(inputObjects.get(0), template, targetFolder.toPath());
    assertThat(report).isSuccessful();
    assertThat(targetFolder.toPath().resolve("testVariableAssignment_attribute.txt").toFile()).exists().hasContent("testingAttributeTable");
    template = findTemplate(cobigen, inputObjects.get(1), templateName);
    targetFolder = this.tmpFolder.newFolder();
    report = cobigen.generate(inputObjects.get(1), template, targetFolder.toPath());
    assertThat(report.hasWarnings());
    assertThat(report).isSuccessful();
    assertThat(targetFolder.toPath().resolve("testVariableAssignment_attribute.txt").toFile()).exists().hasContent("");
}
Also used : GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGen(com.devonfw.cobigen.api.CobiGen) File(java.io.File) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) Test(org.junit.Test)

Example 34 with CobiGen

use of com.devonfw.cobigen.api.CobiGen 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 35 with CobiGen

use of com.devonfw.cobigen.api.CobiGen in project cobigen by devonfw.

the class GeneratorWrapperFactory method createGenerator.

/**
 * Creates a generator dependent on the input of the selection
 *
 * @param selection current {@link IStructuredSelection} treated as input for generation
 * @param monitor tracking progress
 * @return a specific {@link CobiGenWrapper} instance
 * @throws GeneratorCreationException if any exception occurred during converting the inputs or creating the generator
 * @throws GeneratorProjectNotExistentException if the generator configuration project does not exist
 * @throws InvalidInputException if the selection includes non supported input types or is composed in a non supported
 *         combination of inputs.
 */
public static CobiGenWrapper createGenerator(ISelection selection, IProgressMonitor monitor) throws GeneratorCreationException, GeneratorProjectNotExistentException, InvalidInputException {
    List<Object> extractedInputs = extractValidEclipseInputs(selection);
    if (extractedInputs.size() > 0) {
        monitor.subTask("Initialize CobiGen instance");
        CobiGen cobigen = initializeGenerator();
        monitor.subTask("Reading inputs...");
        monitor.worked(10);
        Object firstElement = extractedInputs.get(0);
        if (firstElement instanceof IJavaElement) {
            LOG.info("Create new CobiGen instance for java inputs...");
            return new JavaInputGeneratorWrapper(cobigen, ((IJavaElement) firstElement).getJavaProject().getProject(), JavaInputConverter.convertInput(extractedInputs, cobigen), monitor);
        } else if (firstElement instanceof IResource) {
            LOG.info("Create new CobiGen instance for file inputs...");
            return new FileInputGeneratorWrapper(cobigen, ((IResource) firstElement).getProject(), FileInputConverter.convertInput(cobigen, extractedInputs), monitor);
        }
    }
    return null;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaInputGeneratorWrapper(com.devonfw.cobigen.eclipse.generator.java.JavaInputGeneratorWrapper) CobiGen(com.devonfw.cobigen.api.CobiGen) FileInputGeneratorWrapper(com.devonfw.cobigen.eclipse.generator.generic.FileInputGeneratorWrapper) IResource(org.eclipse.core.resources.IResource)

Aggregations

CobiGen (com.devonfw.cobigen.api.CobiGen)55 File (java.io.File)45 Test (org.junit.Test)45 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)31 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)28 AbstractApiTest (com.devonfw.cobigen.systemtest.common.AbstractApiTest)26 GeneratorPluginActivator (com.devonfw.cobigen.api.extension.GeneratorPluginActivator)10 InputReader (com.devonfw.cobigen.api.extension.InputReader)10 MatcherInterpreter (com.devonfw.cobigen.api.extension.MatcherInterpreter)10 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)10 MatcherToMatcher (com.devonfw.cobigen.api.matchers.MatcherToMatcher)10 List (java.util.List)10 Path (java.nio.file.Path)9 AssertionFailedError (junit.framework.AssertionFailedError)9 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)7 Paths (java.nio.file.Paths)7 CobiGenFactory (com.devonfw.cobigen.impl.CobiGenFactory)5 AbstractIntegrationTest (com.devonfw.cobigen.javaplugin.integrationtest.common.AbstractIntegrationTest)5 Collectors (java.util.stream.Collectors)5 CobiGenAsserts.assertThat (com.devonfw.cobigen.api.assertj.CobiGenAsserts.assertThat)4