Search in sources :

Example 11 with GeneratorPluginActivator

use of com.devonfw.cobigen.api.extension.GeneratorPluginActivator in project cobigen by devonfw.

the class PluginMockFactory method createSimpleJavaConfigurationMock.

/**
 * Creates simple to debug test data, which includes only one object as input. 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 input for generation
 */
@SuppressWarnings("unchecked")
public static Object createSimpleJavaConfigurationMock() {
    // we only need any objects for inputs to have a unique object reference to affect the mocked method
    // calls as intended
    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(false);
    when(matcher.matches(argThat(new MatcherToMatcher(equalTo("package"), ANY, sameInstance(input))))).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<>(3);
    variables.put("rootPackage", "com.devonfw");
    variables.put("component", "comp1");
    variables.put("detail", "");
    when(matcher.resolveVariables(argThat(new MatcherToMatcher(equalTo("fqn"), ANY, sameInstance(input))), argThat(hasItemsInList(// 
    new VariableAssignmentToMatcher(equalTo("regex"), equalTo("rootPackage"), equalTo("1"), equalTo(false)), new VariableAssignmentToMatcher(equalTo("regex"), equalTo("entityName"), equalTo("3"), equalTo(false)))), any())).thenReturn(variables);
    PluginRegistry.registerTriggerInterpreter(triggerInterpreter, activator);
    return input;
}
Also used : TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) MatcherToMatcher(com.devonfw.cobigen.api.matchers.MatcherToMatcher) InputReader(com.devonfw.cobigen.api.extension.InputReader) HashMap(java.util.HashMap) MatcherInterpreter(com.devonfw.cobigen.api.extension.MatcherInterpreter) VariableAssignmentToMatcher(com.devonfw.cobigen.api.matchers.VariableAssignmentToMatcher) GeneratorPluginActivator(com.devonfw.cobigen.api.extension.GeneratorPluginActivator)

Example 12 with GeneratorPluginActivator

use of com.devonfw.cobigen.api.extension.GeneratorPluginActivator in project cobigen by devonfw.

the class ContainerMatcherTest 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}.
 *
 * @param containerChildMatchesTrigger defines whether the child of the container input should match any non-container
 *        matcher
 * @param multipleContainerChildren defines whether the container should contain multiple children
 * @return the container as input for generation interpreter for
 * @author mbrunnli (16.10.2014)
 */
@SuppressWarnings("unchecked")
private Object createTestDataAndConfigureMock(boolean containerChildMatchesTrigger, boolean multipleContainerChildren) {
    // 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
    if (multipleContainerChildren) {
        Object secondChildResource = new Object() {

            @Override
            public String toString() {
                return "child2";
            }
        };
        when(inputReader.getInputObjects(any(), any(Charset.class))).thenReturn(Lists.newArrayList(firstChildResource, secondChildResource));
    } else {
        when(inputReader.getInputObjects(any(), any(Charset.class))).thenReturn(Lists.newArrayList(firstChildResource));
    }
    when(matcher.matches(argThat(new MatcherToMatcher(equalTo("fqn"), ANY, sameInstance(firstChildResource))))).thenReturn(containerChildMatchesTrigger);
    // 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;
}
Also used : TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) MatcherToMatcher(com.devonfw.cobigen.api.matchers.MatcherToMatcher) InputReader(com.devonfw.cobigen.api.extension.InputReader) MatcherInterpreter(com.devonfw.cobigen.api.extension.MatcherInterpreter) Charset(java.nio.charset.Charset) VariableAssignmentToMatcher(com.devonfw.cobigen.api.matchers.VariableAssignmentToMatcher) GeneratorPluginActivator(com.devonfw.cobigen.api.extension.GeneratorPluginActivator)

Example 13 with GeneratorPluginActivator

use of com.devonfw.cobigen.api.extension.GeneratorPluginActivator in project cobigen by devonfw.

the class GenerationTest method testCobiGenVariableAvailabilityInTemplates.

/**
 * Tests whether context properties as well as cobigen properties are correctly resolved to be served in the template
 * in the {@link ModelBuilderImpl#NS_VARIABLES} namespace.
 *
 * @throws Exception test fails
 */
@Test
public void testCobiGenVariableAvailabilityInTemplates() 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();
    CobiGen cobigen = CobiGenFactory.create(new File(testFileRootPath + "variableAvailability").toURI());
    List<TemplateTo> templates = cobigen.getMatchingTemplates(input);
    TemplateTo targetTemplate = getTemplate(templates, "t1");
    // execute
    GenerationReportTo report = cobigen.generate(input, targetTemplate, Paths.get(folder.toURI()));
    // assert
    assertThat(report).isSuccessful();
    File target = new File(folder, "generated.txt");
    assertThat(target).hasContent("contextValue,cobigenPropValue");
}
Also used : TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) HashMap(java.util.HashMap) GeneratorPluginActivator(com.devonfw.cobigen.api.extension.GeneratorPluginActivator) MatcherToMatcher(com.devonfw.cobigen.api.matchers.MatcherToMatcher) InputReader(com.devonfw.cobigen.api.extension.InputReader) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) MatcherInterpreter(com.devonfw.cobigen.api.extension.MatcherInterpreter) List(java.util.List) CobiGen(com.devonfw.cobigen.api.CobiGen) File(java.io.File) MatcherTo(com.devonfw.cobigen.api.to.MatcherTo) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) AbstractApiTest(com.devonfw.cobigen.systemtest.common.AbstractApiTest) Test(org.junit.Test)

Example 14 with GeneratorPluginActivator

use of com.devonfw.cobigen.api.extension.GeneratorPluginActivator in project cobigen by devonfw.

the class PluginRegistry method getTriggerInterpreters.

/**
 * Returns a {@link Map} of all {@link TriggerInterpreter} keys.
 *
 * @param inputPath the path of the input to be read to just return the valid {@link TriggerInterpreter}s in order
 *        sorted by {@link Priority}
 *
 * @return all {@link TriggerInterpreter} keys as a set of strings.
 */
public static List<TriggerInterpreter> getTriggerInterpreters(Path inputPath) {
    String extension;
    if (inputPath.toFile().isFile()) {
        extension = FilenameUtils.getExtension(inputPath.getFileName().toString());
        LOG.debug("Trying to find trigger interpreter by file extension '{}'", extension);
        for (Class<? extends GeneratorPluginActivator> activatorClass : ClassServiceLoader.getGeneratorPluginActivatorClasses()) {
            LOG.debug("Checking found plug-in activator '{}'", activatorClass);
            if (activatorClass.isAnnotationPresent(Activation.class)) {
                Activation activation = activatorClass.getAnnotation(Activation.class);
                String[] byFileExtension = activation.byFileExtension();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Plug-in will be activated by file extensions '{}'.", Arrays.stream(byFileExtension).collect(Collectors.joining(",")));
                }
                Arrays.sort(byFileExtension);
                if (Arrays.binarySearch(byFileExtension, extension) >= 0 && !loadedPlugins.containsKey(activatorClass)) {
                    loadPlugin(activatorClass);
                } else {
                    LOG.debug("File extension not found. Skipping.");
                }
            } else {
                LOG.debug("Activator annotation not present. Skipping.");
            }
        }
    } else {
        // directory
        extension = FOLDER;
        LOG.debug("Trying to find trigger interpreter by for folder inputs");
        for (Class<? extends GeneratorPluginActivator> activatorClass : ClassServiceLoader.getGeneratorPluginActivatorClasses()) {
            LOG.debug("Checking found plug-in activator '{}'", activatorClass);
            if (activatorClass.isAnnotationPresent(Activation.class)) {
                Activation activation = activatorClass.getAnnotation(Activation.class);
                if (activation.byFolder() && !loadedPlugins.containsKey(activatorClass)) {
                    loadPlugin(activatorClass);
                }
            } else {
                LOG.debug("Activator annotation not present. Skipping.");
            }
        }
    }
    List<TriggerInterpreter> sortedPlugins = registeredTriggerInterpreterByFileExtension.get(extension).stream().sorted((a, b) -> {
        Priority priorityA = getPriority(a.getClass());
        Priority priorityB = getPriority(b.getClass());
        return SignedBytes.compare(priorityA.getRank(), priorityB.getRank());
    }).collect(Collectors.toList());
    return sortedPlugins;
}
Also used : TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) LoggerFactory(org.slf4j.LoggerFactory) SignedBytes(com.google.common.primitives.SignedBytes) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) Maps(com.google.common.collect.Maps) Activation(com.devonfw.cobigen.api.annotation.Activation) Merger(com.devonfw.cobigen.api.extension.Merger) ReaderPriority(com.devonfw.cobigen.api.annotation.ReaderPriority) List(java.util.List) HashMultimap(com.google.common.collect.HashMultimap) GeneratorPluginActivator(com.devonfw.cobigen.api.extension.GeneratorPluginActivator) Map(java.util.Map) Priority(com.devonfw.cobigen.api.extension.Priority) TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) Path(java.nio.file.Path) FilenameUtils(org.apache.commons.io.FilenameUtils) ProxyFactory(com.devonfw.cobigen.impl.aop.ProxyFactory) ReaderPriority(com.devonfw.cobigen.api.annotation.ReaderPriority) Priority(com.devonfw.cobigen.api.extension.Priority) Activation(com.devonfw.cobigen.api.annotation.Activation)

Example 15 with GeneratorPluginActivator

use of com.devonfw.cobigen.api.extension.GeneratorPluginActivator in project cobigen by devonfw.

the class PluginRegistry method loadPlugin.

/**
 * Loads the given plug-in and registers all {@link Merger}s and {@link TriggerInterpreter}s bound by the given
 * plug-in
 *
 * @param generatorPlugin plug-in to be loaded
 * @param <T> Type of the plug-in interface
 * @return the instantiated {@link GeneratorPluginActivator}
 */
private static <T extends GeneratorPluginActivator> GeneratorPluginActivator loadPlugin(Class<T> generatorPlugin) {
    try {
        Object plugin = generatorPlugin.newInstance();
        LOG.info("Register CobiGen Plug-in '{}'.", generatorPlugin.getCanonicalName());
        if (plugin instanceof GeneratorPluginActivator) {
            // Collect Mergers
            GeneratorPluginActivator activator = (GeneratorPluginActivator) plugin;
            if (activator.bindMerger() != null) {
                for (Merger merger : activator.bindMerger()) {
                    registerMerger(merger);
                }
            // adds merger plugins to notifyable list
            }
            // Collect TriggerInterpreters
            if (activator.bindTriggerInterpreter() != null) {
                for (TriggerInterpreter triggerInterpreter : activator.bindTriggerInterpreter()) {
                    registerTriggerInterpreter(triggerInterpreter, activator);
                }
            }
            loadedPlugins.put(activator.getClass(), activator);
            return activator;
        } else {
            LOG.warn("Instantiated plugin of class {}, which is not subclass of {}", plugin.getClass().getCanonicalName(), GeneratorPluginActivator.class.getCanonicalName());
            return null;
        }
    } catch (InstantiationException | IllegalAccessException e) {
        throw new CobiGenRuntimeException("Could not intantiate CobiGen Plug-in '" + generatorPlugin.getCanonicalName() + "'.", e);
    }
}
Also used : TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) Merger(com.devonfw.cobigen.api.extension.Merger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) GeneratorPluginActivator(com.devonfw.cobigen.api.extension.GeneratorPluginActivator)

Aggregations

GeneratorPluginActivator (com.devonfw.cobigen.api.extension.GeneratorPluginActivator)15 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)15 InputReader (com.devonfw.cobigen.api.extension.InputReader)13 MatcherInterpreter (com.devonfw.cobigen.api.extension.MatcherInterpreter)13 MatcherToMatcher (com.devonfw.cobigen.api.matchers.MatcherToMatcher)13 CobiGen (com.devonfw.cobigen.api.CobiGen)10 AbstractApiTest (com.devonfw.cobigen.systemtest.common.AbstractApiTest)10 File (java.io.File)10 Test (org.junit.Test)10 HashMap (java.util.HashMap)4 VariableAssignmentToMatcher (com.devonfw.cobigen.api.matchers.VariableAssignmentToMatcher)3 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)3 Charset (java.nio.charset.Charset)3 List (java.util.List)3 CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)2 Merger (com.devonfw.cobigen.api.extension.Merger)2 MatcherTo (com.devonfw.cobigen.api.to.MatcherTo)2 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)2 Path (java.nio.file.Path)2 Activation (com.devonfw.cobigen.api.annotation.Activation)1