Search in sources :

Example 26 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 27 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 28 with VelocityEngine

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

the class VelocityFactory method newVeloictyEngine.

/**
   * Returns a new instance of the VelocityEngine.
   * <p/>
   * The engine is initialized and outputs its logging to IDEA logging.
   *
   * @return a new velocity engine that is initialized.
   */
private static VelocityEngine newVeloictyEngine() {
    ExtendedProperties prop = new ExtendedProperties();
    prop.addProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SimpleLog4JLogSystem.class.getName());
    prop.addProperty("runtime.log.logsystem.log4j.category", "GenerateToString");
    prop.addProperty(RuntimeConstants.RESOURCE_LOADER, "includes");
    prop.addProperty("includes.resource.loader.class", VelocityIncludesClassLoader.class.getName());
    VelocityEngine velocity = new VelocityEngine();
    velocity.setExtendedProperties(prop);
    velocity.init();
    return velocity;
}
Also used : SimpleLog4JLogSystem(org.apache.velocity.runtime.log.SimpleLog4JLogSystem) VelocityEngine(org.apache.velocity.app.VelocityEngine) VelocityIncludesClassLoader(com.intellij.codeInsight.generation.VelocityIncludesClassLoader) ExtendedProperties(org.apache.commons.collections.ExtendedProperties)

Example 29 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)

Example 30 with VelocityEngine

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

the class VelocityHelper method verify.

public static void verify(String text) throws Exception {
    VelocityEngine engine = getEngine();
    VelocityContext vc = new VelocityContext();
    vc.put("today", new DateInfo());
    StringWriter sw = new StringWriter();
    if (text.endsWith("$")) {
        text += getVelocitySuffix();
    }
    engine.evaluate(vc, sw, CopyrightManager.class.getName(), text);
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) CopyrightManager(com.intellij.copyright.CopyrightManager) VelocityContext(org.apache.velocity.VelocityContext)

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