Search in sources :

Example 36 with Template

use of org.apache.velocity.Template 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 37 with Template

use of org.apache.velocity.Template in project roboguice by roboguice.

the class AnnotationDatabaseGenerator method generateAnnotationDatabase.

public void generateAnnotationDatabase(JavaFileObject jfo) throws IOException {
    Properties props = new Properties();
    props.put("resource.loader", "class");
    props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(props);
    VelocityContext context = createVelocityContext();
    Template template = null;
    PrintWriter w = null;
    try {
        template = Velocity.getTemplate(templatePath);
        w = new PrintWriter(jfo.openWriter());
        template.merge(context, w);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new IOException("Impossible to generate annotation database.", ex);
    } finally {
        if (w != null) {
            try {
                w.close();
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new IOException("Impossible to close annotation database.", ex);
            }
        }
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) Template(org.apache.velocity.Template) PrintWriter(java.io.PrintWriter)

Example 38 with Template

use of org.apache.velocity.Template in project cachecloud by sohutv.

the class VelocityUtils method createText.

/**
     * 邮件模板
     *
     * @param appDesc       应用信息
     * @param appAudit      处理信息
     * @param templatePath  模板路径
     * @param customCharset 编码
     */
public static synchronized String createText(VelocityEngine engine, AppDesc appDesc, AppAudit appAudit, AppDailyData appDailyData, List<InstanceAlertValueResult> instanceAlertValueResultList, String templatePath, String customCharset) {
    if (!StringUtils.isEmpty(customCharset)) {
        charset = customCharset;
    }
    Properties p = new Properties();
    p.setProperty("file.resource.loader.path", Thread.currentThread().getContextClassLoader().getResource("").getPath());
    p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
    p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
    p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
    Velocity.init(p);
    logger.info("velocity: init done.");
    VelocityContext context = new VelocityContext();
    context.put("appDesc", appDesc);
    context.put("appAudit", appAudit);
    context.put("appDailyData", appDailyData);
    context.put("instanceAlertValueResultList", instanceAlertValueResultList);
    context.put("numberTool", new NumberTool());
    context.put("ccDomain", ConstUtils.CC_DOMAIN);
    context.put("decimalFormat", new DecimalFormat("###,###"));
    context.put("StringUtils", StringUtils.class);
    FileOutputStream fos = null;
    StringWriter writer = null;
    try {
        Template template = engine.getTemplate(templatePath);
        writer = new StringWriter();
        template.merge(context, writer);
    } catch (ResourceNotFoundException ex) {
        logger.error("error: velocity vm resource not found.", ex);
    } catch (ParseErrorException ex) {
        logger.error("error: velocity parse vm file error.", ex);
    } catch (MethodInvocationException ex) {
        logger.error("error: velocity template merge.", ex);
    } catch (Exception ex) {
        logger.error("error", ex);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            logger.error("error: close writer", e);
        }
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            logger.error("error: close output stream.", e);
        }
    }
    logger.info("velocity: create text done.");
    if (writer != null) {
        return writer.toString();
    }
    return null;
}
Also used : NumberTool(org.apache.velocity.tools.generic.NumberTool) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) DecimalFormat(java.text.DecimalFormat) FileOutputStream(java.io.FileOutputStream) ParseErrorException(org.apache.velocity.exception.ParseErrorException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) IOException(java.io.IOException) Properties(java.util.Properties) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) ParseErrorException(org.apache.velocity.exception.ParseErrorException) IOException(java.io.IOException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) Template(org.apache.velocity.Template)

Example 39 with Template

use of org.apache.velocity.Template in project midpoint by Evolveum.

the class SchemaDocMojo method renderSchema.

private void renderSchema(PrismSchema schema, PrismContext prismContext, VelocityEngine velocityEngine, PathGenerator pathGenerator) throws IOException {
    getLog().info("Processing schema: " + schema);
    VelocityContext velocityContext = new VelocityContext();
    populateVelocityContextBase(velocityContext, prismContext, pathGenerator, schema, "..");
    Template template = velocityEngine.getTemplate(TEMPLATE_SCHEMA_NAME);
    Writer writer = new FileWriter(pathGenerator.prepareSchemaOutputFile(schema));
    template.merge(velocityContext, writer);
    writer.close();
    // Object Definitions
    for (PrismObjectDefinition objectDefinition : schema.getObjectDefinitions()) {
        renderObjectDefinition(objectDefinition, schema, prismContext, velocityEngine, pathGenerator);
    }
    // Types
    for (ComplexTypeDefinition typeDefinition : schema.getComplexTypeDefinitions()) {
        renderComplexTypeDefinition(typeDefinition, schema, prismContext, velocityEngine, pathGenerator);
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) PrismObjectDefinition(com.evolveum.midpoint.prism.PrismObjectDefinition) ComplexTypeDefinition(com.evolveum.midpoint.prism.ComplexTypeDefinition) Template(org.apache.velocity.Template)

Example 40 with Template

use of org.apache.velocity.Template in project lucene-solr by apache.

the class VelocityResponseWriter method write.

@Override
public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException {
    // TODO: have HTTP headers available for configuring engine
    VelocityEngine engine = createEngine(request);
    Template template = getTemplate(engine, request);
    VelocityContext context = createContext(request, response);
    // for $engine.resourceExists(...)
    context.put("engine", engine);
    String layoutTemplate = request.getParams().get(LAYOUT);
    boolean layoutEnabled = request.getParams().getBool(LAYOUT_ENABLED, true) && layoutTemplate != null;
    String jsonWrapper = request.getParams().get(JSON);
    boolean wrapResponse = layoutEnabled || jsonWrapper != null;
    // create output
    if (!wrapResponse) {
        // straight-forward template/context merge to output
        template.merge(context, writer);
    } else {
        // merge to a string buffer, then wrap with layout and finally as JSON
        StringWriter stringWriter = new StringWriter();
        template.merge(context, stringWriter);
        if (layoutEnabled) {
            context.put("content", stringWriter.toString());
            stringWriter = new StringWriter();
            try {
                engine.getTemplate(layoutTemplate + TEMPLATE_EXTENSION).merge(context, stringWriter);
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }
        if (jsonWrapper != null) {
            writer.write(jsonWrapper + "(");
            writer.write(getJSONWrap(stringWriter.toString()));
            writer.write(')');
        } else {
            // using a layout, but not JSON wrapping
            writer.write(stringWriter.toString());
        }
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) IOException(java.io.IOException) IOException(java.io.IOException) Template(org.apache.velocity.Template)

Aggregations

Template (org.apache.velocity.Template)59 VelocityContext (org.apache.velocity.VelocityContext)41 StringWriter (java.io.StringWriter)28 VelocityEngine (org.apache.velocity.app.VelocityEngine)21 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)12 IOException (java.io.IOException)11 ParseErrorException (org.apache.velocity.exception.ParseErrorException)8 Writer (java.io.Writer)7 File (java.io.File)6 Map (java.util.Map)6 Properties (java.util.Properties)6 FileWriter (java.io.FileWriter)5 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)5 PrintWriter (java.io.PrintWriter)4 MethodInvocationException (org.apache.velocity.exception.MethodInvocationException)4 SystemException (com.github.bordertech.wcomponents.util.SystemException)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 FileOutputStream (java.io.FileOutputStream)3 HashMap (java.util.HashMap)3 UIContext (com.github.bordertech.wcomponents.UIContext)2