Search in sources :

Example 31 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project intellij-community by JetBrains.

the class VelocityHelper method getEngine.

private static synchronized VelocityEngine getEngine() {
    if (instance == null) {
        try {
            VelocityEngine engine = new VelocityEngine();
            ExtendedProperties extendedProperties = new ExtendedProperties();
            extendedProperties.addProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            extendedProperties.addProperty(RuntimeConstants.PARSER_POOL_SIZE, "1");
            extendedProperties.addProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
            extendedProperties.addProperty("file.resource.loader.path", PathManager.getPluginsPath() + "/Copyright/resources");
            extendedProperties.addProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SimpleLog4JLogSystem.class.getName());
            extendedProperties.addProperty("runtime.log.logsystem.log4j.category", CopyrightManager.class.getName());
            engine.setExtendedProperties(extendedProperties);
            engine.init();
            instance = engine;
        } catch (Exception ignored) {
        }
    }
    return instance;
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) SimpleLog4JLogSystem(org.apache.velocity.runtime.log.SimpleLog4JLogSystem) CopyrightManager(com.intellij.copyright.CopyrightManager) ExtendedProperties(org.apache.commons.collections.ExtendedProperties)

Example 32 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project intellij-community by JetBrains.

the class GenerationUtil method velocityGenerateCode.

/**
   * Generates the code using Velocity.
   * <p/>
   * This is used to create the {@code toString} method body and it's javadoc.
   *
   * @param selectedMembers the selected members as both {@link PsiField} and {@link PsiMethod}.
   * @param params          additional parameters stored with key/value in the map.
   * @param templateMacro   the velocity macro template
   * @param useAccessors    if true, accessor property for FieldElement bean would be assigned to field getter name append with () 
   * @return code (usually javacode). Returns null if templateMacro is null.
   * @throws GenerateCodeException is thrown when there is an error generating the javacode.
   */
public static String velocityGenerateCode(@Nullable PsiClass clazz, Collection<? extends PsiMember> selectedMembers, Collection<? extends PsiMember> selectedNotNullMembers, Map<String, String> params, Map<String, Object> contextMap, String templateMacro, int sortElements, boolean useFullyQualifiedName, boolean useAccessors) throws GenerateCodeException {
    if (templateMacro == null) {
        return null;
    }
    StringWriter sw = new StringWriter();
    try {
        VelocityContext vc = new VelocityContext();
        // field information
        logger.debug("Velocity Context - adding fields");
        final List<FieldElement> fieldElements = ElementUtils.getOnlyAsFieldElements(selectedMembers, selectedNotNullMembers, useAccessors);
        vc.put("fields", fieldElements);
        if (fieldElements.size() == 1) {
            vc.put("field", fieldElements.get(0));
        }
        PsiMember member = clazz != null ? clazz : ContainerUtil.getFirstItem(selectedMembers);
        // method information
        logger.debug("Velocity Context - adding methods");
        vc.put("methods", ElementUtils.getOnlyAsMethodElements(selectedMembers));
        // element information (both fields and methods)
        logger.debug("Velocity Context - adding members (fields and methods)");
        List<Element> elements = ElementUtils.getOnlyAsFieldAndMethodElements(selectedMembers, selectedNotNullMembers, useAccessors);
        // sort elements if enabled and not using chooser dialog
        if (sortElements != 0 && sortElements < 3) {
            Collections.sort(elements, new ElementComparator(sortElements));
        }
        vc.put("members", elements);
        // class information
        if (clazz != null) {
            ClassElement ce = ElementFactory.newClassElement(clazz);
            vc.put("class", ce);
            if (logger.isDebugEnabled())
                logger.debug("Velocity Context - adding class: " + ce);
            // information to keep as it is to avoid breaking compatibility with prior releases
            vc.put("classname", useFullyQualifiedName ? ce.getQualifiedName() : ce.getName());
            vc.put("FQClassname", ce.getQualifiedName());
        }
        if (member != null) {
            vc.put("java_version", PsiAdapter.getJavaVersion(member));
            final Project project = member.getProject();
            vc.put("settings", CodeStyleSettingsManager.getSettings(project));
            vc.put("project", project);
        }
        vc.put("helper", GenerationHelper.class);
        vc.put("StringUtil", StringUtil.class);
        vc.put("NameUtil", NameUtil.class);
        for (String paramName : contextMap.keySet()) {
            vc.put(paramName, contextMap.get(paramName));
        }
        if (logger.isDebugEnabled())
            logger.debug("Velocity Macro:\n" + templateMacro);
        // velocity
        VelocityEngine velocity = VelocityFactory.getVelocityEngine();
        logger.debug("Executing velocity +++ START +++");
        velocity.evaluate(vc, sw, GenerateToStringWorker.class.getName(), templateMacro);
        logger.debug("Executing velocity +++ END +++");
        // any additional packages to import returned from velocity?
        if (vc.get("autoImportPackages") != null) {
            params.put("autoImportPackages", (String) vc.get("autoImportPackages"));
        }
    } catch (ProcessCanceledException e) {
        throw e;
    } catch (Exception e) {
        throw new GenerateCodeException("Error in Velocity code generator", e);
    }
    return StringUtil.convertLineSeparators(sw.getBuffer().toString());
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) VelocityContext(org.apache.velocity.VelocityContext) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) GenerateCodeException(org.jetbrains.java.generate.exception.GenerateCodeException) PluginException(org.jetbrains.java.generate.exception.PluginException) GenerateCodeException(org.jetbrains.java.generate.exception.GenerateCodeException) Project(com.intellij.openapi.project.Project) StringWriter(java.io.StringWriter) PsiMember(com.intellij.psi.PsiMember) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 33 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project Asqatasun by Asqatasun.

the class CodeGeneratorMojo method execute.

@Override
public void execute() {
    try {
        isContextValid();
    } catch (InvalidParameterException ipe) {
        Logger.getLogger(CodeGeneratorMojo.class.getName()).log(Level.SEVERE, null, ipe);
        return;
    }
    // Initializes engine
    VelocityEngine ve = initializeVelocity();
    Iterable<CSVRecord> records = getCsv();
    if (records == null) {
        return;
    }
    try {
        initializeContext();
        generate(ve, records);
        cleanUpUnusedFiles();
    } catch (IOException ex) {
        Logger.getLogger(CodeGeneratorMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ResourceNotFoundException ex) {
        Logger.getLogger(CodeGeneratorMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseErrorException ex) {
        Logger.getLogger(CodeGeneratorMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(CodeGeneratorMojo.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : InvalidParameterException(org.asqatasun.referential.creator.exception.InvalidParameterException) VelocityEngine(org.apache.velocity.app.VelocityEngine) ParseErrorException(org.apache.velocity.exception.ParseErrorException) CSVRecord(org.apache.commons.csv.CSVRecord) IOException(java.io.IOException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) InvalidParameterException(org.asqatasun.referential.creator.exception.InvalidParameterException) I18NLanguageNotFoundException(org.asqatasun.referential.creator.exception.I18NLanguageNotFoundException) ParseErrorException(org.apache.velocity.exception.ParseErrorException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException)

Example 34 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project midpoint by Evolveum.

the class SchemaDocMojo method createVelocityEngine.

private VelocityEngine createVelocityEngine() {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty("resource.loader", "file");
    ve.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
    ve.setProperty("file.resource.loader.path", getTemplateDirName());
    ve.setProperty("file.resource.loader.cache", "true");
    ve.setProperty("directive.set.null.allowed", "true");
    ve.init();
    return ve;
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine)

Example 35 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project maven-plugins by apache.

the class ProcessRemoteResourcesMojo method execute.

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping remote resources execution.");
        return;
    }
    if (StringUtils.isEmpty(encoding)) {
        getLog().warn("File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!");
    }
    if (runOnlyAtExecutionRoot && !project.isExecutionRoot()) {
        getLog().info("Skipping remote-resource generation in this project because it's not the Execution Root");
        return;
    }
    if (resolveScopes == null) {
        if (excludeScope == null || "".equals(excludeScope)) {
            resolveScopes = new String[] { this.includeScope };
        } else {
            resolveScopes = new String[] { Artifact.SCOPE_TEST };
        }
    }
    velocity = new VelocityEngine();
    velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
    velocity.setProperty("resource.loader", "classpath");
    velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocity.init();
    if (supplementalModels == null) {
        File sups = new File(appendedResourcesDirectory, "supplemental-models.xml");
        if (sups.exists()) {
            try {
                supplementalModels = new String[] { sups.toURI().toURL().toString() };
            } catch (MalformedURLException e) {
                // ignore
                getLog().debug("URL issue with supplemental-models.xml: " + e.toString());
            }
        }
    }
    addSupplementalModelArtifacts();
    locator.addSearchPath(FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath());
    if (appendedResourcesDirectory != null) {
        locator.addSearchPath(FileResourceLoader.ID, appendedResourcesDirectory.getAbsolutePath());
    }
    locator.addSearchPath("url", "");
    locator.setOutputDirectory(new File(project.getBuild().getDirectory()));
    if (includeProjectProperties) {
        final Properties projectProperties = project.getProperties();
        for (Object key : projectProperties.keySet()) {
            properties.put(key.toString(), projectProperties.get(key).toString());
        }
    }
    ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        validate();
        List<File> resourceBundleArtifacts = downloadBundles(resourceBundles);
        supplementModels = loadSupplements(supplementalModels);
        VelocityContext context = new VelocityContext(properties);
        configureVelocityContext(context);
        RemoteResourcesClassLoader classLoader = new RemoteResourcesClassLoader(null);
        initalizeClassloader(classLoader, resourceBundleArtifacts);
        Thread.currentThread().setContextClassLoader(classLoader);
        processResourceBundles(classLoader, context);
        try {
            if (outputDirectory.exists()) {
                // ----------------------------------------------------------------------------
                // Push our newly generated resources directory into the MavenProject so that
                // these resources can be picked up by the process-resources phase.
                // ----------------------------------------------------------------------------
                Resource resource = new Resource();
                resource.setDirectory(outputDirectory.getAbsolutePath());
                // MRRESOURCES-61 handle main and test resources separately
                if (attachToMain) {
                    project.getResources().add(resource);
                }
                if (attachToTest) {
                    project.getTestResources().add(resource);
                }
                // ----------------------------------------------------------------------------
                // Write out archiver dot file
                // ----------------------------------------------------------------------------
                File dotFile = new File(project.getBuild().getDirectory(), ".plxarc");
                FileUtils.mkdir(dotFile.getParentFile().getAbsolutePath());
                FileUtils.fileWrite(dotFile.getAbsolutePath(), outputDirectory.getName());
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Error creating dot file for archiving instructions.", e);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(origLoader);
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) MalformedURLException(java.net.MalformedURLException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) VelocityContext(org.apache.velocity.VelocityContext) Resource(org.apache.maven.model.Resource) IOException(java.io.IOException) Properties(java.util.Properties) ClasspathResourceLoader(org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader) File(java.io.File)

Aggregations

VelocityEngine (org.apache.velocity.app.VelocityEngine)49 VelocityContext (org.apache.velocity.VelocityContext)23 StringWriter (java.io.StringWriter)21 Template (org.apache.velocity.Template)21 Properties (java.util.Properties)15 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)14 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)9 IOException (java.io.IOException)8 ParseErrorException (org.apache.velocity.exception.ParseErrorException)7 File (java.io.File)4 Writer (java.io.Writer)4 CommonsLogLogChute (org.apache.velocity.runtime.log.CommonsLogLogChute)4 SystemException (com.github.bordertech.wcomponents.util.SystemException)3 CopyrightManager (com.intellij.copyright.CopyrightManager)3 InputStreamReader (java.io.InputStreamReader)3 Reader (java.io.Reader)3 HashMap (java.util.HashMap)3 FileNotFoundException (java.io.FileNotFoundException)2 InputStream (java.io.InputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2