use of com.devonfw.cobigen.api.to.GenerationReportTo in project cobigen by devonfw.
the class XPathGenerationTest method testXpathAccess.
/**
* Testing basic Xpath Access
*
* @throws Exception test fails
*/
@Test
public void testXpathAccess() throws Exception {
Path cobigenConfigFolder = new File("src/test/resources/testdata/integrationtest/uml-basic-test").toPath();
Path input = cobigenConfigFolder.resolve("uml.xml");
CobiGen cobigen = CobiGenFactory.create(cobigenConfigFolder.toUri());
Object compliantInput = cobigen.read(input, Charset.forName("UTF-8"));
List<TemplateTo> matchingTemplates = cobigen.getMatchingTemplates(compliantInput);
assertThat(matchingTemplates).isNotNull().hasSize(1);
File targetFolder = this.tmpFolder.newFolder("testXpathAccess");
GenerationReportTo report = cobigen.generate(compliantInput, matchingTemplates.get(0), targetFolder.toPath());
assertThat(report).isSuccessful();
assertThat(targetFolder.toPath().resolve("DocXPath.txt")).hasContent("Bill");
}
use of com.devonfw.cobigen.api.to.GenerationReportTo in project cobigen by devonfw.
the class CobiGenWrapper method generate.
/**
* Generates the the list of templates based on the given {@link #inputs}.
*
* @param templates to be generated
* @param monitor to track the progress
* @return the {@link GenerationReportTo generation report of CobiGen}
* @throws Exception if anything during generation fails.
*/
public GenerationReportTo generate(List<TemplateTo> templates, IProgressMonitor monitor) throws Exception {
final IProject proj = getGenerationTargetProject();
if (proj != null) {
LOG.debug("Generating files...");
SubMonitor subMonitor = SubMonitor.convert(monitor, 105);
if (monitor.isCanceled()) {
throw new CancellationException("generation got Cancelled by the User");
}
monitor.setTaskName("Load templates...");
SubMonitor loadTemplates = subMonitor.split(2);
// set override flags individually for every template
for (TemplateTo template : templates) {
// wizard and does not declare any merge strategy), the complete file should be overwritten
if (template.getMergeStrategy() == null) {
template.setForceOverride(true);
}
}
loadTemplates.done();
if (monitor.isCanceled()) {
throw new CancellationException("Generation got cancelled by the user");
}
monitor.setTaskName("Determine destination paths...");
SubMonitor generateTargetUri = subMonitor.split(1);
URI generationTargetUri = getGenerationTargetProject().getLocationURI();
if (generationTargetUri == null) {
throw new CobiGenRuntimeException("The location URI of the generation target project " + getGenerationTargetProject().getName() + " could not be resolved. This might be " + "a temporary issue. If this problem persists, please state a bug report.");
}
generateTargetUri.done();
monitor.setTaskName("Generate files...");
GenerationReportTo report;
if (this.singleNonContainerInput) {
// if we only consider one input, we want to allow some customizations of the generation
LOG.debug("Generating with single non container input ...");
report = this.cobiGen.generate(this.inputs.get(0), templates, Paths.get(generationTargetUri), false, (String taskName, Integer progress) -> {
monitor.setTaskName(taskName);
monitor.worked(progress);
});
} else {
report = new GenerationReportTo();
for (Object input : this.inputs) {
report.aggregate(this.cobiGen.generate(input, templates, Paths.get(generationTargetUri), false, (taskname, progress) -> {
monitor.setTaskName(taskname);
monitor.worked(progress);
}));
}
}
monitor.setTaskName("Refresh workspace...");
proj.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
monitor.done();
if (report.isSuccessful()) {
LOG.info("Generation finished successfully.");
}
return report;
} else {
throw new CobiGenRuntimeException("No generation target project configured! This is a Bug!");
}
}
use of com.devonfw.cobigen.api.to.GenerationReportTo in project cobigen by devonfw.
the class GenerationProcessorImpl method generate.
@Override
public GenerationReportTo generate(Object input, List<? extends GenerableArtifact> generableArtifacts, Path targetRootPath, boolean forceOverride, Map<String, Object> rawModel, BiConsumer<String, Integer> progressCallback) {
InputValidator.validateInputsUnequalNull(input, generableArtifacts);
List<Class<?>> logicClasses = null;
// only implicit dependency to javaplugin to lower classloader complexity
ClassLoader inputProjectClassLoader = null;
if (input instanceof Class) {
inputProjectClassLoader = ((Class<?>) input).getClassLoader();
} else if (input instanceof Object[]) {
for (Object obj : (Object[]) input) {
if (obj instanceof Class) {
inputProjectClassLoader = ((Class<?>) obj).getClassLoader();
}
}
}
Path templateConfigPath = Paths.get(this.configurationHolder.getConfigurationLocation());
progressCallback.accept("Prepend Templates Classloader", 10);
inputProjectClassLoader = prependTemplatesClassloader(templateConfigPath, inputProjectClassLoader);
if (inputProjectClassLoader != null) {
try {
logicClasses = ConfigurationClassLoaderUtil.resolveUtilClasses(this.configurationHolder, inputProjectClassLoader);
} catch (IOException e) {
LOG.error("An IOException occured while resolving utility classes!", e);
}
}
// initialize
this.forceOverride = forceOverride;
this.input = input;
if (logicClasses != null) {
progressCallback.accept("Load Template logic classes", 20);
loadLogicClasses(progressCallback, logicClasses);
}
progressCallback.accept("Create Temporary Target Directory", 40);
this.rawModel = rawModel;
try {
this.tmpTargetRootPath = Files.createTempDirectory("cobigen-");
LOG.info("Temporary working directory: {}", this.tmpTargetRootPath);
} catch (IOException e) {
throw new CobiGenRuntimeException("Could not create temporary folder.", e);
}
this.targetRootPath = targetRootPath;
this.generationReport = new GenerationReportTo();
progressCallback.accept("Load templates", 50);
LOG.debug("Collecting templates");
Collection<TemplateTo> templatesToBeGenerated = flatten(generableArtifacts);
// generate
Map<File, File> origToTmpFileTrace = Maps.newHashMap();
try {
LOG.debug("Generating {} templates", templatesToBeGenerated.size());
for (TemplateTo template : templatesToBeGenerated) {
try {
Trigger trigger = this.configurationHolder.readContextConfiguration().getTrigger(template.getTriggerId());
TriggerInterpreter triggerInterpreter = PluginRegistry.getTriggerInterpreter(trigger.getType());
InputValidator.validateTriggerInterpreter(triggerInterpreter, trigger);
progressCallback.accept("Generating " + template.getId(), Math.round(1 / (float) templatesToBeGenerated.size() * 800));
generate(template, triggerInterpreter, origToTmpFileTrace, progressCallback);
} catch (CobiGenCancellationException e) {
throw (e);
} catch (CobiGenRuntimeException e) {
this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
this.generationReport.addError(e);
} catch (Throwable e) {
this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
this.generationReport.addError(new CobiGenRuntimeException("Something unexpected happened" + ((e.getMessage() != null) ? ": " + e.getMessage() : "!"), e));
}
}
} catch (CobiGenCancellationException e) {
LOG.error("the Generation has been Canceled.", e);
this.generationReport.setCancelled(true);
}
if (this.generationReport.isCancelled()) {
this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
this.tmpTargetRootPath.toFile().deleteOnExit();
// do nothing if cancelled
} else if (this.generationReport.isSuccessful()) {
try {
for (Entry<File, File> origToTmpFile : origToTmpFileTrace.entrySet()) {
Files.createDirectories(origToTmpFile.getKey().toPath().getParent());
Files.copy(origToTmpFile.getValue().toPath(), origToTmpFile.getKey().toPath(), StandardCopyOption.REPLACE_EXISTING);
this.generationReport.addGeneratedFile(origToTmpFile.getKey().toPath());
}
this.tmpTargetRootPath.toFile().deleteOnExit();
} catch (IOException e) {
this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
throw new CobiGenRuntimeException("Could not copy generated files to target location!", e);
}
} else {
this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
LOG.warn("Generation finished non-successful. Generated contents can be reviewed in " + this.tmpTargetRootPath.toUri());
}
return this.generationReport;
}
use of com.devonfw.cobigen.api.to.GenerationReportTo in project cobigen by devonfw.
the class GenerationTest method testOverrideMergeStrategy.
/**
* Tests that sources get overwritten if merge strategy override is configured.
*
* @throws Exception test fails.
*/
@Test
public void testOverrideMergeStrategy() throws Exception {
Object input = PluginMockFactory.createSimpleJavaConfigurationMock();
File folder = this.tmpFolder.newFolder("GenerationTest");
File target = new File(folder, "generated.txt");
FileUtils.write(target, "base");
CobiGen cobigen = CobiGenFactory.create(new File(testFileRootPath + "overrideMergeStrategy").toURI());
List<TemplateTo> templates = cobigen.getMatchingTemplates(input);
assertThat(templates).hasSize(1);
GenerationReportTo report = cobigen.generate(input, templates.get(0), Paths.get(folder.toURI()));
assertThat(report).isSuccessful();
assertThat(target).hasContent("overwritten");
}
use of com.devonfw.cobigen.api.to.GenerationReportTo in project cobigen by devonfw.
the class GenerationTest method testCobiGenVariableAvailabilityInTemplates_cobigenPropertiesTargetLocation.
/**
* Tests whether the cobigen properties specified in the target folder are correctly resolved to be served in the
* template in the {@link ModelBuilderImpl#NS_VARIABLES} namespace.
*
* @throws Exception test fails
*/
@Test
public void testCobiGenVariableAvailabilityInTemplates_cobigenPropertiesTargetLocation() throws Exception {
Object input = new Object() {
@Override
public String toString() {
return "input object";
}
};
// Pre-processing: Mocking
GeneratorPluginActivator activator = mock(GeneratorPluginActivator.class);
TriggerInterpreter triggerInterpreter = mock(TriggerInterpreter.class);
MatcherInterpreter matcher = mock(MatcherInterpreter.class);
InputReader inputReader = mock(InputReader.class);
when(triggerInterpreter.getType()).thenReturn("mockplugin");
when(triggerInterpreter.getMatcher()).thenReturn(matcher);
when(triggerInterpreter.getInputReader()).thenReturn(inputReader);
when(inputReader.isValidInput(any())).thenReturn(true);
when(matcher.matches(argThat(new MatcherToMatcher(equalTo("fqn"), ANY, sameInstance(input))))).thenReturn(true);
// Simulate variable resolving of any plug-in
HashMap<String, String> variables = new HashMap<>(1);
variables.put("contextVar", "contextValue");
when(matcher.resolveVariables(any(MatcherTo.class), any(List.class), any())).thenReturn(variables);
PluginRegistry.registerTriggerInterpreter(triggerInterpreter, activator);
// further setup
File folder = this.tmpFolder.newFolder();
Path cobigenPropTarget = folder.toPath().resolve("cobigen.properties");
Files.createFile(cobigenPropTarget);
try (FileWriter writer = new FileWriter(cobigenPropTarget.toFile())) {
IOUtils.write("cobigenPropTarget=extValue", writer);
}
CobiGen cobigen = CobiGenFactory.create(new File(testFileRootPath + "variableAvailability").toURI());
List<TemplateTo> templates = cobigen.getMatchingTemplates(input);
TemplateTo targetTemplate = getTemplate(templates, "t2");
// execute
GenerationReportTo report = cobigen.generate(input, targetTemplate, Paths.get(folder.toURI()));
// assert
assertThat(report).isSuccessful();
File target = new File(folder, "generated2.txt");
assertThat(target).hasContent("contextValue,cobigenPropValue,extValue");
}
Aggregations