Search in sources :

Example 16 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project ngAndroid by davityle.

the class SourceCreator method createSourceFiles.

public void createSourceFiles() {
    Properties props = new Properties();
    props.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SystemLogChute");
    props.setProperty("resource.loader", "classpath");
    props.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    VelocityEngine ve = new VelocityEngine(props);
    ve.init();
    Template vtModel = ve.getTemplate("templates/ngmodel.vm");
    Template vtScope = ve.getTemplate("templates/scope.vm");
    Template vtLayout = ve.getTemplate("templates/layout.vm");
    for (NgModelSourceLink ms : modelSourceLinks) {
        try {
            JavaFileObject jfo = filer.createSourceFile(ms.getSourceFileName(), ms.getElements());
            Writer writer = jfo.openWriter();
            vtModel.merge(ms.getVelocityContext(), writer);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            messageUtils.error(Option.of(ms.getElements()[0]), e.getMessage());
        }
    }
    for (ScopeSourceLink ss : scopeSourceLinks) {
        try {
            JavaFileObject jfo = filer.createSourceFile(ss.getSourceFileName(), ss.getElements());
            Writer writer = jfo.openWriter();
            vtScope.merge(ss.getVelocityContext(), writer);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            messageUtils.error(Option.of(ss.getElements()[0]), e.getMessage());
        }
    }
    for (LayoutSourceLink lsl : layoutSourceLinks) {
        try {
            JavaFileObject jfo = filer.createSourceFile(lsl.getSourceFileName(), lsl.getElements());
            Writer writer = jfo.openWriter();
            vtLayout.merge(lsl.getVelocityContext(), writer);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            messageUtils.error(Option.<Element>absent(), e.getMessage());
        }
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) JavaFileObject(javax.tools.JavaFileObject) ScopeSourceLink(com.github.davityle.ngprocessor.source.links.ScopeSourceLink) Element(javax.lang.model.element.Element) LayoutSourceLink(com.github.davityle.ngprocessor.source.links.LayoutSourceLink) IOException(java.io.IOException) Properties(java.util.Properties) Writer(java.io.Writer) Template(org.apache.velocity.Template) NgModelSourceLink(com.github.davityle.ngprocessor.source.links.NgModelSourceLink)

Example 17 with VelocityEngine

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

the class VelocityEndpoint method onExchange.

@Override
protected void onExchange(Exchange exchange) throws Exception {
    String path = getResourceUri();
    ObjectHelper.notNull(path, "resourceUri");
    String newResourceUri = exchange.getIn().getHeader(VelocityConstants.VELOCITY_RESOURCE_URI, String.class);
    if (newResourceUri != null) {
        exchange.getIn().removeHeader(VelocityConstants.VELOCITY_RESOURCE_URI);
        log.debug("{} set to {} creating new endpoint to handle exchange", VelocityConstants.VELOCITY_RESOURCE_URI, newResourceUri);
        VelocityEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
        newEndpoint.onExchange(exchange);
        return;
    }
    Reader reader;
    String content = exchange.getIn().getHeader(VelocityConstants.VELOCITY_TEMPLATE, String.class);
    if (content != null) {
        // use content from header
        reader = new StringReader(content);
        if (log.isDebugEnabled()) {
            log.debug("Velocity content read from header {} for endpoint {}", VelocityConstants.VELOCITY_TEMPLATE, getEndpointUri());
        }
        // remove the header to avoid it being propagated in the routing
        exchange.getIn().removeHeader(VelocityConstants.VELOCITY_TEMPLATE);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Velocity content read from resource {} with resourceUri: {} for endpoint {}", new Object[] { getResourceUri(), path, getEndpointUri() });
        }
        reader = getEncoding() != null ? new InputStreamReader(getResourceAsInputStream(), getEncoding()) : new InputStreamReader(getResourceAsInputStream());
    }
    // getResourceAsInputStream also considers the content cache
    StringWriter buffer = new StringWriter();
    String logTag = getClass().getName();
    Context velocityContext = exchange.getIn().getHeader(VelocityConstants.VELOCITY_CONTEXT, Context.class);
    if (velocityContext == null) {
        Map<String, Object> variableMap = ExchangeHelper.createVariableMap(exchange);
        @SuppressWarnings("unchecked") Map<String, Object> supplementalMap = exchange.getIn().getHeader(VelocityConstants.VELOCITY_SUPPLEMENTAL_CONTEXT, Map.class);
        if (supplementalMap != null) {
            variableMap.putAll(supplementalMap);
        }
        velocityContext = new VelocityContext(variableMap);
    }
    // let velocity parse and generate the result in buffer
    VelocityEngine engine = getVelocityEngine();
    log.debug("Velocity is evaluating using velocity context: {}", velocityContext);
    engine.evaluate(velocityContext, buffer, logTag, reader);
    // now lets output the results to the exchange
    Message out = exchange.getOut();
    out.setBody(buffer.toString());
    out.setHeaders(exchange.getIn().getHeaders());
    out.setAttachments(exchange.getIn().getAttachments());
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) Context(org.apache.velocity.context.Context) VelocityEngine(org.apache.velocity.app.VelocityEngine) InputStreamReader(java.io.InputStreamReader) Message(org.apache.camel.Message) VelocityContext(org.apache.velocity.VelocityContext) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader)

Example 18 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project stashbot by palantir.

the class JenkinsJobXmlFormatter method generateJobXml.

public String generateJobXml(JobTemplate jobTemplate, Repository repo) throws SQLException {
    final VelocityContext vc = velocityManager.getVelocityContext();
    final RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
    final JenkinsServerConfiguration jsc = cpm.getJenkinsServerConfiguration(rc.getJenkinsServerName());
    RepositoryCloneLinksRequest rclr = new RepositoryCloneLinksRequest.Builder().repository(repo).protocol("http").user(null).build();
    String repositoryUrl = rs.getCloneLinks(rclr).iterator().next().getHref();
    String cleanRepositoryUrl = repositoryUrl;
    // Handle the various Authentication modes
    switch(jsc.getAuthenticationMode()) {
        case USERNAME_AND_PASSWORD:
            // manually insert the username and pw we are configured to use
            repositoryUrl = repositoryUrl.replace("://", "://" + jsc.getStashUsername() + ":" + jsc.getStashPassword() + "@");
            break;
        case CREDENTIAL_MANUALLY_CONFIGURED:
            vc.put("credentialUUID", jsc.getStashPassword());
            break;
    }
    vc.put("repositoryUrl", repositoryUrl);
    vc.put("cleanRepositoryUrl", cleanRepositoryUrl);
    vc.put("prebuildCommand", prebuildCommand(rc.getPrebuildCommand()));
    // TODO: figure out build command some other way?
    switch(jobTemplate.getJobType()) {
        case VERIFY_COMMIT:
            vc.put("buildCommand", buildCommand(rc.getVerifyBuildCommand()));
            break;
        case VERIFY_PR:
            vc.put("buildCommand", buildCommand(rc.getVerifyBuildCommand()));
            break;
        case PUBLISH:
            vc.put("buildCommand", buildCommand(rc.getPublishBuildCommand()));
            break;
        case NOOP:
            vc.put("buildCommand", buildCommand("/bin/true"));
            break;
    }
    // Add email notification stuff for all build types
    vc.put("isEmailNotificationsEnabled", rc.getEmailNotificationsEnabled());
    vc.put("emailRecipients", rc.getEmailRecipients());
    vc.put("isEmailForEveryUnstableBuild", rc.getEmailForEveryUnstableBuild());
    vc.put("isEmailSendToIndividuals", rc.getEmailSendToIndividuals());
    vc.put("isEmailPerModuleEmail", rc.getEmailPerModuleEmail());
    vc.put("startedCommand", curlCommandBuilder(repo, jobTemplate, rc, repositoryUrl, "inprogress"));
    vc.put("successCommand", curlCommandBuilder(repo, jobTemplate, rc, repositoryUrl, "successful"));
    vc.put("failedCommand", curlCommandBuilder(repo, jobTemplate, rc, repositoryUrl, "failed"));
    vc.put("repositoryLink", navBuilder.repo(repo).browse().buildAbsolute());
    vc.put("repositoryName", repo.getProject().getName() + " " + repo.getName());
    // Parameters are type-dependent for now
    ImmutableList.Builder<Map<String, String>> paramBuilder = new ImmutableList.Builder<Map<String, String>>();
    switch(jobTemplate.getJobType()) {
        case VERIFY_COMMIT:
            // repoId
            paramBuilder.add(ImmutableMap.of("name", "repoId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "stash repository Id", "defaultValue", "unknown"));
            // buildHead
            paramBuilder.add(ImmutableMap.of("name", "buildHead", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the change to build", "defaultValue", "head"));
            break;
        case VERIFY_PR:
            // repoId
            paramBuilder.add(ImmutableMap.of("name", "repoId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "stash repository Id", "defaultValue", "unknown"));
            // buildHead
            paramBuilder.add(ImmutableMap.of("name", "buildHead", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the change to build", "defaultValue", "head"));
            // pullRequestId
            paramBuilder.add(ImmutableMap.of("name", "pullRequestId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the pull request Id", "defaultValue", ""));
            break;
        case PUBLISH:
            // repoId
            paramBuilder.add(ImmutableMap.of("name", "repoId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "stash repository Id", "defaultValue", "unknown"));
            // buildHead
            paramBuilder.add(ImmutableMap.of("name", "buildHead", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the change to build", "defaultValue", "head"));
            break;
        case NOOP:
            // no params
            break;
    }
    vc.put("paramaterList", paramBuilder.build());
    // Junit settings
    vc.put("isJunit", rc.getJunitEnabled());
    vc.put("junitPath", rc.getJunitPath());
    // Artifact settings
    vc.put("artifactsEnabled", rc.getArtifactsEnabled());
    vc.put("artifactsPath", rc.getArtifactsPath());
    // insert pinned data
    switch(jobTemplate.getJobType()) {
        case VERIFY_COMMIT:
        case VERIFY_PR:
            vc.put("isPinned", rc.getVerifyPinned());
            vc.put("label", rc.getVerifyLabel());
            break;
        case PUBLISH:
            vc.put("isPinned", rc.getPublishPinned());
            vc.put("label", rc.getPublishLabel());
            break;
        case NOOP:
            vc.put("isPinned", false);
            break;
    }
    StringWriter xml = new StringWriter();
    VelocityEngine ve = velocityManager.getVelocityEngine();
    Template template = ve.getTemplate(jobTemplate.getTemplateFile());
    template.merge(vc, xml);
    return xml.toString();
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) ImmutableList(com.google.common.collect.ImmutableList) StashbotUrlBuilder(com.palantir.stash.stashbot.urlbuilder.StashbotUrlBuilder) NavBuilder(com.atlassian.stash.nav.NavBuilder) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) RepositoryCloneLinksRequest(com.atlassian.stash.repository.RepositoryCloneLinksRequest) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) Template(org.apache.velocity.Template) JobTemplate(com.palantir.stash.stashbot.persistence.JobTemplate)

Example 19 with VelocityEngine

use of org.apache.velocity.app.VelocityEngine in project qi4j-sdk by Qi4j.

the class RestServerAssembler method assemble.

@Override
public void assemble(ModuleAssembly module) throws AssemblyException {
    Properties props = new Properties();
    try {
        props.load(getClass().getResourceAsStream("/velocity.properties"));
        VelocityEngine velocity = new VelocityEngine(props);
        module.importedServices(VelocityEngine.class).importedBy(INSTANCE).setMetaInfo(velocity);
    } catch (Exception e) {
        throw new AssemblyException("Could not load velocity properties", e);
    }
    freemarker.template.Configuration cfg = new freemarker.template.Configuration();
    cfg.setClassForTemplateLoading(AbstractResponseWriter.class, "");
    cfg.setObjectWrapper(new ValueCompositeObjectWrapper());
    module.importedServices(freemarker.template.Configuration.class).setMetaInfo(cfg);
    module.importedServices(MetadataService.class);
    module.importedServices(ResponseWriterDelegator.class).identifiedBy("responsewriterdelegator").importedBy(NEW_OBJECT).visibleIn(Visibility.layer);
    module.objects(ResponseWriterDelegator.class);
    module.importedServices(RequestReaderDelegator.class).identifiedBy("requestreaderdelegator").importedBy(NEW_OBJECT).visibleIn(Visibility.layer);
    module.objects(RequestReaderDelegator.class);
    module.importedServices(InteractionConstraintsService.class).importedBy(NewObjectImporter.class).visibleIn(Visibility.application);
    module.objects(InteractionConstraintsService.class);
    // Standard response writers
    Iterable<Class<?>> writers = ClassScanner.findClasses(DefaultResponseWriter.class);
    Specification<Class<?>> responseWriterClass = isAssignableFrom(ResponseWriter.class);
    Specification<Class<?>> isNotAnAbstract = not(hasModifier(Modifier.ABSTRACT));
    Iterable<Class<?>> candidates = filter(and(isNotAnAbstract, responseWriterClass), writers);
    for (Class<?> responseWriter : candidates) {
        module.objects(responseWriter);
    }
    // Standard request readers
    module.objects(DefaultRequestReader.class);
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) ValueCompositeObjectWrapper(org.qi4j.library.rest.server.restlet.freemarker.ValueCompositeObjectWrapper) ResponseWriterDelegator(org.qi4j.library.rest.server.restlet.ResponseWriterDelegator) Properties(java.util.Properties) AssemblyException(org.qi4j.bootstrap.AssemblyException) AssemblyException(org.qi4j.bootstrap.AssemblyException) NewObjectImporter(org.qi4j.api.service.importer.NewObjectImporter) RequestReaderDelegator(org.qi4j.library.rest.server.restlet.RequestReaderDelegator)

Example 20 with VelocityEngine

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

the class VelocityHelper method evaluate.

public static String evaluate(PsiFile file, Project project, Module module, String template) {
    VelocityEngine engine = getEngine();
    VelocityContext vc = new VelocityContext();
    vc.put("today", new DateInfo());
    if (file != null)
        vc.put("file", new FileInfo(file));
    if (project != null)
        vc.put("project", new ProjectInfo(project));
    if (module != null)
        vc.put("module", new ModuleInfo(module));
    vc.put("username", System.getProperty("user.name"));
    if (file != null) {
        final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
        if (virtualFile != null) {
            final CopyrightVariablesProvider variablesProvider = CopyrightVariablesProviders.INSTANCE.forFileType(virtualFile.getFileType());
            if (variablesProvider != null) {
                final Map<String, Object> context = new HashMap<>();
                variablesProvider.collectVariables(context, project, module, file);
                for (Map.Entry<String, Object> entry : context.entrySet()) {
                    vc.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    try {
        StringWriter sw = new StringWriter();
        boolean stripLineBreak = false;
        if (template.endsWith("$")) {
            template += getVelocitySuffix();
            stripLineBreak = true;
        }
        engine.evaluate(vc, sw, CopyrightManager.class.getName(), template);
        final String result = sw.getBuffer().toString();
        return stripLineBreak ? StringUtil.trimEnd(result, getVelocitySuffix()) : result;
    } catch (Exception e) {
        return "";
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) VelocityEngine(org.apache.velocity.app.VelocityEngine) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) StringWriter(java.io.StringWriter) CopyrightManager(com.intellij.copyright.CopyrightManager) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

VelocityEngine (org.apache.velocity.app.VelocityEngine)29 VelocityContext (org.apache.velocity.VelocityContext)13 StringWriter (java.io.StringWriter)10 Properties (java.util.Properties)9 Template (org.apache.velocity.Template)9 IOException (java.io.IOException)7 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)6 Writer (java.io.Writer)5 File (java.io.File)4 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)4 CopyrightManager (com.intellij.copyright.CopyrightManager)3 InputStreamReader (java.io.InputStreamReader)3 Reader (java.io.Reader)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 ParseErrorException (org.apache.velocity.exception.ParseErrorException)3 FileNotFoundException (java.io.FileNotFoundException)2 InputStream (java.io.InputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2 Map (java.util.Map)2 ExtendedProperties (org.apache.commons.collections.ExtendedProperties)2