Java Code Examples for freemarker.template.Configuration#setClassForTemplateLoading()

The following examples show how to use freemarker.template.Configuration#setClassForTemplateLoading() . 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: FreemarkerUtils.java    From swagger-coverage with Apache License 2.0 6 votes vote down vote up
public static String processTemplate(final String path, String locale, final Object object) {
    final Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);

    configuration.setClassForTemplateLoading(FreemarkerUtils.class, "/");
    configuration.setDefaultEncoding("UTF-8");

    Map<String, String> messages = readMessages(locale);

    try {
        final Map<String, Object> data = new HashMap<>();
        data.put("data", object);
        data.put("messages", messages);

        final Writer writer = new StringWriter();
        final Template template = configuration.getTemplate(path);
        template.process(data, writer);
        return writer.toString();
    } catch (IOException | TemplateException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: JiraContentFormatter.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private String buildDescription(String jiraTemplate, Map<String, Object> templateValues) {
  String description;

  // Render the values in templateValues map to the jira ftl template file
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try (Writer out = new OutputStreamWriter(baos, CHARSET)) {
    Configuration freemarkerConfig = new Configuration(Configuration.VERSION_2_3_21);
    freemarkerConfig.setClassForTemplateLoading(getClass(), "/org/apache/pinot/thirdeye/detector");
    freemarkerConfig.setDefaultEncoding(CHARSET);
    freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    Template template = freemarkerConfig.getTemplate(jiraTemplate);
    template.process(templateValues, out);

    description = new String(baos.toByteArray(), CHARSET);
  } catch (Exception e) {
    description = "Found an exception while constructing the description content. Pls report & reach out"
        + " to the Thirdeye team. Exception = " + e.getMessage();
  }

  return description;
}
 
Example 3
Source File: AbstractGeneratorStrategy.java    From sloth with Apache License 2.0 6 votes vote down vote up
/**
 * base freemarker genarate method
 * @param templateData
 * @param templateFileRelativeDir
 * @param templateFileName
 * @param targetFileAbsoluteDir
 * @param targetFileName
 */
private void gen(Object templateData, String templateFileRelativeDir, String templateFileName, String targetFileAbsoluteDir, String targetFileName){
    try{
        Configuration configuration = new Configuration();
        configuration.setClassForTemplateLoading(Application.class, templateFileRelativeDir);
        configuration.setObjectWrapper(new DefaultObjectWrapper());
        Template template = configuration.getTemplate(templateFileName);
        template.setEncoding(encoding);
        if(!targetFileAbsoluteDir.endsWith(File.separator))
            targetFileAbsoluteDir+=File.separator;
        FileUtil.mkdir(targetFileAbsoluteDir);
        Writer fw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(targetFileAbsoluteDir + targetFileName)),encoding));
        template.process(templateData, fw);
    }catch (Throwable e){
        logger.error("Can not found the template file, path is \"" + templateFileRelativeDir + templateFileName +".\"");
        e.printStackTrace();
        throw new RuntimeException("IOException occur , please check !! ");
    }
}
 
Example 4
Source File: FreemarkerProcessor.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * Configuration initialization
 * @param resourceLoaderClass class for loading resources
 * @param templatePath template path
 */
public FreemarkerProcessor(Class<?> resourceLoaderClass, String templatePath)
{
    configuration = new Configuration(Configuration.VERSION_2_3_30);
    configuration.setClassForTemplateLoading(resourceLoaderClass, templatePath);
    configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
 
Example 5
Source File: BootFactory.java    From hub-detect with Apache License 2.0 5 votes vote down vote up
public Configuration createConfiguration() {
    final Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
    configuration.setClassForTemplateLoading(Application.class, "/");
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLogTemplateExceptions(true);

    return configuration;
}
 
Example 6
Source File: KurentoJsBase.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  try {
    final String outputFolder =
        new ClassPathResource("static").getFile().getAbsolutePath() + File.separator;

    Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    cfg.setClassForTemplateLoading(KurentoJsBase.class, "/templates/");
    Template template = cfg.getTemplate("kurento-client.html.ftl");

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("kurentoUrl", kurentoUrl);

    for (String lib : kurentoLibs) {
      Writer writer = new FileWriter(new File(outputFolder + lib + ".html"));
      data.put("kurentoLib", lib);

      if (lib.contains("utils")) {
        data.put("kurentoObject", "kurentoUtils");
      } else {
        data.put("kurentoObject", "kurentoClient");
      }

      template.process(data, writer);
      writer.flush();
      writer.close();
    }
  } catch (Exception e) {
    Assert.fail("Exception creating templates: " + e.getMessage());
  }

}
 
Example 7
Source File: Freemarker.java    From aws-scala-sdk with Apache License 2.0 5 votes vote down vote up
public Freemarker() {
    Configuration config = new Configuration(Configuration.VERSION_2_3_21);

    config.setClassForTemplateLoading(Freemarker.class, "/templates");
    config.setDefaultEncoding("UTF-8");

    CONFIGURATION = config;
}
 
Example 8
Source File: FreeMarkerUtil.java    From game-server with MIT License 5 votes vote down vote up
public static Template getTemplate(Class<?> clazz,String name,String ftlPath) {
	try {
		// 通过Freemaker的Configuration读取相应的ftl
		Configuration cfg = new Configuration(new Version(2, 3, 23));
		// 设定去哪里读取相应的ftl模板文件
		cfg.setClassForTemplateLoading(FreeMarkerUtil.class, ftlPath);
		// 在模板文件目录中找到名称为name的文件
		Template temp = cfg.getTemplate(name);
		return temp;
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 9
Source File: Environment.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
private Environment() {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    // Specify the data source where the template files come from.
    cfg.setClassForTemplateLoading(getClass(), "/templates/");
    DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23);
    builder.setExposeFields(true);
    cfg.setObjectWrapper(builder.build());
    freemarkerConfig = cfg;

    fmHelper = new FreeMarkerHelper();
    templateCache = new ConcurrentHashMap<String, Template>();

    symbols = new ConcurrentHashMap<String, String>();

    textFormatter = new TextFormatter();

    xmlFormatter = new XMLFormatter();
    nsContext = new NamespaceContextImpl();
    fillNamespaceContext();
    xPathHelper = new XPathHelper();

    jsonPathHelper = new JsonPathHelper();
    jsonHelper = new JsonHelper();

    htmlCleaner = new HtmlCleaner();

    httpClient = new HttpClient();

    programHelper = new ProgramHelper();
    programHelper.setTimeoutHelper(timeoutHelper);
    configDatesHelper();

    driverManager = new DriverManager();
    cookieConverter = new CookieConverter();
}
 
Example 10
Source File: AbstractHalProcessor.java    From core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AbstractHalProcessor() {

        Version version = new Version(2, 3, 22);
        config = new Configuration(version);
        config.setDefaultEncoding("UTF-8");
        config.setClassForTemplateLoading(getClass(), "templates");
        config.setObjectWrapper(new DefaultObjectWrapperBuilder(version).build());
    }
 
Example 11
Source File: DefaultHtmlEmitter.java    From zserio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void initConfig()
{
    if (cfg != null)
        return;

    Configuration config = new Configuration(Configuration.VERSION_2_3_28);
    config.setClassForTemplateLoading(DefaultHtmlEmitter.class, "/freemarker/");

    cfg = config;
}
 
Example 12
Source File: TemplateProcessor.java    From core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void process(String name, Map<String, Object> model, OutputStream output) {

        try {
            Configuration config = new Configuration();
            config.setClassForTemplateLoading(getClass(), "");
            config.setObjectWrapper(new DefaultObjectWrapper());

            Template templateEngine = config.getTemplate(name);
            templateEngine.process(model, new PrintWriter(output));

        } catch (Throwable t) {
            throw new RuntimeException("Error processing template: " + t.getClass().getName(), t);
        }
    }
 
Example 13
Source File: Templates.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private static Configuration createConfiguration() {
  Configuration configuration = new Configuration(Configuration.VERSION_2_3_25);
  configuration.setClassForTemplateLoading(Templates.class, "/templates/appengine");
  configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
  configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  configuration.setLogTemplateExceptions(false);
  return configuration;
}
 
Example 14
Source File: CodeGeneratorUtil.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private static void generatorProcess(String packageName, String headName, String templateFilePath) throws Exception {
	Configuration cfg = new Configuration( Configuration.VERSION_2_3_21 );
	cfg.setClassForTemplateLoading(CodeGeneratorUtil.class, "");
	Template template = cfg.getTemplate(templateFilePath, "utf-8");
	Map<String, Object> params = new HashMap<String, Object>();
	params.put("packageName", packageName);
	params.put("headName", headName);
	params.put("headNameSmall", headName.substring(0, 1).toLowerCase() + headName.substring(1, headName.length()));
	String outDir = System.getProperty("user.dir") + "/out";
	String outFilePath = outDir + "/" + getOutFileFootName(headName, templateFilePath);
	Writer file = new FileWriter (new File(outFilePath));
	template.process(params, file);
	file.flush();
	file.close();
}
 
Example 15
Source File: KmsService.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void createKurentoConf() {
  Map<String, Object> data = new HashMap<String, Object>();
  try {
    URI wsAsUri = new URI(wsUri);
    int port = wsAsUri.getPort();
    String path = wsAsUri.getPath();
    data.put("wsPort", String.valueOf(port));
    data.put("wsPath", path.substring(1));
    data.put("registrar", registrarUri);
    data.put("registrarLocalAddress", registrarLocalAddress);

  } catch (URISyntaxException e) {
    throw new KurentoException("Invalid ws uri: " + wsUri);
  }
  data.put("gstPlugins", getGstPlugins());
  data.put("debugOptions", getDebugOptions());
  data.put("serverCommand", getServerCommand());
  data.put("workspace", getKmsLogPath());

  Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
  cfg.setClassForTemplateLoading(this.getClass(), "/templates/");

  createFileFromTemplate(cfg, data, "kurento.conf.json");
  createFileFromTemplate(cfg, data, "kurento.sh");

  Shell.runAndWait("chmod", "+x", workspace + File.separator + "kurento.sh");
}
 
Example 16
Source File: TemplateConfiguration.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
private static Configuration createConfiguration() {
    final Configuration cfg = new Configuration(Configuration.getVersion());
    cfg.setClassForTemplateLoading(TemplateConfiguration.class, "/megamek/common/templates");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    cfg.setWrapUncheckedExceptions(true);
    return cfg;
}
 
Example 17
Source File: Template.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a freemarker template based on some parameters
 */
public void toFile() {
    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(classContext, "/");
    try {
        freemarker.template.Template template = configuration.getTemplate(name);
        Writer file = new FileWriter(new File(outputFile));
        template.process(data, file);
        file.flush();
        file.close();

    } catch (Exception e) {

    }
}
 
Example 18
Source File: IDLReader.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void init(
        Document iddDoc,
        Document extensionDoc,
        final String service,
        String packageName,
        final String basedir,
        final String genSrcDir,
        final Log log,
        final String outputDir,
        boolean client,
        boolean server)
        throws Exception {

    try {
        output = new File(basedir, genSrcDir);
        if (outputDir != null) {
            iDDOutputDir = new File(basedir+"/"+outputDir);
            if (!iDDOutputDir.exists()) {
                if (!iDDOutputDir.mkdirs()) {
                    throw new IllegalArgumentException("IDD Output Directory "+iDDOutputDir+" could not be created");
                }
            }
            if (!iDDOutputDir.isDirectory() || (!iDDOutputDir.canWrite())) {
                throw new IllegalArgumentException("IDD Output Directory "+iDDOutputDir+" is not a directory or cannot be written to.");
            }
        }
        config = new Configuration();
        config.setClassForTemplateLoading(IDLReader.class, "/templates");

        config.setStrictSyntaxMode(true);
        this.log = log;
        this.packageName = packageName;
        this.service = service;
        this.client = client;
        this.server = server || !client; // server must be true if client if false.

        dataModel = NodeModel.wrap(iddDoc.cloneNode(true));

        if (extensionDoc != null) {
            NodeModel extensionModel = NodeModel.wrap(extensionDoc);
            mergeExtensionsIntoDocument(getRootNode(dataModel),
                    getRootNode(extensionModel));
            removeUndefinedOperations(getRootNode(dataModel),
                    getRootNode(extensionModel));
        }
        if(log.isDebugEnabled()) {
            log.debug(serialize());
        }
    } catch (final Exception e) {
        log.error("Failed to initialise FTL", e);
        throw e;
    }
}
 
Example 19
Source File: FreemarkerTemplateEngine.java    From pippo with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Application application) {
    super.init(application);

    Router router = getRouter();
    PippoSettings pippoSettings = getPippoSettings();

    configuration = new Configuration(Configuration.VERSION_2_3_21);
    configuration.setDefaultEncoding(PippoConstants.UTF8);
    configuration.setOutputEncoding(PippoConstants.UTF8);
    configuration.setLocalizedLookup(true);
    configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, getTemplatePathPrefix());

    // We also do not want Freemarker to chose a platform dependent
    // number formatting. Eg "1000" could be printed out by FTL as "1,000"
    // on some platforms.
    // See also:
    // http://freemarker.sourceforge.net/docs/app_faq.html#faq_number_grouping
    configuration.setNumberFormat("0.######"); // now it will print 1000000

    if (pippoSettings.isDev()) {
        configuration.setTemplateUpdateDelayMilliseconds(0); // disable cache
    } else {
        // never update the templates in production or while testing...
        configuration.setTemplateUpdateDelayMilliseconds(Integer.MAX_VALUE);

        // Hold 20 templates as strong references as recommended by:
        // http://freemarker.sourceforge.net/docs/pgui_config_templateloading.html
        configuration.setCacheStorage(new freemarker.cache.MruCacheStorage(20, Integer.MAX_VALUE));
    }

    // set global template variables
    configuration.setSharedVariable("contextPath", new SimpleScalar(router.getContextPath()));
    configuration.setSharedVariable("appPath", new SimpleScalar(router.getApplicationPath()));

    webjarResourcesMethod = new WebjarsAtMethod(router);
    publicResourcesMethod = new PublicAtMethod(router);

    // allow custom initialization
    init(application, configuration);
}
 
Example 20
Source File: FreeMarkerEngine.java    From spark-template-engines with Apache License 2.0 4 votes vote down vote up
private Configuration createDefaultConfiguration() {
    Configuration configuration = new Configuration(new Version(2, 3, 23));
    configuration.setClassForTemplateLoading(FreeMarkerEngine.class, "");
    return configuration;
}