Search in sources :

Example 6 with CobiGen

use of com.devonfw.cobigen.api.CobiGen 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)

Example 7 with CobiGen

use of com.devonfw.cobigen.api.CobiGen 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");
}
Also used : Path(java.nio.file.Path) 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)

Example 8 with CobiGen

use of com.devonfw.cobigen.api.CobiGen 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!");
    }
}
Also used : ConfigurationConstants(com.devonfw.cobigen.api.constants.ConfigurationConstants) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) Arrays(java.util.Arrays) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) SubMonitor(org.eclipse.core.runtime.SubMonitor) LoggerFactory(org.slf4j.LoggerFactory) CobiGen(com.devonfw.cobigen.api.CobiGen) Function(java.util.function.Function) PlatformUIUtil(com.devonfw.cobigen.eclipse.common.tools.PlatformUIUtil) InvalidInputException(com.devonfw.cobigen.eclipse.common.exceptions.InvalidInputException) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) IProject(org.eclipse.core.resources.IProject) ComparableIncrement(com.devonfw.cobigen.eclipse.generator.entity.ComparableIncrement) Map(java.util.Map) URI(java.net.URI) Path(java.nio.file.Path) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) MapUtils(com.devonfw.cobigen.eclipse.common.tools.MapUtils) Trigger(org.eclipse.jface.bindings.Trigger) Logger(org.slf4j.Logger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Iterator(java.util.Iterator) CancellationException(java.util.concurrent.CancellationException) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) IOException(java.io.IOException) CobiGenEclipseRuntimeException(com.devonfw.cobigen.eclipse.common.exceptions.CobiGenEclipseRuntimeException) Display(org.eclipse.swt.widgets.Display) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) List(java.util.List) Paths(java.nio.file.Paths) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) GeneratorProjectNotExistentException(com.devonfw.cobigen.eclipse.common.exceptions.GeneratorProjectNotExistentException) IResource(org.eclipse.core.resources.IResource) Entry(java.util.Map.Entry) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CancellationException(java.util.concurrent.CancellationException) SubMonitor(org.eclipse.core.runtime.SubMonitor) URI(java.net.URI) IProject(org.eclipse.core.resources.IProject) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 9 with CobiGen

use of com.devonfw.cobigen.api.CobiGen in project cobigen by devonfw.

the class CobiGenUtils method extractArtificialPom.

/**
 * Extracts an artificial POM which defines all the CobiGen plug-ins that are needed
 *
 * @return the extracted POM file
 */
public static File extractArtificialPom() {
    Path cliHome = getCliHomePath();
    File pomFile = cliHome.resolve(MavenConstants.POM).toFile();
    if (!pomFile.exists()) {
        try (InputStream resourcesIs1 = CobiGenUtils.class.getResourceAsStream("/" + MavenConstants.POM);
            InputStream resourcesIs2 = CobiGenUtils.class.getClass().getResourceAsStream("/" + MavenConstants.POM)) {
            if (resourcesIs1 != null) {
                LOG.debug("Taking pom.xml from classpath");
                Files.createDirectories(pomFile.toPath().getParent());
                Files.copy(resourcesIs1, pomFile.getAbsoluteFile().toPath());
            } else if (resourcesIs2 != null) {
                LOG.debug("Taking pom.xml from system classpath");
                Files.createDirectories(pomFile.toPath().getParent());
                Files.copy(resourcesIs1, pomFile.getAbsoluteFile().toPath());
            } else {
                if (CobiGenUtils.class.getClassLoader() instanceof URLClassLoader) {
                    LOG.debug("Classloader URLs:");
                    Arrays.stream(((URLClassLoader) CobiGenUtils.class.getClassLoader()).getURLs()).forEach(url -> LOG.debug("  - {}", url));
                }
                if (CobiGenUtils.class.getClass().getClassLoader() instanceof URLClassLoader) {
                    LOG.debug("System Classloader URLs:");
                    Arrays.stream(((URLClassLoader) CobiGenUtils.class.getClassLoader()).getURLs()).forEach(url -> LOG.debug("  - {}", url));
                }
                throw new CobiGenRuntimeException("Unable to locate pom.xml on classpath");
            }
        } catch (IOException e1) {
            throw new CobiGenRuntimeException("Failed to extract CobiGen plugins pom.", e1);
        }
    }
    return pomFile;
}
Also used : Path(java.nio.file.Path) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) Arrays(java.util.Arrays) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException) LoggerFactory(org.slf4j.LoggerFactory) CobiGen(com.devonfw.cobigen.api.CobiGen) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) CobiGenFactory(com.devonfw.cobigen.impl.CobiGenFactory) CobiGenCLI(com.devonfw.cobigen.cli.CobiGenCLI) InputInterpreter(com.devonfw.cobigen.api.InputInterpreter) Path(java.nio.file.Path) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) ClassServiceLoader(com.devonfw.cobigen.impl.extension.ClassServiceLoader) Charsets(com.google.common.base.Charsets) Logger(org.slf4j.Logger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Files(java.nio.file.Files) MavenUtil(com.devonfw.cobigen.api.util.MavenUtil) IOException(java.io.IOException) File(java.io.File) List(java.util.List) Paths(java.nio.file.Paths) CobiGenPaths(com.devonfw.cobigen.api.util.CobiGenPaths) MavenConstants(com.devonfw.cobigen.api.constants.MavenConstants) InputStream(java.io.InputStream) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) InputStream(java.io.InputStream) URLClassLoader(java.net.URLClassLoader) IOException(java.io.IOException) File(java.io.File)

Example 10 with CobiGen

use of com.devonfw.cobigen.api.CobiGen in project cobigen by devonfw.

the class GenerateCommand method doAction.

@Override
public Integer doAction() throws Exception {
    if (!areArgumentsValid()) {
        return 1;
    }
    LOG.debug("Input files and output root path confirmed to be valid.");
    CobiGen cg = CobiGenUtils.initializeCobiGen(this.templatesProject);
    resolveTemplateDependencies();
    if (this.increments == null && this.templates != null) {
        Tuple<List<Object>, List<TemplateTo>> inputsAndArtifacts = preprocess(cg, TemplateTo.class);
        for (int i = 0; i < inputsAndArtifacts.getA().size(); i++) {
            generate(this.inputFiles.get(i), inputsAndArtifacts.getA().get(i), MavenUtil.getProjectRoot(this.inputFiles.get(i), false), inputsAndArtifacts.getB(), cg, TemplateTo.class);
        }
    } else {
        Tuple<List<Object>, List<IncrementTo>> inputsAndArtifacts = preprocess(cg, IncrementTo.class);
        for (int i = 0; i < inputsAndArtifacts.getA().size(); i++) {
            generate(this.inputFiles.get(i), inputsAndArtifacts.getA().get(i), MavenUtil.getProjectRoot(this.inputFiles.get(i), false), inputsAndArtifacts.getB(), cg, IncrementTo.class);
        }
    }
    return 0;
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) CobiGen(com.devonfw.cobigen.api.CobiGen)

Aggregations

CobiGen (com.devonfw.cobigen.api.CobiGen)55 File (java.io.File)45 Test (org.junit.Test)45 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)31 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)28 AbstractApiTest (com.devonfw.cobigen.systemtest.common.AbstractApiTest)26 GeneratorPluginActivator (com.devonfw.cobigen.api.extension.GeneratorPluginActivator)10 InputReader (com.devonfw.cobigen.api.extension.InputReader)10 MatcherInterpreter (com.devonfw.cobigen.api.extension.MatcherInterpreter)10 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)10 MatcherToMatcher (com.devonfw.cobigen.api.matchers.MatcherToMatcher)10 List (java.util.List)10 Path (java.nio.file.Path)9 AssertionFailedError (junit.framework.AssertionFailedError)9 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)7 Paths (java.nio.file.Paths)7 CobiGenFactory (com.devonfw.cobigen.impl.CobiGenFactory)5 AbstractIntegrationTest (com.devonfw.cobigen.javaplugin.integrationtest.common.AbstractIntegrationTest)5 Collectors (java.util.stream.Collectors)5 CobiGenAsserts.assertThat (com.devonfw.cobigen.api.assertj.CobiGenAsserts.assertThat)4