use of com.devonfw.cobigen.api.extension.TriggerInterpreter 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.extension.TriggerInterpreter in project cobigen by devonfw.
the class InputResolverImpl method resolveContainerElements.
@Cached
@Override
public List<Object> resolveContainerElements(Object input, Trigger trigger) {
List<Object> inputObjects = new ArrayList<>();
if (this.inputInterpreter.combinesMultipleInputs(input)) {
TriggerInterpreter triggerInterpreter = PluginRegistry.getTriggerInterpreter(trigger.getType());
InputReader inputReader = triggerInterpreter.getInputReader();
// check whether the inputs should be retrieved recursively
boolean retrieveInputsRecursively = false;
for (ContainerMatcher containerMatcher : trigger.getContainerMatchers()) {
MatcherTo matcherTo = new MatcherTo(containerMatcher.getType(), containerMatcher.getValue(), input);
if (triggerInterpreter.getMatcher().matches(matcherTo)) {
if (!retrieveInputsRecursively) {
retrieveInputsRecursively = containerMatcher.isRetrieveObjectsRecursively();
} else {
break;
}
}
}
if (retrieveInputsRecursively) {
inputObjects = inputReader.getInputObjectsRecursively(input, trigger.getInputCharset());
} else {
inputObjects = inputReader.getInputObjects(input, trigger.getInputCharset());
}
// Remove non matching inputs
Iterator<Object> it = inputObjects.iterator();
while (it.hasNext()) {
Object next = it.next();
if (!this.matcherEvaluator.matches(next, trigger.getMatcher(), triggerInterpreter)) {
it.remove();
}
}
} else {
inputObjects.add(input);
}
return inputObjects;
}
use of com.devonfw.cobigen.api.extension.TriggerInterpreter in project cobigen by devonfw.
the class ModelBuilderImpl method createModel.
/**
* Creates a new model by trying to retrieve the corresponding {@link TriggerInterpreter} from the plug-in registry
*
* @return the created model
* @throws InvalidConfigurationException if there are {@link VariableAssignment}s, which could not be resolved
*/
@Override
public Map<String, Object> createModel() throws InvalidConfigurationException {
TriggerInterpreter triggerInterpreter = PluginRegistry.getTriggerInterpreter(this.trigger.getType());
InputValidator.validateTriggerInterpreter(triggerInterpreter, this.trigger);
return createModel(triggerInterpreter);
}
use of com.devonfw.cobigen.api.extension.TriggerInterpreter in project cobigen by devonfw.
the class InputValidator method validateTrigger.
/**
* Validates the trigger to be not null as well as to be connected to any trigger interpreter.
*
* @param trigger {@link Trigger} to be validated
*/
public static void validateTrigger(Trigger trigger) {
if (trigger == null) {
throw new IllegalArgumentException("Invalid trigger == null");
}
TriggerInterpreter interpreter = PluginRegistry.getTriggerInterpreter(trigger.getType());
validateTriggerInterpreter(interpreter, trigger.getType());
}
use of com.devonfw.cobigen.api.extension.TriggerInterpreter in project cobigen by devonfw.
the class ClassLoadingTest method createTestDataAndConfigureMock.
/**
* Creates simple to debug test data, which includes on container object and one child of the container object. A
* {@link TriggerInterpreter TriggerInterpreter} will be mocked with all necessary supplier classes to mock a simple
* java trigger interpreter. Furthermore, the mocked trigger interpreter will be directly registered in the
* {@link PluginRegistry}.
*
* @return the container as input for generation interpreter for
*/
@SuppressWarnings("unchecked")
private Object createTestDataAndConfigureMock() {
// we only need any objects for inputs to have a unique object reference to affect the mocked method
// calls as intended
Object container = new Object() {
@Override
public String toString() {
return "container";
}
};
Object firstChildResource = new Object() {
@Override
public String toString() {
return "child";
}
};
// 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(container))))).thenReturn(false);
when(matcher.matches(argThat(new MatcherToMatcher(equalTo("package"), ANY, sameInstance(container))))).thenReturn(true);
// Simulate container children resolution of any plug-in
when(inputReader.getInputObjects(any(), any(Charset.class))).thenReturn(Lists.newArrayList(firstChildResource));
when(matcher.matches(argThat(new MatcherToMatcher(equalTo("fqn"), ANY, sameInstance(firstChildResource))))).thenReturn(true);
// Simulate variable resolving of any plug-in
when(matcher.resolveVariables(argThat(new MatcherToMatcher(equalTo("fqn"), ANY, sameInstance(firstChildResource))), argThat(hasItemsInList(//
new VariableAssignmentToMatcher(equalTo("regex"), equalTo("rootPackage"), equalTo("1"), equalTo(false)), new VariableAssignmentToMatcher(equalTo("regex"), equalTo("entityName"), equalTo("3"), equalTo(false)))), any())).thenReturn(ImmutableMap.<String, String>builder().put("rootPackage", "com.devonfw").put("entityName", "Test").build());
PluginRegistry.registerTriggerInterpreter(triggerInterpreter, activator);
return container;
}
Aggregations