Search in sources :

Example 31 with CobiGenRuntimeException

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

the class TemplatesJarUtil method downloadJar.

/**
 * @param groupId of the artifact to download
 * @param artifactId of the artifact to download
 * @param version of the artifact to download
 * @param isDownloadSource true if downloading source jar file
 * @param templatesDirectory directory where the templates jar are located
 * @return fileName Name of the file downloaded
 */
private static String downloadJar(String groupId, String artifactId, String version, boolean isDownloadSource, File templatesDirectory) {
    // By default the version should be latest
    if (version.isEmpty() || version == null) {
        version = "LATEST";
    }
    String mavenUrl = "https://repository.sonatype.org/service/local/artifact/maven/" + "redirect?r=central-proxy&g=" + groupId + "&a=" + artifactId + "&v=" + version;
    if (isDownloadSource) {
        mavenUrl = mavenUrl + "&c=sources";
    }
    String fileName = "";
    File[] jarFiles;
    if (isDownloadSource) {
        jarFiles = templatesDirectory.listFiles(fileNameFilterSources);
    } else {
        jarFiles = templatesDirectory.listFiles(fileNameFilterJar);
    }
    try {
        if (jarFiles.length <= 0 || isJarOutdated(jarFiles[0], mavenUrl, isDownloadSource, templatesDirectory)) {
            HttpURLConnection conn = initializeConnection(mavenUrl);
            try (InputStream inputStream = conn.getInputStream()) {
                fileName = conn.getURL().getFile().substring(conn.getURL().getFile().lastIndexOf("/") + 1);
                File file = new File(templatesDirectory.getPath() + File.separator + fileName);
                Path targetPath = file.toPath();
                if (!file.exists()) {
                    Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
                }
            }
            conn.disconnect();
        } else {
            fileName = jarFiles[0].getPath().substring(jarFiles[0].getPath().lastIndexOf(File.separator) + 1);
        }
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Could not download file from " + mavenUrl, e);
    }
    return fileName;
}
Also used : Path(java.nio.file.Path) HttpURLConnection(java.net.HttpURLConnection) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) InputStream(java.io.InputStream) IOException(java.io.IOException) File(java.io.File)

Example 32 with CobiGenRuntimeException

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

the class ProxyFactory method getProxy.

/**
 * Creates a new dynamic proxy for a given target object and registers the handlers.
 *
 * @param <T> type of the target object.
 * @param targetObject the target object
 * @return the proxied targetObject
 */
@SuppressWarnings("unchecked")
public static <T> T getProxy(T targetObject) {
    // assure single wrapping
    if (Proxy.isProxyClass(targetObject.getClass()) && Proxy.getInvocationHandler(targetObject) instanceof AbstractInterceptor) {
        return targetObject;
    }
    // ask cache
    T proxyObject = (T) _cache.get(targetObject);
    if (proxyObject != null) {
        if (Boolean.FALSE.equals(proxyObject)) {
            return targetObject;
        } else {
            LOG.debug("Taking proxy for {}", targetObject.getClass());
            return proxyObject;
        }
    }
    // create proxy if not cached
    boolean proxied = false;
    for (String annotationClass : collectAnnotations(targetObject.getClass())) {
        proxyObject = targetObject;
        Class<? extends AbstractInterceptor> interceptorClass = annotationToInterceptorMap.get(annotationClass);
        if (interceptorClass != null) {
            AbstractInterceptor interceptor;
            try {
                interceptor = interceptorClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new CobiGenRuntimeException("Unable to instantiate class " + interceptorClass.getCanonicalName());
            }
            interceptor.setTargetObject(proxyObject);
            proxyObject = (T) Proxy.newProxyInstance(proxyObject.getClass().getClassLoader(), proxyObject.getClass().getInterfaces(), interceptor);
            proxied = true;
            LOG.debug("Created proxy for {} with {} interceptor", targetObject.getClass(), interceptorClass);
        }
    }
    if (proxied) {
        // if any proxy has been generated -> cache
        _cache.put(targetObject, proxyObject);
    } else {
        // if not annotated -> mark
        _cache.put(targetObject, false);
    }
    return proxyObject != null ? proxyObject : targetObject;
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException)

Example 33 with CobiGenRuntimeException

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

the class CobiGenPropertiesReader method load.

/**
 * @param folder the {@link Path} pointing to the folder that may contain a {@code cobigen.properties} file.
 * @param parent the parent {@link Properties} to inherit from and override with potentially read properties.
 * @return the new {@link Properties} containing the properties from a potential {@code cobigen.properties} merged
 *         with the given {@code parent} properties.
 */
public static final Properties load(Path folder, Properties parent) {
    Path propertiesPath = folder.resolve(ConfigurationConstants.COBIGEN_PROPERTIES);
    if (!Files.exists(propertiesPath)) {
        if (parent == null) {
            return new Properties();
        }
        return parent;
    }
    Properties properties = new Properties();
    if (parent != null) {
        properties.putAll(parent);
    }
    try (Reader reader = Files.newBufferedReader(propertiesPath, UTF_8)) {
        properties.load(reader);
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Failed to read " + ConfigurationConstants.COBIGEN_PROPERTIES + " from " + folder, e);
    }
    return properties;
}
Also used : Path(java.nio.file.Path) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Reader(java.io.Reader) IOException(java.io.IOException) Properties(java.util.Properties)

Example 34 with CobiGenRuntimeException

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

Example 35 with CobiGenRuntimeException

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

the class GenerationProcessorImpl method compileTemplateUtils.

/**
 * Compile a template folder by executing MVN
 *
 * @param templateFolder the cobigen template folder
 */
private void compileTemplateUtils(Path templateFolder) {
    LOG.debug("Build templates folder {}", templateFolder);
    try {
        StartedProcess process = new ProcessExecutor().destroyOnExit().directory(templateFolder.toFile()).command(SystemUtil.determineMvnPath().toString(), "compile", // https://stackoverflow.com/a/66801171
        "-Djansi.force=true", "-Djansi.passthrough=true", "-B", "-Dorg.slf4j.simpleLogger.defaultLogLevel=" + (LOG.isDebugEnabled() ? "DEBUG" : "INFO"), "-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN", "-q").redirectError(Slf4jStream.of(LoggerFactory.getLogger(GenerationProcessorImpl.class.getName() + "." + "mvn-compile-templates")).asError()).redirectOutput(Slf4jStream.of(LoggerFactory.getLogger(GenerationProcessorImpl.class.getName() + "." + "mvn-compile-templates")).asInfo()).start();
        Future<ProcessResult> future = process.getFuture();
        ProcessResult processResult = future.get();
        if (processResult.getExitValue() != 0) {
            throw new CobiGenRuntimeException("Unable to compile template project " + templateFolder);
        }
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new CobiGenRuntimeException("Unable to compile template project " + templateFolder, e);
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) ProcessResult(org.zeroturnaround.exec.ProcessResult) IOException(java.io.IOException) ProcessExecutor(org.zeroturnaround.exec.ProcessExecutor) ExecutionException(java.util.concurrent.ExecutionException) StartedProcess(org.zeroturnaround.exec.StartedProcess)

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