Search in sources :

Example 1 with GenerationReportTo

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

the class AnnotationQueryingTest method testAnnotationWithObjectArraysAsValues.

/**
 * Tests whether annotations with object array values are correctly accessible within the templates
 *
 * @throws Exception test fails
 */
@Test
public void testAnnotationWithObjectArraysAsValues() throws Exception {
    CobiGen cobiGen = CobiGenFactory.create(this.cobigenConfigFolder.toURI());
    File tmpFolderCobiGen = this.tmpFolder.newFolder("cobigen_output");
    Object input = cobiGen.read(new File("src/test/resources/testdata/unittest/inputreader/TestClassWithAnnotationsContainingObjectArrays.java").toPath(), Charset.forName("UTF-8"), getClass().getClassLoader());
    List<TemplateTo> templates = cobiGen.getMatchingTemplates(input);
    boolean methodTemplateFound = false;
    for (TemplateTo template : templates) {
        if (template.getId().equals("annotationQuerying.txt")) {
            GenerationReportTo report = cobiGen.generate(input, template, Paths.get(tmpFolderCobiGen.getAbsolutePath()), false);
            File expectedFile = new File(tmpFolderCobiGen.getAbsoluteFile() + SystemUtils.FILE_SEPARATOR + "annotationQuerying.txt");
            assertThat(report).isSuccessful();
            assertThat(expectedFile).exists();
            assertThat(expectedFile).hasContent("TestClassWithAnnotationsContainingObjectArrays.class,TestClassWithAnnotations.class,");
            methodTemplateFound = true;
            break;
        }
    }
    if (!methodTemplateFound) {
        throw new AssertionFailedError("Test template not found");
    }
}
Also used : GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGen(com.devonfw.cobigen.api.CobiGen) AssertionFailedError(junit.framework.AssertionFailedError) File(java.io.File) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) Test(org.junit.Test) AbstractIntegrationTest(com.devonfw.cobigen.javaplugin.integrationtest.common.AbstractIntegrationTest)

Example 2 with GenerationReportTo

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

the class VariablesResolutionTest method testSuccessfulPathResolution_variableEqNull.

/**
 * Tests that the path resolution is performed successfully in case of including path variables derived from variable
 * assignments retrieved by regex groups, which have been resolved to null. This bug has been introduced by changing
 * the model building from DOM to Bean model. The latter required to explicitly not to set <code>null</code> as a
 * value for variable resolution. Basically, this is odd, but we have to comply with backward compatibility and the
 * issue that we cannot encode unary-operators like ?? in a file path sufficiently.
 *
 * @throws Exception test fails
 */
@Test
public void testSuccessfulPathResolution_variableEqNull() throws Exception {
    CobiGen cobiGen = CobiGenFactory.create(this.cobigenConfigFolder.toURI());
    File tmpFolderCobiGen = this.tmpFolder.newFolder("cobigen_output");
    Object input = cobiGen.read(new File("src/test/resources/testdata/integrationtest/javaSources/SampleEntity.java").toPath(), Charset.forName("UTF-8"));
    List<TemplateTo> templates = cobiGen.getMatchingTemplates(input);
    boolean methodTemplateFound = false;
    for (TemplateTo template : templates) {
        if (template.getId().equals("${variables.entityName}.java")) {
            GenerationReportTo report = cobiGen.generate(input, template, Paths.get(tmpFolderCobiGen.getAbsolutePath()), false);
            assertThat(report).isSuccessful();
            methodTemplateFound = true;
            break;
        }
    }
    if (!methodTemplateFound) {
        throw new AssertionFailedError("Test template not found");
    }
}
Also used : GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGen(com.devonfw.cobigen.api.CobiGen) AssertionFailedError(junit.framework.AssertionFailedError) File(java.io.File) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) AbstractIntegrationTest(com.devonfw.cobigen.javaplugin.integrationtest.common.AbstractIntegrationTest) Test(org.junit.Test)

Example 3 with GenerationReportTo

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

the class GenerateSelectionJob method run.

@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    MDC.put(InfrastructureConstants.CORRELATION_ID, UUID.randomUUID().toString());
    this.LOG.info("Start generation process...");
    if (this.templatesToBeGenerated.size() == 0) {
        this.LOG.warn("No templates determined to be generated... This might be a bug.");
        return;
    }
    try {
        final GenerationReportTo generationReport = performGeneration(monitor);
        if (generationReport.isSuccessful()) {
            Set<String> generatedFiles = this.cobigenWrapper.getWorkspaceDependentTemplateDestinationPath(generationReport.getGeneratedFiles());
            Set<IProject> projects = Sets.newHashSet();
            for (String filePath : generatedFiles) {
                IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(PathUtil.getProject(filePath));
                project = PathUtil.getRelativeProjectIfNeeded(filePath, project);
                if (project.exists()) {
                    projects.add(project);
                }
            }
            for (IProject proj : projects) {
                proj.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
            }
            final ICompilationUnit[] cus = getGeneratedCompilationUnits(generatedFiles);
            monitor.setTaskName("Organize Imports...");
            organizeImports(cus);
            monitor.setTaskName("Format Source Code...");
            formatSourceCode(cus);
            if (generationReport.hasWarnings()) {
                PlatformUIUtil.getWorkbench().getDisplay().syncExec(new Runnable() {

                    @Override
                    public void run() {
                        StringBuilder strBuilder = new StringBuilder();
                        int counter = 0;
                        for (String warning : generationReport.getWarnings()) {
                            strBuilder.append(++counter);
                            strBuilder.append(". ");
                            strBuilder.append(warning);
                            strBuilder.append("\n");
                        }
                        MessageDialog.openWarning(PlatformUIUtil.getWorkbench().getDisplay().getActiveShell(), CobiGenDialogConstants.DIALOG_TITLE_GEN_SUCCEEDED_W_WARNINGS, "Contents from " + GenerateSelectionJob.this.templatesToBeGenerated.size() + " templates have been generated.\n\nWarnings:\n" + strBuilder.toString());
                    }
                });
            } else {
                String reportMessage = generationReport.isCancelled() ? "generation got Cancelled" : "Contents from " + this.templatesToBeGenerated.size() + " templates have been generated.";
                PlatformUIUtil.getWorkbench().getDisplay().syncExec(new Runnable() {

                    @Override
                    public void run() {
                        MessageDialog.openInformation(PlatformUIUtil.getWorkbench().getDisplay().getActiveShell(), CobiGenDialogConstants.DIALOG_TITLE_GEN_SUCCEEDED, reportMessage);
                    }
                });
            }
        } else {
            PlatformUIUtil.getWorkbench().getDisplay().syncExec(new Runnable() {

                @Override
                public void run() {
                    Throwable firstError = generationReport.getErrors().get(0);
                    String tempGenMessage = "The merge of generated contents to the " + "target code base has been aborted. Please find the errorneous generation " + "results in the following temporary folder for further investigation: " + generationReport.getTemporaryWorkingDirectory();
                    PlatformUIUtil.openErrorDialog(generationReport.getErrors().size() > 1 ? "Multiple errors occurred during generation. There are " + generationReport.getErrors().size() + " errors in total. See the stack trace only of the first error below." + " Please investigate the Log file to view all errors if needed. " + tempGenMessage : "An error occurred during generation. " + tempGenMessage, firstError);
                }
            });
            for (Throwable e : generationReport.getErrors()) {
                this.LOG.error("An error occurred during generation:", e);
            }
        }
    } catch (Throwable e) {
        ExceptionHandler.handle(e, null);
    } finally {
        this.LOG.info("Finished processing generation.");
        monitor.done();
    }
    MDC.remove(InfrastructureConstants.CORRELATION_ID);
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) IProject(org.eclipse.core.resources.IProject)

Example 4 with GenerationReportTo

use of com.devonfw.cobigen.api.to.GenerationReportTo 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 5 with GenerationReportTo

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

the class XmlPluginIntegrationTest method testSimpleUmlEntityExtraction.

/**
 * Tests simple extraction of entities out of XMI UML.
 *
 * @throws Exception test fails
 */
@Test
public void testSimpleUmlEntityExtraction() throws Exception {
    // arrange
    Path configFolder = new File(testFileRootPath + "uml-classdiag").toPath();
    File xmlFile = configFolder.resolve("completeUmlXmi.xml").toFile();
    CobiGen cobigen = CobiGenFactory.create(configFolder.toUri());
    Object doc = cobigen.read(xmlFile.toPath(), UTF_8);
    File targetFolder = this.tmpFolder.newFolder("testSimpleUmlEntityExtraction");
    // act
    List<TemplateTo> matchingTemplates = cobigen.getMatchingTemplates(doc);
    List<TemplateTo> templateOfInterest = matchingTemplates.stream().filter(e -> e.getId().equals("${className}.txt")).collect(Collectors.toList());
    assertThat(templateOfInterest).hasSize(1);
    GenerationReportTo generate = cobigen.generate(doc, templateOfInterest, targetFolder.toPath());
    // assert
    assertThat(generate).isSuccessful();
    File[] files = targetFolder.listFiles();
    assertThat(files).extracting(e -> e.getName()).containsExactlyInAnyOrder("Student.txt", "User.txt", "Marks.txt", "Teacher.txt");
    assertThat(targetFolder.toPath().resolve("Student.txt")).hasContent("public Student EAID_4509184A_D724_495f_AAEB_1ACE1AD90879");
    assertThat(targetFolder.toPath().resolve("User.txt")).hasContent("public User EAID_C2E366C0_510F_4145_B650_110537B98360");
    assertThat(targetFolder.toPath().resolve("Marks.txt")).hasContent("public Marks EAID_1D7DCE81_651D_40f2_A6E5_A522CF6E0C64");
    assertThat(targetFolder.toPath().resolve("Teacher.txt")).hasContent("public Teacher EAID_6EA6FC61_FB9B_4e8e_98A1_30BD386AEA9A");
}
Also used : Path(java.nio.file.Path) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) FileUtils(org.apache.commons.io.FileUtils) Test(org.junit.Test) AssertionFailedError(junit.framework.AssertionFailedError) CobiGen(com.devonfw.cobigen.api.CobiGen) Collectors(java.util.stream.Collectors) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) List(java.util.List) PluginNotAvailableException(com.devonfw.cobigen.api.exception.PluginNotAvailableException) CobiGenFactory(com.devonfw.cobigen.impl.CobiGenFactory) CobiGenAsserts.assertThat(com.devonfw.cobigen.api.assertj.CobiGenAsserts.assertThat) Rule(org.junit.Rule) Charset(java.nio.charset.Charset) Paths(java.nio.file.Paths) Assert(org.junit.Assert) GenerationReportToAssert(com.devonfw.cobigen.api.assertj.GenerationReportToAssert) Path(java.nio.file.Path) TemporaryFolder(org.junit.rules.TemporaryFolder) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) 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)

Aggregations

GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)33 CobiGen (com.devonfw.cobigen.api.CobiGen)27 Test (org.junit.Test)26 File (java.io.File)25 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)24 AbstractApiTest (com.devonfw.cobigen.systemtest.common.AbstractApiTest)9 Path (java.nio.file.Path)9 AssertionFailedError (junit.framework.AssertionFailedError)8 List (java.util.List)7 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)5 MatcherTo (com.devonfw.cobigen.api.to.MatcherTo)5 Paths (java.nio.file.Paths)5 GenerationReportToAssert (com.devonfw.cobigen.api.assertj.GenerationReportToAssert)4 CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)4 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)4 AbstractIntegrationTest (com.devonfw.cobigen.javaplugin.integrationtest.common.AbstractIntegrationTest)4 Charset (java.nio.charset.Charset)4 CobiGenAsserts.assertThat (com.devonfw.cobigen.api.assertj.CobiGenAsserts.assertThat)3 PluginNotAvailableException (com.devonfw.cobigen.api.exception.PluginNotAvailableException)3 GeneratorPluginActivator (com.devonfw.cobigen.api.extension.GeneratorPluginActivator)3