Search in sources :

Example 26 with CobiGenRuntimeException

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

the class VelocityTemplateEngine method process.

@Override
public void process(TextTemplate template, Map<String, Object> model, Writer out, String outputEncoding) {
    this.engine.setProperty(RuntimeConstants.OUTPUT_ENCODING, outputEncoding);
    executeInThisClassloader(null, (p) -> {
        this.engine.init();
        return null;
    });
    Context context = new VelocityContext(model);
    Template vmTemplate = null;
    try {
        vmTemplate = executeInThisClassloader(template.getRelativeTemplatePath(), (path) -> this.engine.getTemplate(path));
    } catch (Throwable e) {
        throw new CobiGenRuntimeException("An error occured while retrieving the Velocity template " + template.getAbsoluteTemplatePath() + " from the Velocity configuration. (Velocity v" + VelocityMetadata.VERSION + ")", e);
    }
    if (vmTemplate != null) {
        try {
            vmTemplate.merge(context, out);
        } catch (VelocityException e) {
            throw new CobiGenRuntimeException("An error occurred while generating the template." + template.getAbsoluteTemplatePath() + "(Velocity v" + VelocityMetadata.VERSION + ")", e);
        } catch (Throwable e) {
            throw new CobiGenRuntimeException("An unkonwn error occurred while generating the template." + template.getAbsoluteTemplatePath() + "(Velocity v" + VelocityMetadata.VERSION + ")", e);
        }
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) Context(org.apache.velocity.context.Context) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) NullResourceCache(com.devonfw.cobigen.tempeng.velocity.runtime.resources.NullResourceCache) LoggerFactory(org.slf4j.LoggerFactory) RuntimeConstants(org.apache.velocity.runtime.RuntimeConstants) Function(java.util.function.Function) VelocityContext(org.apache.velocity.VelocityContext) LogChuteDelegate(com.devonfw.cobigen.tempeng.velocity.log.LogChuteDelegate) Name(com.devonfw.cobigen.api.annotation.Name) Template(org.apache.velocity.Template) ResourceManagerDelegate(com.devonfw.cobigen.tempeng.velocity.runtime.resources.ResourceManagerDelegate) Context(org.apache.velocity.context.Context) VelocityEngine(org.apache.velocity.app.VelocityEngine) TextTemplate(com.devonfw.cobigen.api.extension.TextTemplate) Map(java.util.Map) Writer(java.io.Writer) VelocityMetadata(com.devonfw.cobigen.tempeng.velocity.constant.VelocityMetadata) VelocityException(org.apache.velocity.exception.VelocityException) Path(java.nio.file.Path) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) VelocityContext(org.apache.velocity.VelocityContext) VelocityException(org.apache.velocity.exception.VelocityException) Template(org.apache.velocity.Template) TextTemplate(com.devonfw.cobigen.api.extension.TextTemplate)

Example 27 with CobiGenRuntimeException

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

the class CobiGenPaths method getCobiGenHomePath.

/**
 * Returns the CobiGen home directory, or creates a new one if it does not exist
 *
 * @return {@link Path} of the CobiGen home directory
 */
public static Path getCobiGenHomePath() {
    String envValue = System.getenv(ConfigurationConstants.CONFIG_ENV_HOME);
    Path cobiGenPath;
    if (!StringUtils.isEmpty(envValue)) {
        LOG.info("Custom configuration folder configured in environment variable {}={}", ConfigurationConstants.CONFIG_ENV_HOME, envValue);
        cobiGenPath = Paths.get(envValue);
    } else {
        cobiGenPath = ConfigurationConstants.DEFAULT_HOME;
    }
    // We first check whether we already have a directory
    if (Files.exists(cobiGenPath)) {
        return cobiGenPath;
    }
    try {
        Files.createDirectories(cobiGenPath);
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Unable to create cobigen home directory at " + cobiGenPath);
    }
    return cobiGenPath;
}
Also used : Path(java.nio.file.Path) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) IOException(java.io.IOException)

Example 28 with CobiGenRuntimeException

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

the class AbstractConfigurationUpgrader method upgradeConfigurationToLatestVersion.

/**
 * Upgrades the configuration to the latest supported version.
 *
 * @param configurationRoot the root folder containing the configuration with the specified
 *        {@link #configurationFilename}. See {@link #AbstractConfigurationUpgrader(Enum, Class, String)} for more
 *        information.
 * @param backupPolicy the {@link BackupPolicy} to choose if a backup is necessary or not.
 * @return if manual adoptions has to be performed after upgrading
 * @throws BackupFailedException if the backup could not be created
 */
public boolean upgradeConfigurationToLatestVersion(Path configurationRoot, BackupPolicy backupPolicy) {
    boolean manualAdoptionsNecessary = false;
    VERSIONS_TYPE currentVersion = resolveLatestCompatibleSchemaVersion(configurationRoot);
    Path configurationFile = configurationRoot.resolve(this.configurationFilename);
    if (currentVersion == null) {
        throw new InvalidConfigurationException(configurationFile.toUri().toString(), StringUtils.capitalize(this.configurationName) + " does not match any current or legacy schema definitions.");
    } else {
        VERSIONS_TYPE latestVersion = this.versions[this.versions.length - 1];
        // increasing iteration of versions
        for (int i = 0; i < this.versions.length; i++) {
            if (currentVersion == latestVersion) {
                // already up to date
                break;
            }
            if (currentVersion == this.versions[i]) {
                LOG.info("Upgrading {} '{}' from version {} to {}...", this.configurationName, configurationFile.toUri(), this.versions[i], this.versions[i + 1]);
                Object rootNode;
                try {
                    Class<?> jaxbConfigurationClass = getJaxbConfigurationClass(this.versions[i]);
                    rootNode = unmarshallConfiguration(configurationFile, this.versions[i], jaxbConfigurationClass);
                    createBackup(configurationFile, backupPolicy);
                    // NotYetSupportedException
                    ConfigurationUpgradeResult result = performNextUpgradeStep(this.versions[i], rootNode);
                    manualAdoptionsNecessary |= result.areManualAdoptionsNecessary();
                    try (OutputStream out = Files.newOutputStream(configurationFile)) {
                        JAXB.marshal(result.getResultConfigurationJaxbRootNode(), out);
                    }
                    // implicitly check upgrade step
                    currentVersion = resolveLatestCompatibleSchemaVersion(configurationRoot);
                } catch (NotYetSupportedException | BackupFailedException e) {
                    throw e;
                } catch (Throwable e) {
                    throw new CobiGenRuntimeException("An unexpected exception occurred while upgrading the " + this.configurationName + " from version '" + this.versions[i] + "' to '" + this.versions[i + 1] + "'.", e);
                }
                // if CobiGen does not understand the upgraded file... throw exception
                if (currentVersion == null) {
                    throw new CobiGenRuntimeException("An error occurred while upgrading " + this.configurationName + " from version " + this.versions[i] + " to " + this.versions[i + 1] + ".");
                }
            }
        }
    }
    return manualAdoptionsNecessary;
}
Also used : Path(java.nio.file.Path) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) BackupFailedException(com.devonfw.cobigen.impl.exceptions.BackupFailedException) OutputStream(java.io.OutputStream) NotYetSupportedException(com.devonfw.cobigen.api.exception.NotYetSupportedException) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException)

Example 29 with CobiGenRuntimeException

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

the class BeanFactory method newInstance.

/**
 * Enforces the creation of a new instance just of the bean for the given interface. Objects for field initialization
 * will be retrieved from the registry. If there is already a bean instance registered for the given interface, this
 * bean will be overwritten by the newly created one. This method should just be used if a new object instance has to
 * be enforced.
 *
 * @param <T> type of the interface
 * @param interfaze to be instantiated
 * @return the newly created instance
 */
@SuppressWarnings("unchecked")
public <T> T newInstance(Class<T> interfaze) {
    try {
        for (Class<?> c : KNOWN_BEANS) {
            if (interfaze.isAssignableFrom(c)) {
                Object newInstance = c.newInstance();
                this.registry.put(interfaze.getCanonicalName(), ProxyFactory.getProxy(newInstance));
                initializeAndSetFields(newInstance);
                return (T) this.registry.get(interfaze.getCanonicalName());
            }
        }
    } catch (InstantiationException | IllegalAccessException e) {
        throw new CobiGenRuntimeException("Failure on initialization of class " + interfaze.getCanonicalName(), e);
    }
    throw new CobiGenRuntimeException("Could find bean implementation for interface " + interfaze.getCanonicalName() + " as no class of such has been registered at AopFactory#KNOWN_BEANS");
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException)

Example 30 with CobiGenRuntimeException

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

the class MavenUtil method addURLsFromCachedClassPathsFile.

/**
 * Adds URLs from class paths cache file to URLClassLoader. If no class paths cache file was found a new one will be
 * generated.
 *
 * @param classPathCacheFile the class paths cache file to read/create
 * @param pomFile POM file that defines the needed CobiGen dependencies to build
 * @param parentClassLoader parent ClassLoader
 *
 * @return URLClassLoader
 */
public static URLClassLoader addURLsFromCachedClassPathsFile(Path classPathCacheFile, Path pomFile, ClassLoader parentClassLoader) {
    if (!Files.exists(classPathCacheFile)) {
        LOG.debug("Building class paths for maven configuration ...");
        cacheMavenClassPath(pomFile, classPathCacheFile);
    } else {
        LOG.debug("Taking cached class paths from: {}", classPathCacheFile);
    }
    try (Stream<String> fileLinesStream = Files.lines(classPathCacheFile)) {
        URL[] classPathEntries = fileLinesStream.flatMap(e -> Arrays.stream(e.split(SystemUtil.getOS().contains("win") ? ";" : ":"))).map(path -> {
            try {
                return new File(path).toURI().toURL();
            } catch (MalformedURLException e) {
                LOG.error("URL of class path entry {} is malformed", path, e);
            }
            return null;
        }).toArray(size -> new URL[size]);
        return new URLClassLoader(classPathEntries, parentClassLoader);
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Unable to read " + classPathCacheFile, e);
    }
}
Also used : Arrays(java.util.Arrays) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) Hashing(com.google.common.hash.Hashing) StringUtils(org.apache.commons.lang3.StringUtils) Slf4jStream(org.zeroturnaround.exec.stream.slf4j.Slf4jStream) ProcessResult(org.zeroturnaround.exec.ProcessResult) URLClassLoader(java.net.URLClassLoader) Future(java.util.concurrent.Future) Matcher(java.util.regex.Matcher) Lists(com.google.common.collect.Lists) ByteSource(com.google.common.io.ByteSource) Path(java.nio.file.Path) Logger(org.slf4j.Logger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) SystemUtils(org.apache.commons.lang3.SystemUtils) IOException(java.io.IOException) ProcessExecutor(org.zeroturnaround.exec.ProcessExecutor) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) StartedProcess(org.zeroturnaround.exec.StartedProcess) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) Pattern(java.util.regex.Pattern) MavenConstants(com.devonfw.cobigen.api.constants.MavenConstants) MalformedURLException(java.net.MalformedURLException) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) URLClassLoader(java.net.URLClassLoader) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL)

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