public void buildToOutputStream(Class<?> commonServiceClass, OutputStream os) throws Exception { Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setClassForTemplateLoading(ThriftFileBuilder.class, "/"); Template template = cfg.getTemplate("templates/thrift/thrift.ftl"); Writer out = new OutputStreamWriter(os); ThriftServiceBuilder serviceBuilder = new ThriftServiceBuilder(commonServiceClass); ThriftService service = serviceBuilder.buildThriftService(); Map<String, Object> rootMap = new HashMap<String, Object>(); rootMap.put("thriftServicePackage", this.getPackageName(commonServiceClass)); List<ThriftStruct> structs = serviceBuilder.getStructs(); List<ThriftEnum> enums = serviceBuilder.getEnums(); CommonUtils.removeRepeat(structs); rootMap.put("structList", structs); rootMap.put("enumList", enums); CommonUtils.removeRepeat(enums); rootMap.put("serviceList", Arrays.asList(service)); template.process(rootMap, out); }
@Override protected Configuration getFreemarkerConfiguration(RepoCtx ctx) { if (useRemoteCallbacks) { // as per 3.0, 3.1 return super.getFreemarkerConfiguration(ctx); } else { Configuration cfg = new Configuration(); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setTemplateLoader(new ClassPathRepoTemplateLoader(nodeService, contentService, defaultEncoding)); // TODO review i18n cfg.setLocalizedLookup(false); cfg.setIncompatibleImprovements(new Version(2, 3, 20)); cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); return cfg; } }
private FreemarkerHelper buildFreemarkerHelper(File templateBaseDir) { Configuration configuration = new Configuration(new Version(2, 3, 0)); try { TemplateLoader templateLoader = new FileTemplateLoader(templateBaseDir); configuration.setTemplateLoader(templateLoader); } catch (IOException e) { throw new GeneratorException("构建模板助手出错:" + e.getMessage()); } configuration.setNumberFormat("###############"); configuration.setBooleanFormat("true,false"); configuration.setDefaultEncoding("UTF-8"); // 自动导入公共文件,用于支持灵活变量 if (autoIncludeFile.exists()) { List<String> autoIncludeList = new ArrayList<>(); autoIncludeList.add(FREEMARKER_AUTO_INCLUDE_SUFFIX); configuration.setAutoIncludes(autoIncludeList); } return new FreemarkerHelper(configuration); }
private static Configuration templateConfiguration() { Configuration configuration = new Configuration(Configuration.VERSION_2_3_26); configuration.setDefaultEncoding("UTF-8"); configuration.setLogTemplateExceptions(false); try { configuration.setSetting("object_wrapper", "DefaultObjectWrapper(2.3.26, forceLegacyNonListCollections=false, " + "iterableSupport=true, exposeFields=true)"); } catch (TemplateException e) { e.printStackTrace(); } configuration.setAPIBuiltinEnabled(true); configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "templates/ccda"); return configuration; }
public DaoGenerator() throws IOException { System.out.println("greenDAO Generator"); System.out.println("Copyright 2011-2016 Markus Junginger, greenrobot.de. Licensed under GPL V3."); System.out.println("This program comes with ABSOLUTELY NO WARRANTY"); patternKeepIncludes = compilePattern("INCLUDES"); patternKeepFields = compilePattern("FIELDS"); patternKeepMethods = compilePattern("METHODS"); Configuration config = getConfiguration("dao.ftl"); templateDao = config.getTemplate("dao.ftl"); templateDaoMaster = config.getTemplate("dao-master.ftl"); templateDaoSession = config.getTemplate("dao-session.ftl"); templateEntity = config.getTemplate("entity.ftl"); templateDaoUnitTest = config.getTemplate("dao-unit-test.ftl"); templateContentProvider = config.getTemplate("content-provider.ftl"); }
@PostConstruct public void initConfig() throws Exception { Configuration configuration = new Configuration(); File file = new File(servletContext.getRealPath("/WEB-INF/layouts")); configuration.setDirectoryForTemplateLoading(file); configuration.setDefaultEncoding("UTF-8"); this.template = configuration.getTemplate("email.template"); }
private static void runReport(Parameters params) { Map<String, TestCasesData> tests = loadTestCases( params ); Map<String, Vendor> results = loadTestResults( params, tests ); Map<String, List<TestCasesData>> labels = sortTestsByLabel( tests ); ReportHeader header = createReportHeader( tests, labels, results ); Map<String, ReportTable> tableByLabels = createTableByLabels( labels, results ); Map<String, ReportChart> chartByLabels = createChartByLabels( labels, results); Map<String, ReportChart> chartByLabelsPercent = createChartByLabelsPercent( labels, results); ReportTable tableAllTests = createTableAllTests( params, tests.values() ); Map<String, ReportTable> tableAllTestsByVendor = createTableAllTestsByVendor( params, tests.values(), results ); Map<String, List<ReportTable>> tableIndividualLabels = createTableByIndividualLabels( params, labels, results ); logger.info( "Generating report" ); Configuration cfg = createFreemarkerConfiguration(); IndexGenerator.generatePage( params, cfg, header, results ); for( Vendor vendor : results.values() ) { OverviewGenerator.generatePage( params, cfg, vendor, header, tableByLabels.get( vendor.getFileNameId() ), chartByLabels.get( vendor.getFileNameId() ), chartByLabelsPercent.get( vendor.getFileNameId() ) ); DetailGenerator.generatePage( params, cfg, vendor, header, tableAllTestsByVendor.get( vendor.getFileNameId() ), tableIndividualLabels.get( vendor.getFileNameId() ) ); } TestsGenerator.generatePage( params, cfg, header, tableAllTests ); GlossaryGenerator.generatePage( params, cfg, header ); }
private String generateResumeHTML(String json, String theme) throws Exception { if (!isValidJSON(json)) { throw new InvalidJSONException(); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); cfg.setDirectoryForTemplateLoading(new File("themes")); cfg.setDefaultEncoding("UTF-8"); Template temp = cfg.getTemplate(theme + ".html"); //System.out.println(json); Resume resume = gson.fromJson(json, Resume.class); resume.getRidOfArraysWithEmptyElements(); resume.setConfig(config); StringWriter htmlStringWriter = new StringWriter(); temp.process(resume, htmlStringWriter); String html = htmlStringWriter.toString(); return html; }
public static void main(String[] args) { Map<String,Object> tmp = new HashMap<>(); tmp.put("user","邢天宇"); Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); StringTemplateLoader loader = new StringTemplateLoader(); loader.putTemplate(NAME,"hello ${user}"); cfg.setTemplateLoader(loader); cfg.setDefaultEncoding("UTF-8"); try { Template template = cfg.getTemplate(NAME); StringWriter writer = new StringWriter(); template.process(tmp,writer); System.out.println(writer.toString()); } catch (Exception e) { e.printStackTrace(); } }
private static void writeToFile(IssuesReport report, Path toFile) { try { Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); cfg.setClassForTemplateLoading(HtmlReport.class, ""); Map<String, Object> root = new HashMap<>(); root.put("report", report); Template template = cfg.getTemplate("sonarlintreport.ftl"); try (FileOutputStream fos = new FileOutputStream(toFile.toFile()); Writer writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) { template.process(root, writer); writer.flush(); } } catch (Exception e) { throw new IllegalStateException("Fail to generate HTML Issues Report to: " + toFile, e); } }
/** * @param onTable */ public SchemaMaker(String tenant, String module, TenantOperation mode, String previousVersion, String rmbVersion){ if(SchemaMaker.cfg == null){ //do this ONLY ONCE SchemaMaker.cfg = new Configuration(new Version(2, 3, 26)); // Where do we load the templates from: cfg.setClassForTemplateLoading(SchemaMaker.class, "/templates/db_scripts"); cfg.setDefaultEncoding("UTF-8"); cfg.setLocale(Locale.US); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } this.tenant = tenant; this.module = module; this.mode = mode; this.previousVersion = previousVersion; this.rmbVersion = rmbVersion; }
public void init() throws IOException { ClassTemplateLoader ctl = new ClassTemplateLoader(Application.class, "/freemarker"); MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] {ctl}); Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); cfg.setTemplateLoader(mtl); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); Pair<String, Template> clusterResourceQuota = new ImmutablePair<String, Template>("ClusterResourceQuota-ForUser", cfg.getTemplate("ClusterResourceQuota-ForUser.ftlh")); Pair<String, Template> bestEffortResourceLimits = new ImmutablePair<String, Template>("LimitRange-BestEffortResourceLimits", cfg.getTemplate("LimitRange-BestEffortResourceLimits.ftlh")); Pair<String, Template> burstableResourceLimits = new ImmutablePair<String, Template>("LimitRange-BurstableResourceLimits", cfg.getTemplate("LimitRange-BurstableResourceLimits.ftlh")); Pair<String, Template> maxImageCounts = new ImmutablePair<String, Template>("LimitRange-MaxImageCounts", cfg.getTemplate("LimitRange-MaxImageCounts.ftlh")); Pair<String, Template> bestEffort = new ImmutablePair<String, Template>("ResourceQuota-BestEffort", cfg.getTemplate("ResourceQuota-BestEffort.ftlh")); Pair<String, Template> notTerminatingAndNotBestEffort = new ImmutablePair<String, Template>("ResourceQuota-NotTerminating-And-NotBestEffort", cfg.getTemplate("ResourceQuota-NotTerminating-And-NotBestEffort.ftlh")); Pair<String, Template> terminating = new ImmutablePair<String, Template>("ResourceQuota-Terminating", cfg.getTemplate("ResourceQuota-Terminating.ftlh")); templates = Arrays.asList(clusterResourceQuota, bestEffortResourceLimits, burstableResourceLimits, maxImageCounts, bestEffort, notTerminatingAndNotBestEffort, terminating); }
/** * Gets a Template instance from the template cache. If the Template instance isn't * found in the cache, then one will be created. * <p> * SCIPIO: 2017-02-21: May now pass cache null to bypass caching. */ public static Template getTemplate(String templateLocation, UtilCache<String, Template> cache, Configuration config) throws TemplateException, IOException { Template template = (cache != null) ? cache.get(templateLocation) : null; if (template == null) { // only make the reader if we need it, and then close it right after! Reader templateReader = makeReader(templateLocation); try { template = new Template(templateLocation, templateReader, config); } finally { // SCIPIO: added finally templateReader.close(); } if (cache != null) { template = cache.putIfAbsentAndGet(templateLocation, template); } } return template; }
/** * SCIPIO: Gets template from string out of custom cache (new). * 2017-02-21: May now pass cache null to bypass caching. */ public static Template getTemplateFromString(String templateString, String templateKey, String templateName, UtilCache<String, Template> cache, Configuration config) throws TemplateException, IOException { Template template = (cache != null) ? cache.get(templateKey) : null; if (template == null) { Reader templateReader = new StringReader(templateString); try { template = new Template(templateName, templateReader, config); } finally { templateReader.close(); } if (cache != null) { template = cache.putIfAbsentAndGet(templateKey, template); } } return template; }
/** * Returns a FreeMarker template from a representation and a configuration. * * @param config * The FreeMarker configuration. * @param templateRepresentation * The template representation. * @return The template or null if not found. */ public static Template getTemplate(Configuration config, Representation templateRepresentation) { try { // Instantiate the template with the character set of the template // representation if it has been set, otherwise use UTF-8. if (templateRepresentation.getCharacterSet() != null) { return new Template("template", templateRepresentation.getReader(), config, templateRepresentation.getCharacterSet().getName()); } return new Template("template", templateRepresentation.getReader(), config, CharacterSet.UTF_8.getName()); } catch (IOException e) { Context.getCurrentLogger().warn( "Unable to get the template from the representation " + templateRepresentation.getLocationRef(), e); return null; } }
/** * Tries to get appropriate location-based UtilCache in use for templates being rendered. * <p> * FIXME: WARNING: massive limitations here, we do not have access to all the Configuration instances * we'd need to test to implement this, and a host of problems... * as a result I am creating a new two-layer cache system that first keys on the Configuration instances. */ public static UtilCache<String, Template> getTemplateLocationCacheForConfig(Configuration config, Environment env) throws TemplateModelException { Map<Configuration, UtilCache<String, Template>> configTmplLocCaches = TemplateSource.configTmplLocCaches; UtilCache<String, Template> cache = configTmplLocCaches.get(config); if (cache == null) { // double-locking idiom, with configTmplLocCaches as unmodifiable synchronized(TemplateSource.class) { configTmplLocCaches = TemplateSource.configTmplLocCaches; cache = configTmplLocCaches.get(config); if (cache == null) { Map<Configuration, UtilCache<String, Template>> newConfigCacheMap = new HashMap<>(configTmplLocCaches); cache = UtilCache.createUtilCache("templatesource.ftl.location." + (configTmplLocCaches.size() + 1), 0, configTmplCacheExpireTime, false); newConfigCacheMap.put(config, cache); TemplateSource.configTmplLocCaches = newConfigCacheMap; } } } return cache; }
protected void generatePath(Map<String, Object> data, CodeTemplateEntity codeTemplate) throws NotificationException { try { @SuppressWarnings("deprecation") Template codeTemplateTargetPath = new Template("codeTemplateTargetPath", new StringReader(codeTemplate.getTargetPath()), new Configuration()); StringWriter output = new StringWriter(); codeTemplateTargetPath.process(data, output); codeTemplate.setConcreteTargetPath(output.toString()); @SuppressWarnings("deprecation") Template codeTemplateTemplatePath = new Template("codeTemplateTemplatePath", new StringReader(codeTemplate.getTemplatePath()), new Configuration()); output = new StringWriter(); codeTemplateTemplatePath.process(data, output); codeTemplate.setConcreteTemplatePath(output.toString()); } catch (IOException | TemplateException e) { LOG.error("Error during file writing: ", e); ResponseMetadata errorResponse = new ResponseMetadata(ResponseCode.ERROR, "error.generation.generatepath"); throw new NotificationException(errorResponse); } }
/** * 根据根路径的类,获取配置文件 * @author nan.li * @param paramClass * @param prefix * @return */ public static Configuration getConfigurationByClass(Class<?> paramClass, String prefix) { try { Configuration configuration = new Configuration(Configuration.VERSION_2_3_25); configuration.setClassForTemplateLoading(paramClass, prefix); //等价于下面这种方法 // configuration.setTemplateLoader( new ClassTemplateLoader(paramClass,prefix)); configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_25)); configuration.setDefaultEncoding(CharEncoding.UTF_8); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25).build()); return configuration; } catch (Exception e) { e.printStackTrace(); } return null; }
protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() throws Exception { FreemarkerEndpoint endpoint = new FreemarkerEndpoint(); endpoint.setCamelContext(context); endpoint.setResourceUri("org/apache/camel/component/freemarker/example.ftl"); Configuration configuraiton = new Configuration(); configuraiton.setTemplateLoader(new ClassTemplateLoader(Resource.class, "/")); endpoint.setConfiguration(configuraiton); context.addEndpoint("free", endpoint); from("direct:a").to("free"); } }; }
public void render(String modelType) throws IOException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setClassLoaderForTemplateLoading(SimpleModel.class.getClassLoader(), "/"); if (!outDir.getParentFile().exists()) outDir.getParentFile().mkdirs(); String modelTypeName = modelType.substring(0, 1).toUpperCase() + modelType.substring(1); Map<String, Object> params = new HashMap<String, Object>(); params.put("packageName", packageName); params.put("models", models); writeFile(packageName, modelTypeName, getTemplate(cfg, modelType), params); for (SimpleModel model : models) { if (model.isRender()) { params = new HashMap<>(); params.put("model", model); writeFile(model.getPackageName(), model.getName(), getModelTemplate(cfg), params); } } }
protected static String __processTemplate(TemplateLoader templateLoader, String templateName, Map<String, ?> parameterValues) { Map<String, Object> params = prepareParams(parameterValues); final StringWriter writer = new StringWriter(); try { final Configuration configuration = new Configuration(); configuration.setTemplateLoader(templateLoader); final Template template = configuration.getTemplate(templateName); template.process(params, writer); return writer.toString(); } catch (Throwable e) { throw new RuntimeException("Unable to process template", e); } }
/** * 返回激活链接 * * @param email email * @return 有3个参数 email password */ public static String getContent(String email, String password, Configuration configuration) { Long now = TimeUtil.getNowOfMills(); Map<String, Object> data = new HashMap<>(10); StringBuilder sb = new StringBuilder("http://localhost:8080/user/validate?email="); sb.append(email); sb.append("&password="); sb.append(password); sb.append("&time="); sb.append(now); data.put("email", email); data.put("url", sb.toString()); data.put("now", TimeUtil.getFormatDate(now, TimeUtil.DEFAULT_FORMAT)); Template template; String readyParsedTemplate = null; try { template = configuration.getTemplate("email.ftl"); readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, data); } catch (Exception e) { e.printStackTrace(); } return readyParsedTemplate; }
private IStatus writeCommandCards(boolean obsRefreshFlag, String templateInputDirectory, String templateOutputDirectory) { Writer playerArmyFile = null; try { Configuration config = us.nineworlds.xstreamer.core.Activator.getDefault().getFreemarkerConfig(); config.setDirectoryForTemplateLoading(new File(templateInputDirectory)); java.nio.file.Path jpath = java.nio.file.Paths.get(templateFilename); Template armyTemplate = config.getTemplate(jpath.getFileName().toString()); playerArmyFile = new FileWriter(new File(templateOutputDirectory + File.separator + commandFilename)); Map<String, Object> input = new HashMap<>(); input.put("iaspec", iaspec); input.put("allDeployments", Activator.getDefault().getDeploymentsLookup().getDeployments()); input.put("allCommandCards", Activator.getDefault().getCommandCardLookup().getCommandCards()); input.put("obs_refresh", obsRefreshFlag); armyTemplate.process(input, playerArmyFile); } catch (Exception e) { e.printStackTrace(); return Status.CANCEL_STATUS; } finally { IOUtils.closeQuietly(playerArmyFile); } return Status.OK_STATUS; }
/** * Create the php index listing all of the Docs features * * @param cfg * @param workUnitList * @param groupMaps * @throws IOException */ protected void processIndexTemplate( final Configuration cfg, final List<DocWorkUnit> workUnitList, final List<Map<String, String>> groupMaps ) throws IOException { // Get or create a template and merge in the data final Template template = cfg.getTemplate(getIndexTemplateName()); final File indexFile = new File(getDestinationDir(), getIndexBaseFileName() + '.' + getIndexFileExtension() ); try (final FileOutputStream fileOutStream = new FileOutputStream(indexFile); final OutputStreamWriter outWriter = new OutputStreamWriter(fileOutStream)) { template.process(groupIndexMap(workUnitList, groupMaps), outWriter); } catch (TemplateException e) { throw new DocException("Freemarker Template Exception during documentation index creation", e); } }
private PluginStatusReportViewBuilder() throws IOException { configuration = new Configuration(Configuration.VERSION_2_3_23); configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/")); configuration.setDefaultEncoding("UTF-8"); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setLogTemplateExceptions(false); configuration.setDateTimeFormat("iso"); }
private void createTemplateConfiguration(final CompositeConfiguration config, final File templatesPath) { templateCfg = new Configuration(); templateCfg.setDefaultEncoding(config.getString(Keys.RENDER_ENCODING)); try { templateCfg.setDirectoryForTemplateLoading(templatesPath); } catch (IOException e) { e.printStackTrace(); } templateCfg.setObjectWrapper(new DefaultObjectWrapper()); }
public void testSpeedOfFreemarker() throws Exception { Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(getWorkDir()); cfg.setObjectWrapper(new BeansWrapper()); Template templ = cfg.getTemplate("template.txt"); for(int i = 0; i < whereTo.length; i++) { Writer out = new BufferedWriter(new FileWriter(whereTo[i])); templ.process(parameters, out); out.close(); } }
public static String renderString(String templateString, Map<String, ?> model) { try { StringWriter result = new StringWriter(); Template t = new Template("name", new StringReader(templateString), new Configuration(Configuration.VERSION_2_3_23)); t.process(model, result); return result.toString(); } catch (Exception e) { throw Exceptions.unchecked(e); } }
/** * Initializes template engine configuration. */ private void initTemplateEngineCfg() { configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext(); configuration.setServletContextForTemplateLoading(servletContext, "/plugins/" + dirName); logger.debug("Initialized template configuration:{}", dirName); readLangs(); }
public NexuDeployScriptController() { try { Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setClassForTemplateLoading(getClass(), "/"); this.template = cfg.getTemplate("nexu_deploy.ftl.js", "UTF-8"); } catch (IOException e) { throw new RuntimeException(); } }
public static TemplateHashModel useStaticPackage(String key) { try { BeansWrapper wrapper = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel statics = (TemplateHashModel) staticModels.get(key); return statics; } catch (Exception e) { e.printStackTrace(); } return null; }
@PostConstruct public void init() throws IOException { try { cfg = new Configuration(Configuration.getVersion()); cfg.setDirectoryForTemplateLoading(new File(templateLocation)); cfg.setDefaultEncoding(templateEncoding); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } catch (IOException e) { logger.error("Problem getting rule template location." + e.getMessage()); throw e; } }
public FreemarkerAttachmentRenderer(final String templateName) { this.templateName = templateName; this.configuration = new Configuration(Configuration.VERSION_2_3_23); this.configuration.setLocalizedLookup(false); this.configuration.setTemplateUpdateDelayMilliseconds(0); this.configuration.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "tpl"); }
private static Configuration initializeTemplateConfiguration() throws IOException { Configuration cfg = new Configuration(Configuration.getVersion()); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); return cfg; }
/** * Generate a dockerrun.aws.json file with a custom user template * @param dockerrunFilePath the location of the dockerrun template * @param dockerrunOutputDestination the output directory * @param parameters a map to hydrate the template with * @throws IOException if failed to load the template file * @throws TemplateException if template generation fails */ public static void generateUserDockerrunFile( String dockerrunFilePath, String dockerrunOutputDestination, Map<String, Object> parameters ) throws IOException, TemplateException { File templateFile = new File(dockerrunFilePath); Configuration cfg = initializeTemplateConfiguration(); cfg.setDirectoryForTemplateLoading(templateFile.getParentFile()); generateFileFromTemplate(cfg, templateFile.getName(), dockerrunOutputDestination, parameters); }
/** *Generate a dockerrun.aws.json file with the default template * @param outputFilePath the output directory * @param parameters a map to hydrate the default template with * @throws IOException if failed to load the template file * @throws TemplateException if template generation fails */ public static void generateDefaultDockerrunFile( String outputFilePath, Map<String, Object> parameters ) throws IOException, TemplateException { Configuration cfg = initializeTemplateConfiguration(); cfg.setClassForTemplateLoading(FileGenerator.class, "/"); final String defaultDockerrunTemplateFile = "DockerrunTemplate.ftlh"; generateFileFromTemplate(cfg, defaultDockerrunTemplateFile, outputFilePath, parameters); }
private static void generateFileFromTemplate(Configuration cfg, String templateFile, String outputFilePath, Map<String, Object> parameters) throws IOException, TemplateException { Template temp = cfg.getTemplate(templateFile); File file = new File(outputFilePath); if (file.getParent() != null) { file.getParentFile().mkdirs(); } FileWriter writer = new FileWriter(file); temp.process(parameters, writer); }
protected Configuration getFreemarkerConfiguration(RepoCtx ctx) { Configuration cfg = new Configuration(); cfg.setObjectWrapper(new DefaultObjectWrapper()); // custom template loader cfg.setTemplateLoader(new TemplateWebScriptLoader(ctx.getRepoEndPoint(), ctx.getTicket())); // TODO review i18n cfg.setLocalizedLookup(false); cfg.setIncompatibleImprovements(new Version(2, 3, 20)); cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); return cfg; }
protected String processFreemarker(Map<String, Template> templateCache, String fmTemplate, Configuration cfg, Map<String, Object> model) throws IOException, TemplateException, Exception { // Save on lots of modification date checking by caching templates locally Template myTemplate = templateCache.get(fmTemplate); if (myTemplate == null) { myTemplate = cfg.getTemplate(fmTemplate); templateCache.put(fmTemplate, myTemplate); } StringWriter textWriter = new StringWriter(); myTemplate.process(model, textWriter); return textWriter.toString(); }