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

The following examples show how to use freemarker.template.Configuration#setTemplateExceptionHandler() . 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: FreemarkerTemplateEngineFactory.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
    configuration.setDefaultEncoding("utf-8");
    configuration.setLogTemplateExceptions(true);
    configuration.setNumberFormat("computer");
    configuration.setOutputFormat(XHTMLOutputFormat.INSTANCE);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setTemplateLoader(new SpringTemplateLoader(this.resourceLoader, this.resourceLoaderPath));

    if (this.shouldCheckForTemplateModifications) {
        configuration.setTemplateUpdateDelayMilliseconds(1000);
    } else {
        configuration.setTemplateUpdateDelayMilliseconds(Long.MAX_VALUE);
    }

    this.configuration = configuration;
}
 
Example 2
Source File: CodeRenderer.java    From jpa-entity-generator with MIT License 6 votes vote down vote up
/**
 * Renders source code by using Freemarker template engine.
 */
public static String render(String templatePath, RenderingData data) throws IOException, TemplateException {
    Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    String source;
    try (InputStream is = ResourceReader.getResourceAsStream(templatePath);
         BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
        source = buffer.lines().collect(Collectors.joining("\n"));
    }
    templateLoader.putTemplate("template", source);
    config.setTemplateLoader(templateLoader);
    config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    config.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
    config.setWhitespaceStripping(true);

    try (Writer writer = new java.io.StringWriter()) {
        Template template = config.getTemplate("template");
        template.process(data, writer);
        return writer.toString();
    }
}
 
Example 3
Source File: Freemarker.java    From freeacs with MIT License 6 votes vote down vote up
/**
 * Inits the freemarker.
 *
 * @return the configuration
 */
public static Configuration initFreemarker() {
  try {
    Configuration config = new Configuration();
    config.setTemplateLoader(new ClassTemplateLoader(Freemarker.class, "/templates"));
    config.setTemplateUpdateDelay(0);
    config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
    config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
    config.setDefaultEncoding("ISO-8859-1");
    config.setOutputEncoding("ISO-8859-1");
    config.setNumberFormat("0");
    config.setSetting("url_escaping_charset", "ISO-8859-1");
    config.setLocale(Locale.ENGLISH);
    setAutoImport(config);
    setSharedVariables(config);
    return config;
  } catch (Throwable e) {
    throw new RuntimeException("Could not initialise Freemarker configuration", e);
  }
}
 
Example 4
Source File: FreemarkerEngine.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance of {@link FreemarkerEngine}.
 * @param backend the backend name
 * @param directives custom directives to register
 * @param model some model attributes to set for each rendering invocation
 */
public FreemarkerEngine(String backend,
                        Map<String, String> directives,
                        Map<String, String> model) {
    checkNonNullNonEmpty(backend, BACKEND_PROP);
    this.backend = backend;
    this.directives = directives == null ? Collections.emptyMap() : directives;
    this.model = model == null ? Collections.emptyMap() : model;
    freemarker = new Configuration(FREEMARKER_VERSION);
    freemarker.setTemplateLoader(new TemplateLoader());
    freemarker.setDefaultEncoding(DEFAULT_ENCODING);
    freemarker.setObjectWrapper(OBJECT_WRAPPER);
    freemarker.setTemplateExceptionHandler(
            TemplateExceptionHandler.RETHROW_HANDLER);
    freemarker.setLogTemplateExceptions(false);
}
 
Example 5
Source File: ScriptUtils.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** @return script variables */
public static Set<String> getScriptVariables(Script script) {
  // based on https://stackoverflow.com/a/48024379
  Set<String> scriptExpressions = new LinkedHashSet<>();
  Configuration configuration = new Configuration(VERSION);
  configuration.setTemplateExceptionHandler(
      (te, env, out) -> {
        if (te instanceof InvalidReferenceException) {
          scriptExpressions.add(te.getBlamedExpressionString());
          return;
        }
        throw te;
      });

  try {
    Template template = new Template(null, new StringReader(script.getContent()), configuration);
    template.process(emptyMap(), new StringWriter());
  } catch (TemplateException | IOException e) {
    throw new GenerateScriptException(
        "Error processing parameters for script [" + script.getName() + "]. " + e.getMessage());
  }
  return scriptExpressions;
}
 
Example 6
Source File: FreemarkerRenderer.java    From act with GNU General Public License v3.0 6 votes vote down vote up
private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection) throws IOException {
  cfg = new Configuration(Configuration.VERSION_2_3_23);

  cfg.setClassLoaderForTemplateLoading(
      this.getClass().getClassLoader(), "/act/installer/reachablesexplorer/templates");
  cfg.setDefaultEncoding("UTF-8");

  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setLogTemplateExceptions(true);

  reachableTemplate = cfg.getTemplate(reachableTemplateName);
  pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

  // TODO: move this elsewhere.
  MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
  DB db = client.getDB(dbName);

  dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class, String.class);
  Cascade.setCollectionName(pathwayCollection);
}
 
Example 7
Source File: FreeMarkerViewResolver.java    From ask-sdk-frameworks-java with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a default config for FreeMarker which reads templates from the classpath under the path specified in the prefix
 * a prefix is specified.
 *
 * @param configuration free marker config
 * @param resourceClass class to load resources relative to
 * @return supplied configuration if not nul, otherwise a default one
 */
protected Configuration buildDefaultConfig(Configuration configuration, Class<?> resourceClass) {
    if (configuration != null) {
        return configuration;
    }
    Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    cfg.setClassForTemplateLoading(resourceClass == null ? getClass() : resourceClass, "/");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(true);
    cfg.setCacheStorage(NullCacheStorage.INSTANCE);
    return cfg;
}
 
Example 8
Source File: WelcomePage.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 创建 Configuration 实例.
 *
 * @return
 * @throws IOException
 */
private Configuration config(String ftlDir) throws IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    cfg.setDirectoryForTemplateLoading(new File(ftlDir));
    cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    return cfg;
}
 
Example 9
Source File: FreemarkerServiceImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
private Configuration createConfiguration(String id) throws IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    File dir = new File(_conf.getConf(id, FtlPropsConf.P_ftl_dir));
    dir.mkdirs();
    cfg.setDirectoryForTemplateLoading(dir);
    cfg.setDefaultEncoding(_conf.getConf(id, FtlPropsConf.P_ftl_encoding, "UTF-8"));
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    return cfg;
}
 
Example 10
Source File: HtmlTriplePatternFragmentWriterImpl.java    From Server.Java with MIT License 5 votes vote down vote up
/**
 *
 * @param prefixes
 * @param datasources
 * @throws IOException
 */
public HtmlTriplePatternFragmentWriterImpl(Map<String, String> prefixes, HashMap<String, IDataSource> datasources) throws IOException {
    super(prefixes, datasources);
    
    cfg = new Configuration(Configuration.VERSION_2_3_22);
    cfg.setClassForTemplateLoading(getClass(), "/views");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    
    indexTemplate = cfg.getTemplate("index.ftl.html");
    datasourceTemplate = cfg.getTemplate("datasource.ftl.html");
    notfoundTemplate = cfg.getTemplate("notfound.ftl.html");
    errorTemplate = cfg.getTemplate("error.ftl.html");
}
 
Example 11
Source File: GatekeeperConfig.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Bean
public Configuration freemarkerConfig() {
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_29);
    configuration.setClassForTemplateLoading(EmailService.class, "/emails");
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    return configuration;
}
 
Example 12
Source File: MagicWebSiteGenerator.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public MagicWebSiteGenerator(String template, String dest) throws IOException {
	cfg = new Configuration(MTGConstants.FREEMARKER_VERSION);
	cfg.setDirectoryForTemplateLoading(new File(MTGConstants.MTG_TEMPLATES_DIR, template));
	cfg.setDefaultEncoding(MTGConstants.DEFAULT_ENCODING.displayName());
	cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	cfg.setObjectWrapper(new DefaultObjectWrapperBuilder(MTGConstants.FREEMARKER_VERSION).build());

	this.dest = dest;
	FileUtils.copyDirectory(new File(MTGConstants.MTG_TEMPLATES_DIR, template), new File(dest), pathname -> {
		if (pathname.isDirectory())
			return true;

		return !pathname.getName().endsWith(".html");
	});
}
 
Example 13
Source File: TelegramNotificator.java    From teamcity-telegram-plugin with Apache License 2.0 5 votes vote down vote up
private Configuration createFreeMarkerConfig(@NotNull Path configDir) throws IOException {
  Configuration cfg = new Configuration();
  cfg.setDefaultEncoding("UTF-8");
  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setDirectoryForTemplateLoading(configDir.toFile());
  cfg.setTemplateUpdateDelay(TeamCityProperties.getInteger(
      "teamcity.notification.template.update.interval", 60));
  return cfg;
}
 
Example 14
Source File: FreemarkerTransformer.java    From tutorials with MIT License 5 votes vote down vote up
public String html() throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
    cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
    cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    cfg.setWrapUncheckedExceptions(true);
    cfg.setFallbackOnNullLoopVariable(false);
    Template temp = cfg.getTemplate(templateFile);
    try (Writer output = new StringWriter()) {
        temp.process(staxTransformer.getMap(), output);
        return output.toString();
    }
}
 
Example 15
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 16
Source File: PreprocessorImpl.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
public PreprocessorImpl() {
    cfg = new Configuration(VERSION);
    cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    cfg.setWrapUncheckedExceptions(true);
    cfg.setFallbackOnNullLoopVariable(false);
}
 
Example 17
Source File: FreemarkerConfigurationBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public Configuration build() {
	Configuration configuration = getConfiguration();
	String defaultEncoding = defaultEncodingValueBuilder.getValue();
	if (defaultEncoding != null) {
		configuration.setDefaultEncoding(defaultEncoding);
	}
	if (templateExceptionHandler != null) {
		configuration.setTemplateExceptionHandler(templateExceptionHandler);
	}
	buildSharedVariables(configuration);
	buildStaticMethodAccess(configuration);
	return configuration;
}
 
Example 18
Source File: GeneratorHelper.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
private Template getTemplate(String templateName) throws Exception {
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
    String templatePath = GeneratorHelper.class.getResource("/generator/templates/").getPath();
    File file = new File(templatePath);
    if (!file.exists()) {
        templatePath = System.getProperties().getProperty(FebsConstant.JAVA_TEMP_DIR);
        file = new File(templatePath + File.separator + templateName);
        FileUtils.copyInputStreamToFile(Objects.requireNonNull(GeneratorHelper.class.getClassLoader().getResourceAsStream("classpath:generator/templates/" + templateName)), file);
    }
    configuration.setDirectoryForTemplateLoading(new File(templatePath));
    configuration.setDefaultEncoding(FebsConstant.UTF8);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
    return configuration.getTemplate(templateName);

}
 
Example 19
Source File: TrainModule.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * TrainModule
 */
public TrainModule() {
    String maxChartPointsProp = System.getProperty(DL4JSystemProperties.CHART_MAX_POINTS_PROPERTY);
    int value = DEFAULT_MAX_CHART_POINTS;
    if (maxChartPointsProp != null) {
        try {
            value = Integer.parseInt(maxChartPointsProp);
        } catch (NumberFormatException e) {
            log.warn("Invalid system property: {} = {}", DL4JSystemProperties.CHART_MAX_POINTS_PROPERTY, maxChartPointsProp);
        }
    }
    if (value >= 10) {
        maxChartPoints = value;
    } else {
        maxChartPoints = DEFAULT_MAX_CHART_POINTS;
    }

    configuration = new Configuration(new Version(2, 3, 23));
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    configuration.setClassForTemplateLoading(TrainModule.class, "");
    try {
        File dir = Resources.asFile("templates/TrainingOverview.html.ftl").getParentFile();
        configuration.setDirectoryForTemplateLoading(dir);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
 
Example 20
Source File: TimeStepRunnerCodeGenerator.java    From hazelcast-simulator with Apache License 2.0 4 votes vote down vote up
private JavaFileObject createJavaFileObject(
        String className,
        String executionGroup,
        Class<? extends Metronome> metronomeClass,
        TimeStepModel timeStepModel,
        Class<? extends Probe> probeClass,
        long logFrequency,
        long logRateMs,
        boolean hasIterationCap) {
    try {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);
        cfg.setClassForTemplateLoading(this.getClass(), "/");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);

        Map<String, Object> root = new HashMap<>();
        root.put("testInstanceClass", getClassName(timeStepModel.getTestClass()));
        root.put("metronomeClass", getMetronomeClass(metronomeClass));
        root.put("timeStepMethods", timeStepModel.getActiveTimeStepMethods(executionGroup));
        root.put("probeClass", getClassName(probeClass));
        root.put("isStartNanos", new IsStartNanos(timeStepModel));
        root.put("isAssignableFrom", new IsAssignableFromMethod());
        root.put("isAsyncResult", new IsAsyncResult());
        root.put("Probe", Probe.class);
        root.put("threadStateClass", getClassName(timeStepModel.getThreadStateClass(executionGroup)));
        root.put("hasProbe", new HasProbeMethod());
        root.put("className", className);
        if (logFrequency > 0) {
            root.put("logFrequency", "" + logFrequency);
        }

        if (logRateMs > 0) {
            root.put("logRateMs", "" + logRateMs);
        }

        if (hasIterationCap) {
            root.put("hasIterationCap", "true");
        }

        Template temp = cfg.getTemplate("TimeStepRunner.ftl");
        StringWriter out = new StringWriter();
        temp.process(root, out);

        String javaCode = out.toString();
        File javaFile = new File(targetDirectory, className + ".java");

        writeText(javaCode, javaFile);

        return new JavaSourceFromString(className, javaCode);
    } catch (Exception e) {
        throw new IllegalTestException(className + " ran into a code generation problem: " + e.getMessage(), e);
    }
}