Search in sources :

Example 11 with CobiGenRuntimeException

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

the class GenerationProcessorImpl method generateTemplateAndWriteFile.

/**
 * Generates the given template contents using the given model and writes the contents into the given {@link File}
 *
 * @param output {@link File} to be written
 * @param template FreeMarker template which will generate the contents
 * @param templateEngine template engine to be used
 * @param model to generate with
 * @param outputCharset charset the target file should be written with
 */
private void generateTemplateAndWriteFile(File output, Template template, TextTemplateEngine templateEngine, Map<String, Object> model, String outputCharset) {
    try (Writer out = new StringWriter()) {
        templateEngine.process(template, model, out, outputCharset);
        FileUtils.writeStringToFile(output, out.toString(), outputCharset);
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Could not write file while processing template " + template.getAbsoluteTemplatePath(), e);
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 12 with CobiGenRuntimeException

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

the class GenerationProcessorImpl method prependTemplatesClassloader.

/**
 * Prepend the classloader to get from the template folder to the classloader passed or create a new one. This method
 * will even make sure the code is compiled, if the templateFolder does not point to a jar, but maven project
 *
 * @param configLocation the template folder path or jar
 * @param inputProjectClassLoader an existing classloader or null
 * @return the combined classloader for the templates with classLoader argument as parent or null if both arguments
 *         passed as null
 */
private ClassLoader prependTemplatesClassloader(Path configLocation, ClassLoader inputProjectClassLoader) {
    ClassLoader combinedClassLoader = inputProjectClassLoader != null ? inputProjectClassLoader : Thread.currentThread().getContextClassLoader();
    if (configLocation != null) {
        Path pomFile = this.configurationHolder.getConfigurationPath().resolve("pom.xml");
        Path cpCacheFile = null;
        try {
            if (Files.exists(pomFile)) {
                LOG.debug("Found templates to be configured by maven.");
                String pomFileHash = MavenUtil.generatePomFileHash(pomFile);
                if (this.configurationHolder.isJarConfig()) {
                    cpCacheFile = configLocation.resolveSibling(String.format(MavenConstants.CLASSPATH_CACHE_FILE, pomFileHash));
                } else {
                    cpCacheFile = configLocation.resolve(String.format(MavenConstants.CLASSPATH_CACHE_FILE, pomFileHash));
                }
                combinedClassLoader = MavenUtil.addURLsFromCachedClassPathsFile(cpCacheFile, pomFile, combinedClassLoader);
            }
            // prepend jar/compiled resources as well
            URL[] urls;
            if (Files.isDirectory(configLocation) && Files.exists(pomFile)) {
                compileTemplateUtils(configLocation);
                urls = new URL[] { configLocation.resolve("target").resolve("classes").toUri().toURL() };
            } else {
                urls = new URL[] { configLocation.toUri().toURL() };
            }
            combinedClassLoader = new URLClassLoader(urls, combinedClassLoader);
            return combinedClassLoader;
        } catch (MalformedURLException e) {
            throw new CobiGenRuntimeException("Invalid Path", e);
        } catch (IOException e) {
            throw new CobiGenRuntimeException("Unable to read " + cpCacheFile, e);
        }
    } else {
        combinedClassLoader = inputProjectClassLoader;
    }
    return combinedClassLoader;
}
Also used : Path(java.nio.file.Path) MalformedURLException(java.net.MalformedURLException) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) IOException(java.io.IOException) URL(java.net.URL)

Example 13 with CobiGenRuntimeException

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

the class TemplateEngineRegistry method getEngine.

/**
 * Returns a {@link TextTemplateEngine template engine} based on its name.
 *
 * @param name of the {@link TextTemplateEngine template engine}
 * @return the {@link TextTemplateEngine template engine} or {@code null} if no template engine has been registered
 *         with the name.
 */
public static TextTemplateEngine getEngine(String name) {
    TextTemplateEngine templateEngine = registeredEngines.get(name);
    if (templateEngine == null) {
        for (Class<? extends TextTemplateEngine> engine : ClassServiceLoader.getTemplateEngineClasses()) {
            if (engine.isAnnotationPresent(Name.class)) {
                Name engineNameAnnotation = engine.getAnnotation(Name.class);
                String engineName = engineNameAnnotation.value();
                if (name.equals(engineName)) {
                    register(engine, engineName);
                    break;
                }
            } else {
                LOG.warn("Template engine '{}' should have a name specified by @Name annotation.", engine.getClass().getCanonicalName());
            }
        }
    }
    templateEngine = registeredEngines.get(name);
    if (templateEngine == null) {
        throw new CobiGenRuntimeException("No template engine with name '" + name + "' registered.");
    }
    return ProxyFactory.getProxy(templateEngine);
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) Name(com.devonfw.cobigen.api.annotation.Name)

Example 14 with CobiGenRuntimeException

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

the class FileSystemUtil method isZipFile.

/**
 * Determine whether a file is a ZIP File.
 *
 * @param uri {@link URI} to be checked
 * @return <code>true</code> if the file is a zip/jar file
 */
public static boolean isZipFile(URI uri) {
    File file = new File(uri);
    if (file.isDirectory()) {
        return false;
    }
    if (!file.canRead()) {
        throw new CobiGenRuntimeException("No permission to read file " + file.getAbsolutePath());
    }
    if (file.length() < 4) {
        return false;
    }
    // check "magic number" in the first 4bytes to indicate zip/jar resources
    try (FileInputStream fileInputstream = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputstream);
        DataInputStream in = new DataInputStream(bufferedInputStream)) {
        int test = in.readInt();
        in.close();
        return test == 0x504b0304;
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Unable to read file " + file.getAbsolutePath(), e);
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) BufferedInputStream(java.io.BufferedInputStream) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 15 with CobiGenRuntimeException

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

the class HealthCheckImpl method upgradeTemplatesConfiguration.

@Override
public HealthCheckReport upgradeTemplatesConfiguration(Path templatesConfigurationFolder, BackupPolicy backupPolicy) {
    LOG.info("Upgrade of the templates configuration in '{}' triggered.", templatesConfigurationFolder);
    System.out.println(templatesConfigurationFolder.toString());
    TemplateConfigurationUpgrader templateConfigurationUpgrader = new TemplateConfigurationUpgrader();
    try {
        templateConfigurationUpgrader.upgradeConfigurationToLatestVersion(templatesConfigurationFolder, backupPolicy);
        LOG.info("Upgrade finished successfully.");
    } catch (BackupFailedException e) {
        this.healthCheckReport.addError(e);
        if (containsAnyExceptionOfClass(BackupFailedException.class)) {
            templateConfigurationUpgrader.upgradeConfigurationToLatestVersion(templatesConfigurationFolder, BackupPolicy.NO_BACKUP);
            LOG.info("Upgrade finished successfully but without backup.");
        } else {
            this.healthCheckReport.addError(new CobiGenRuntimeException("Upgrade aborted"));
            LOG.info("Upgrade aborted.");
        }
    }
    return this.healthCheckReport;
}
Also used : TemplateConfigurationUpgrader(com.devonfw.cobigen.impl.config.upgrade.TemplateConfigurationUpgrader) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) BackupFailedException(com.devonfw.cobigen.impl.exceptions.BackupFailedException)

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