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");
}
}
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");
}
}
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);
}
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);
}
}
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");
}
Aggregations