Search in sources :

Example 1 with CobiGenRuntimeException

use of com.devonfw.cobigen.api.exception.CobiGenRuntimeException 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);
    }
}
Also used : GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) MojoFailureException(org.apache.maven.plugin.MojoFailureException) CobiGen(com.devonfw.cobigen.api.CobiGen)

Example 2 with CobiGenRuntimeException

use of com.devonfw.cobigen.api.exception.CobiGenRuntimeException in project cobigen by devonfw.

the class UpdateTemplatesDialog method createButtonsForButtonBar.

@Override
protected void createButtonsForButtonBar(Composite parent) {
    Button button = createButton(parent, IDialogConstants.OK_ID, "Download", false);
    button.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                ResourcesPluginUtil.setUserWantsToDownloadTemplates(true);
                ResourcesPluginUtil.downloadJar(false);
                ResourcesPluginUtil.downloadJar(true);
                MessageDialog dialog = new MessageDialog(Display.getDefault().getActiveShell(), "Information", null, "Downloaded succesfully!", MessageDialog.INFORMATION, new String[] { "Ok" }, 1);
                dialog.setBlockOnOpen(true);
                dialog.open();
            } catch (MalformedURLException malformedURLException) {
                PlatformUIUtil.openErrorDialog("Templates were not downloaded because the maven central repo url or path doesn't exist. \n " + "Please create a new issue on GitHub https://github.com/devonfw/cobigen/issues", malformedURLException);
                throw new CobiGenRuntimeException("Invalid maven central repo url or path doesn't exist " + malformedURLException);
            } catch (IOException exceptionIO) {
                PlatformUIUtil.openErrorDialog("Templates were not downloaded because there is no connection." + " Are you connected to the Internet? ", exceptionIO);
                throw new CobiGenRuntimeException("Failed while reading or writing Jar at .metadata folder" + exceptionIO);
            }
        }
    });
    createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, true);
}
Also used : MalformedURLException(java.net.MalformedURLException) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Button(org.eclipse.swt.widgets.Button) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) SelectionEvent(org.eclipse.swt.events.SelectionEvent) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) IOException(java.io.IOException)

Example 3 with CobiGenRuntimeException

use of com.devonfw.cobigen.api.exception.CobiGenRuntimeException in project cobigen by devonfw.

the class JavaParserUtil method getJavaContext.

/**
 * Tries to get the Java context by creating a new class loader of the input project that is able to load the input
 * file. We need this in order to perform reflection on the templates.
 *
 * @param inputFile input file the user wants to generate code from
 * @param inputProject input project where the input file is located. We need this in order to build the classpath of
 *        the input file
 * @return the Java context created from the input project
 */
public static JavaContext getJavaContext(Path inputFile, Path inputProject) {
    String fqn = null;
    MavenUtil.resolveDependencies(inputProject);
    try {
        MavenDependencyCollector dependencyCollector = new MavenDependencyCollector(new MavenBridgeImpl(MavenUtil.determineMavenRepositoryPath().toFile()), false, true, null);
        JavaContext context = JavaSourceProviderUsingMaven.createFromLocalMavenProject(inputProject.toFile(), dependencyCollector);
        LOG.debug("Checking dependencies to exist.");
        if (dependencyCollector.asClassLoader() instanceof URLClassLoader) {
            for (URL url : dependencyCollector.asUrls()) {
                try {
                    if (!Files.exists(Paths.get(url.toURI()))) {
                        LOG.info("Found at least one maven dependency not to exist ({}).", url);
                        MavenUtil.resolveDependencies(inputProject);
                        // rerun collection
                        context = JavaSourceProviderUsingMaven.createFromLocalMavenProject(inputProject.toFile(), true);
                        break;
                    }
                } catch (URISyntaxException e) {
                    LOG.warn("Unable to check {} for existence", url, (LOG.isDebugEnabled() ? e : null));
                }
            }
            LOG.info("All dependencies exist on file system.");
        } else {
            LOG.debug("m-m-m classloader is instance of {}. Unable to check dependencies", dependencyCollector.asClassLoader().getClass());
        }
        fqn = getFQN(inputFile);
        context.getClassLoader().loadClass(fqn);
        return context;
    } catch (NoClassDefFoundError | ClassNotFoundException e) {
        throw new CobiGenRuntimeException("Compiled class " + fqn + " has not been found. Most probably you need to build project " + inputProject.toString() + ".", e);
    } catch (Exception e) {
        throw new CobiGenRuntimeException("Transitive dependencies have not been found on your m2 repository (Maven). Please run 'mvn package' " + "in your input project in order to download all the needed dependencies.", e);
    }
}
Also used : MavenDependencyCollector(net.sf.mmm.code.impl.java.source.maven.MavenDependencyCollector) JavaContext(net.sf.mmm.code.impl.java.JavaContext) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) MavenBridgeImpl(net.sf.mmm.code.java.maven.impl.MavenBridgeImpl) URLClassLoader(java.net.URLClassLoader) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) URISyntaxException(java.net.URISyntaxException)

Example 4 with CobiGenRuntimeException

use of com.devonfw.cobigen.api.exception.CobiGenRuntimeException in project cobigen by devonfw.

the class TypeScriptInputReader method read.

@Override
public Object read(Path path, Charset inputCharset, Object... additionalArguments) throws InputReaderException {
    String json = (String) super.read(path, inputCharset, additionalArguments);
    Map<String, Object> pojoModel = new HashMap<>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        // convert JSON string to Map
        pojoModel.put("model", mapper.readValue(json, new TypeReference<Map<String, Object>>() {
        }));
        return pojoModel;
    } catch (JsonGenerationException e) {
        throw new CobiGenRuntimeException("Exception during JSON writing. This is most probably a bug", e);
    } catch (JsonMappingException e) {
        throw new CobiGenRuntimeException("Exception during JSON mapping. This error occured while converting the templates model from JSON string to map", e);
    } catch (IOException e) {
        throw new CobiGenRuntimeException("IO exception while converting the templates model from JSON string to map", e);
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with CobiGenRuntimeException

use of com.devonfw.cobigen.api.exception.CobiGenRuntimeException in project cobigen by devonfw.

the class XmlMatcher method matches.

@Override
public boolean matches(MatcherTo matcher) {
    try {
        MatcherType matcherType = Enum.valueOf(MatcherType.class, matcher.getType().toUpperCase());
        Object target = matcher.getTarget();
        switch(matcherType) {
            case NODENAME:
                if (target instanceof Document) {
                    String documentRootName = ((Document) target).getDocumentElement().getNodeName();
                    return documentRootName != null && !documentRootName.equals("") && matcher.getValue().matches(documentRootName);
                }
                break;
            case XPATH:
                Node targetNode = getDocElem(target, 1);
                XPath xPath = createXpathObject(target);
                String xpathExpression = matcher.getValue();
                try {
                    return (boolean) xPath.evaluate(xpathExpression, targetNode, XPathConstants.BOOLEAN);
                } catch (XPathExpressionException e) {
                    if (checkXPathSyntax(xpathExpression)) {
                        return false;
                    }
                    throw new InvalidConfigurationException(xpathExpression, "Invalid XPath expression", e);
                }
        }
    } catch (IllegalArgumentException e) {
        throw new CobiGenRuntimeException("Matcher type " + matcher.getType() + " not registered!", e);
    }
    return false;
}
Also used : XPath(javax.xml.xpath.XPath) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Aggregations

CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)43 IOException (java.io.IOException)22 Path (java.nio.file.Path)15 File (java.io.File)8 LoggerFactory (org.slf4j.LoggerFactory)5 InvalidConfigurationException (com.devonfw.cobigen.api.exception.InvalidConfigurationException)4 TextTemplateEngine (com.devonfw.cobigen.api.extension.TextTemplateEngine)4 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)4 Trigger (com.devonfw.cobigen.impl.config.entity.Trigger)4 InputStream (java.io.InputStream)4 URL (java.net.URL)4 URLClassLoader (java.net.URLClassLoader)4 CobiGen (com.devonfw.cobigen.api.CobiGen)3 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)3 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)3 BackupFailedException (com.devonfw.cobigen.impl.exceptions.BackupFailedException)3 Paths (java.nio.file.Paths)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Logger (org.slf4j.Logger)3