Java Code Examples for org.apache.velocity.app.Velocity#mergeTemplate()

The following examples show how to use org.apache.velocity.app.Velocity#mergeTemplate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TransController.java    From das with Apache License 2.0 5 votes vote down vote up
private String mergeTemplate(Context context) {
    java.util.Properties property = new java.util.Properties();
    property.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogChute");
    property.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
    property.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(property);

    StringWriter writer = new StringWriter();
    Velocity.mergeTemplate("templates/convert/convert1.tpl", "UTF-8", context, writer);
    return  writer.toString();
}
 
Example 2
Source File: GenUtils.java    From dal with Apache License 2.0 5 votes vote down vote up
/**
 * 根据Velocity模板,生成相应的文件
 *
 * @param context VelocityHost
 * @param resultFilePath 生成的文件路径
 * @param templateFile Velocity模板文件
 * @return
 */
public static boolean mergeVelocityContext(VelocityContext context, String resultFilePath, String templateFile)
        throws Exception {
    FileWriter daoWriter = null;
    try {
        daoWriter = new FileWriter(resultFilePath);
        Velocity.mergeTemplate(templateFile, "UTF-8", context, daoWriter);
    } catch (Throwable e) {
        throw e;
    } finally {
        JavaIOUtils.closeWriter(daoWriter);
    }

    return true;
}
 
Example 3
Source File: GenUtils.java    From dal with Apache License 2.0 5 votes vote down vote up
/**
 * 根据Velocity模板,生成相应的文件
 *
 * @param context VelocityHost
 * @param templateFile Velocity模板文件
 * @return
 */
public static String mergeVelocityContext(VelocityContext context, String templateFile) throws Exception {
    Writer writer = null;
    try {
        writer = new StringWriter();
        Velocity.mergeTemplate(templateFile, "UTF-8", context, writer);
    } catch (Throwable e) {
        throw e;
    } finally {
        JavaIOUtils.closeWriter(writer);
    }

    return writer.toString();
}
 
Example 4
Source File: WebServer.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void showTasks(HttpServletRequest request, HttpServletResponse response, Collection<TaskRecord> tasks, String title, boolean showDbStats)
        throws IOException {
    if ("json".equals(request.getParameter("format"))) {
        response.setContentType("text/plain");
    } else {
        response.setContentType("text/html");
    }
    int offset = getOffset(request);
    int length = getLength(request);
    // Create Velocity context
    VelocityContext context = new VelocityContext();
    context.put("tasks", tasks);
    context.put("title", title);
    context.put("reportStore", metadata);
    context.put("request", request);
    context.put("offset", offset);
    context.put("length", length);
    context.put("lastResultNum", offset + length - 1);
    context.put("prevOffset", Math.max(0, offset - length));
    context.put("nextOffset", offset + length);
    context.put("showStats", showDbStats);
    context.put("JSON_DATE_FORMAT", JSON_DATE_FORMAT);
    context.put("HTML_DATE_FORMAT", HTML_DATE_FORMAT);
    context.put("PAGE_LENGTH", PAGE_LENGTH);
    // Return Velocity results
    try {
        Velocity.mergeTemplate("tasks.vm", "UTF-8", context, response.getWriter());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        LOG.warn("Failed to display tasks.vm", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to display tasks.vm");
    }
}
 
Example 5
Source File: TemplateService.java    From oxTrust with MIT License 5 votes vote down vote up
public String generateConfFile(String template, VelocityContext context) {
	StringWriter sw = new StringWriter();
	try {
		Velocity.mergeTemplate(template + ".vm", "UTF-8", context, sw);
	} catch (Exception ex) {
		log.error("Failed to load velocity template '{}'", template, ex);
		return null;
	}

	return sw.toString();
}
 
Example 6
Source File: VelocityUtil.java    From easy-httpserver with Apache License 2.0 5 votes vote down vote up
/**
 * 渲染Velocity模板
 * @param path
 * @param map
 */
public static String mergeTemplate(String path, Map<String, Object> map) throws IOException {
	VelocityContext vc = new VelocityContext();
	if (null != map) {
		for (String key : map.keySet()) {
			vc.put(key, map.get(key));
		}
	}
	StringWriter w = new StringWriter();
	Velocity.mergeTemplate(path, "utf-8", vc, w);
	String content = w.toString();
	w.close();
	return content;
}
 
Example 7
Source File: GenerateLogMessages.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
/**
 * This is the main method that generates the _Messages.java file.
 * The class is generated by extracting the list of messges from the
 * available LogMessages Resource.
 *
 * The extraction is done based on typeIdentifier which is a 3-digit prefix
 * on the messages e.g. BRK for Broker.
 *
 * @throws InvalidTypeException when an unknown parameter type is used in the properties file
 * @throws Exception            thrown by velocity if there is an error
 */
private void createMessageClass(String file)
        throws InvalidTypeException, Exception
{
    VelocityContext context = new VelocityContext();

    String bundle = file.replace(File.separator, ".");

    int packageStartIndex = bundle.indexOf(_packageSource) + _packageSource.length() + 2;

    bundle = bundle.substring(packageStartIndex, bundle.indexOf(".properties"));

    System.out.println("Creating Class for bundle:" + bundle);

    ResourceBundle fileBundle = ResourceBundle.getBundle(bundle, Locale.US);

    // Pull the bit from /os/path/<className>.logMessages from the bundle name
    String className = file.substring(file.lastIndexOf(File.separator) + 1, file.lastIndexOf("_"));
    debug("Creating ClassName form file:" + className);

    String packageString = bundle.substring(0, bundle.indexOf(className));
    String packagePath = packageString.replace(".", File.separator);

    debug("Package path:" + packagePath);

    File outputDirectory = new File(_outputDir + File.separator + packagePath);
    if (!outputDirectory.exists())
    {
        if (!outputDirectory.mkdirs())
        {
            throw new IllegalAccessException("Unable to create package structure:" + outputDirectory);
        }
    }

    // Get the Data for this class and typeIdentifier
    HashMap<String, Object> typeData = prepareType(className, fileBundle);

    context.put("package", packageString.substring(0, packageString.lastIndexOf('.')));
    //Store the resource Bundle name for the macro
    context.put("resource", bundle);

    // Store this data in the context for the macro to access
    context.put("type", typeData);

    // Create the file writer to put the finished file in
    String outputFile = _outputDir + File.separator + packagePath + className + "Messages.java";
    debug("Creating Java file:" + outputFile);
    FileWriter output = new FileWriter(outputFile);

    // Run Velocity to create the output file.
    // Fix the default file encoding to 'ISO-8859-1' rather than let
    // Velocity fix it. This is the encoding format for the macro.
    Velocity.mergeTemplate("LogMessages.vm", "ISO-8859-1", context, output);

    //Close our file.
    output.flush();
    output.close();
}