freemarker.template.DefaultObjectWrapper Java Examples

The following examples show how to use freemarker.template.DefaultObjectWrapper. 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: CreateFileUtil.java    From Vert.X-generator with MIT License 7 votes vote down vote up
/**
 * 执行创建文件
 * 
 * @param content
 *          模板所需要的上下文
 * @param templeteName
 *          模板的名字 示例:Entity.ftl
 * @param projectPath
 *          生成的项目路径 示例:D://create
 * @param packageName
 *          包名 示例:com.szmirren
 * @param fileName
 *          文件名 示例:Entity.java
 * @param codeFormat
 *          输出的字符编码格式 示例:UTF-8
 * @throws Exception
 */
public static void createFile(GeneratorContent content, String templeteName, String projectPath, String packageName, String fileName,
		String codeFormat, boolean isOverride) throws Exception {
	String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/";
	if (!isOverride) {
		if (Files.exists(Paths.get(outputPath + fileName))) {
			LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
			return;
		}
	}
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
	config.setDirectoryForTemplateLoading(new File(tempPath));
	config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
	config.setDefaultEncoding("utf-8");
	Template template = config.getTemplate(templeteName);
	Map<String, Object> item = new HashMap<>();
	item.put("content", content);
	if (!Files.exists(Paths.get(outputPath))) {
		Files.createDirectories(Paths.get(outputPath));
	}
	try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
		template.process(item, writer);
	}
}
 
Example #2
Source File: ValidatableFormAdapter.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
public ValidatableFormAdapter(Validatable form, DefaultObjectWrapper ow) {
    super(form, ow);
    this.hasErrors = arguments -> {
        switch (arguments.size()) {
            case 0:
                return (Boolean) form.hasErrors();
            case 1:
                return (Boolean) form.hasErrors(arguments.get(0).toString());
            default:
                return null;
        }
    };

    this.getErrors = arguments -> {
        switch (arguments.size()) {
            case 0:
                return form.getErrors();
            case 1:
                return form.getErrors(arguments.get(0).toString());
            default:
                return null;
        }
    };
}
 
Example #3
Source File: FreemarkerTemplateHandler.java    From myexcel with Apache License 2.0 6 votes vote down vote up
private void setObjectWrapper(Configuration configuration) {
    configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23) {
        @Override
        public TemplateModel wrap(Object object) throws TemplateModelException {
            if (object instanceof LocalDate) {
                return new SimpleDate(Date.valueOf((LocalDate) object));
            }
            if (object instanceof LocalTime) {
                return new SimpleDate(Time.valueOf((LocalTime) object));
            }
            if (object instanceof LocalDateTime) {
                return new SimpleDate(Timestamp.valueOf((LocalDateTime) object));
            }
            return super.wrap(object);
        }
    });
}
 
Example #4
Source File: QNameAwareObjectWrapper.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected ObjectWrapper initialValue()
{
    return new DefaultObjectWrapper()
    {
        /* (non-Javadoc)
         * @see freemarker.template.DefaultObjectWrapper#wrap(java.lang.Object)
         */
        @Override
        public TemplateModel wrap(Object obj) throws TemplateModelException
        {
            if (obj instanceof QNameMap)
            {
                return new QNameHash((QNameMap)obj, this);
            }
            else
            {
                return super.wrap(obj);
            }
        }
    };
}
 
Example #5
Source File: XmlIngesterAftBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected List<File> buildUserFileUploadList() throws Exception {
    List<File> fileUploadList = new ArrayList<File>();
    try {
        Properties props = loadProperties(PROPS_LOCATION, DEFAULT_PROPS_LOCATION);

        String usersArg = System.getProperty("xmlingester.user.list").replace(".", "").replace("-", "").toLowerCase();
        List<XmlIngesterUser> xmlIngesterUsers = new LinkedList<XmlIngesterUser>();
        StringTokenizer token = new StringTokenizer(usersArg, ",");
        while (token.hasMoreTokens()) {
            xmlIngesterUsers.add(new XmlIngesterUser(token.nextToken()));
        }

        props.put("xmlIngesterUsers", xmlIngesterUsers);

        cfg.setObjectWrapper(new DefaultObjectWrapper());

        // build files and add to array
        fileUploadList.add(
                writeTemplateToFile(newTempFile("userlist-users.xml"), cfg.getTemplate("UserListIngestion.ftl"), props));

    } catch( Exception e) {
        throw new Exception("Unable to generate files for upload " + e.getMessage(), e);
    }

    return fileUploadList;
}
 
Example #6
Source File: LocalFeedTaskProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #7
Source File: FilesGenerator.java    From QuickProject with Apache License 2.0 6 votes vote down vote up
public void generate() throws GlobalConfigException {
    Configuration cfg = new Configuration();
    File tmplDir = globalConfig.getTmplFile();
    try {
        cfg.setDirectoryForTemplateLoading(tmplDir);
    } catch (IOException e) {
        throw new GlobalConfigException("tmplPath", e);
    }
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    for (Module module : modules) {
        logger.debug("module:" + module.getName());
        for (Bean bean : module.getBeans()) {
            logger.debug("bean:" + bean.getName());
            Map dataMap = new HashMap();
            dataMap.put("bean", bean);
            dataMap.put("module", module);
            dataMap.put("generate", generate);
            dataMap.put("config", config);
            dataMap.put("now", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));

            generate(cfg, dataMap);
        }
    }
}
 
Example #8
Source File: DatabaseGenerator.java    From j-road with Apache License 2.0 6 votes vote down vote up
public static void generate(DatabaseClasses classes, String outputdir) throws IOException, TemplateException {
  Configuration cfg = new Configuration();
  cfg.setClassForTemplateLoading(TypeGen.class, "/");
  cfg.setObjectWrapper(new DefaultObjectWrapper());

  Template interfaceTemp = cfg.getTemplate(DATABASE_TEMPLATE_FILE);
  Template implTemp = cfg.getTemplate(DATABASE_IMPL_TEMPLATE_FILE);

  for (DatabaseClass databaseClass : classes.getClasses().values()) {
    Map<String, DatabaseClass> root = new HashMap<String, DatabaseClass>();
    root.put("databaseClass", databaseClass);

    Writer out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedInterfaceName(), outputdir);
    interfaceTemp.process(root, out);
    out.flush();

    out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedImplementationName(), outputdir);
    implTemp.process(root, out);
    out.flush();
  }
}
 
Example #9
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 #10
Source File: MailService.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public String processTemplate(String templateUrl, Map<String, Object> model) {
	try {
		if(templateUrl != null) {
			String mailBody = mailContentBuilderService.getRemoteMailContent(templateUrl);
			Configuration cfg = new Configuration();
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			Template t = new Template(UUID.randomUUID().toString(), new StringReader(mailBody), cfg);
		    Writer out = new StringWriter();
			t.process(model, out);
			return out.toString();
		}
	} catch (Exception exception) {
		Log.error(exception.getMessage());
	}
	return null;
}
 
Example #11
Source File: AbstractTestExecutorService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
	super.setUp();
	try {
		Configuration config = new Configuration();
		DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
		config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
		config.setObjectWrapper(wrapper);
		config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
		TemplateModel templateModel = this.createModel(wrapper);
		ExecutorBeanContainer ebc = new ExecutorBeanContainer(config, templateModel);
		super.getRequestContext().addExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER, ebc);
	} catch (Throwable t) {
		throw new Exception(t);
	}
}
 
Example #12
Source File: MapperGenerator.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
private static void genMapperXml(Map<String, Object> params, String className, String resourcePath,
                                 GeneratorConfig generatorConfig) {

    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = MapperGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "mapper//";
        String savePath = filePath + className + "Mapper.xml";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter out = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("mapper_xml.ftl");
            template.process(params, out);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example #13
Source File: SourceReportGenerator.java    From testability-explorer with Apache License 2.0 6 votes vote down vote up
public SourceReportGenerator(GradeCategories grades, SourceLoader sourceLoader,
    File outputDirectory, CostModel costModel, Date currentTime,
    int worstCount, Configuration cfg) {
  this.grades = grades;
  this.sourceLoader = sourceLoader;
  this.directory = outputDirectory;
  this.costModel = costModel;
  this.cfg = cfg;
  cfg.setTemplateLoader(new ClassPathTemplateLoader(PREFIX));
  cfg.setObjectWrapper(new DefaultObjectWrapper());
  try {
    cfg.setSharedVariable("maxExcellentCost", grades.getMaxExcellentCost());
    cfg.setSharedVariable("maxAcceptableCost", grades.getMaxAcceptableCost());
    cfg.setSharedVariable("currentTime", currentTime);
    cfg.setSharedVariable("computeOverallCost", new OverallCostMethod());
    cfg.setSharedVariable("printCost", new PrintCostMethod());
  } catch (TemplateModelException e) {
    throw new RuntimeException(e);
  }
  projectByClassReport = new ProjectReport("index", grades,
      new WeightedAverage());
  projectByClassReport.setMaxUnitCosts(worstCount);
  projectByPackageReport = new ProjectReport("index", grades,
      new WeightedAverage());
}
 
Example #14
Source File: DTOGenerator.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
private static void genDTO(Map<String, Object> paramMap,
                           String reousrcePath,
                           GeneratorConfig generatorConfig) {


    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = ControllerGenerator.class.getClassLoader().getResource(reousrcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "dto//";
        String savePath = filePath + paramMap.get("className") + "DTO.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("dto.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: MessagesForCostDetailBoxTest.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  Configuration cfg = new Configuration();
  cfg.setTemplateLoader(new ClassPathTemplateLoader(ReportGeneratorProvider.PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  cfg.setObjectWrapper(objectWrapper);
  ResourceBundleModel messageBundleModel =
      new ResourceBundleModel(ResourceBundle.getBundle("messages"), objectWrapper);
  issueQueue = Lists.newLinkedList();
  template = cfg.getTemplate("costDetailBoxTest.ftl");
  model = new HashMap<String, Object>();
  model.put("message", messageBundleModel);
  model.put("sourceLink", new SourceLinkerModel(new SourceLinker("", "")));
}
 
Example #16
Source File: Generator.java    From doma-gen with Apache License 2.0 5 votes vote down vote up
/**
 * インスタンスを構築します。
 *
 * @param templateEncoding テンプレートファイルのエンコーディング
 * @param templatePrimaryDir テンプレートファイルを格納したプライマリディレクトリ、プライマリディレクトリを使用しない場合{@code null}
 */
public Generator(String templateEncoding, File templatePrimaryDir) {
  if (templateEncoding == null) {
    throw new NullPointerException("templateFileEncoding");
  }
  this.configuration = new Configuration();
  configuration.setObjectWrapper(new DefaultObjectWrapper());
  configuration.setSharedVariable("currentDate", new OnDemandDateModel());
  configuration.setEncoding(Locale.getDefault(), templateEncoding);
  configuration.setNumberFormat("0.#####");
  configuration.setTemplateLoader(createTemplateLoader(templatePrimaryDir));
}
 
Example #17
Source File: ControllerServlet.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void initFreemarker(HttpServletRequest request,
		HttpServletResponse response, RequestContext reqCtx)
		throws TemplateModelException {
	Configuration config = new Configuration();
	DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
	config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
	config.setObjectWrapper(wrapper);
	config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
	TemplateModel templateModel = this.createModel(wrapper, this.getServletContext(), request, response);
	ExecutorBeanContainer ebc = new ExecutorBeanContainer(config, templateModel);
	reqCtx.addExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER, ebc);
}
 
Example #18
Source File: EntityGenerator.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
public static void generatorSingleEntity(String tableName, String className,
                                         String classComment, GeneratorConfig generatorConfig) {
    TableInfo tableInfo = AnalysisDB.getTableInfoByName(tableName, generatorConfig);
    Map<String, Object> paramMap = new HashMap<>();

    paramMap.put("className", className);
    paramMap.put("tableInfo", tableInfo);
    paramMap.put("sysTime", new Date());
    paramMap.put("classComment", classComment);
    paramMap.put("packageName", generatorConfig.getPackageName());


    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        configuration.setDirectoryForTemplateLoading(new File(EntityGenerator.class.getClassLoader()
                .getResource("ftl").getPath()));
        String savePath = PackageDirUtils.getPackageEntityDir(generatorConfig.getSrcBasePath());
        String filePath = generatorConfig.getSrcBasePath() + "entity//";
        savePath = filePath + className + ".java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(savePath)) {
            Template temporal = configuration.getTemplate("entity.ftl");
            temporal.process(paramMap, fileWriter);
        }
        System.out.println("************" + savePath + "************");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: FreemarkerService.java    From hasting with MIT License 5 votes vote down vote up
@Override
public void startService() {
	cfg.setDefaultEncoding(encoding);
	try {
		cfg.setDirectoryForTemplateLoading(new File(location));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		cfg.setNumberFormat("#");
		logger.info("freemarker service started");
	} catch (IOException e) {
		logger.error("setDirectoryForTemplateLoading IOException location: "+location,e);
		throw new RuntimeException(e);
	}
}
 
Example #20
Source File: CodeGenerator.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException {
    File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile();

    Bean bean = new Bean();
    bean.setTableName(tableName);

    String[] attrArray = attrs.replace(", ", ",").split(",");
    for (String attr : attrArray) {
        try {
            String[] splits = attr.split(" ");
            Property property = new Property();
            property.setType(new PropertyType(splits[0]));
            property.setName(splits[1]);
            bean.addProperty(property);
        } catch (Exception e) {
            throw new RuntimeException("attr的格式应为$Javatype$ $attrName$");
        }
    }

    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(dir);
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    Template temp = cfg.getTemplate(isReturnList ? "daoGetForListMethodTmpl.ftl" : "daoGetForObjMethodTmpl.ftl");
    Map dataMap = new HashMap();
    dataMap.put("bean", bean);
    if (beanNameRegex != null) {
        // 根据用户设置修正beanName
        Pattern pattern = Pattern.compile(beanNameRegex);
        Matcher matcher = pattern.matcher(bean.getTableName());
        matcher.find();
        String group = matcher.group(matcher.groupCount());
        bean.setName(StringUtils.uncapitalizeCamelBySeparator(group, "_"));
    }
    Writer out = new OutputStreamWriter(System.out);
    temp.process(dataMap, out);
    out.flush();
    out.close();
}
 
Example #21
Source File: FreeMarkerRenderer.java    From opoopress with Apache License 2.0 5 votes vote down vote up
public FreeMarkerRenderer(Site site) {
    super();
    this.site = site;
    templateDir = site.getTemplates();
    log.debug("Template directory: " + templateDir.getAbsolutePath());

    //Working directory
    workingTemplateDir = new File(site.getWorking(), "templates");
    PathUtils.checkDir(workingTemplateDir, PathUtils.Strategy.CREATE_IF_NOT_EXISTS);
    log.debug("Working template directory: {}", workingTemplateDir.getAbsolutePath());

    //config
    configuration = new Configuration();
    configuration.setObjectWrapper(new DefaultObjectWrapper());
    configuration.setTemplateLoader(buildTemplateLoader(site));

    Locale locale = site.getLocale();
    if (locale != null) {
        configuration.setLocale(site.getLocale());
    }

    //Add import i18n messages template.
    //config.addAutoImport("i18n", "i18n/messages.ftl");

    initializeAutoImportTemplates(site, configuration);
    initializeAutoIncludeTemplates(site, configuration);

    initializeTemplateModels();


    renderMethod = site.get(PROPERTY_PREFIX + "render_method");

    Boolean useMacroLayout = site.get(PROPERTY_PREFIX + "macro_layout");
    workingTemplateHolder = (useMacroLayout == null || useMacroLayout.booleanValue()) ?
            new MacroWorkingTemplateHolder() : new NonMacroWorkingTemplateHolder();
}
 
Example #22
Source File: ViewExportedVariablesServletTest.java    From util with Apache License 2.0 5 votes vote down vote up
private ViewExportedVariablesServlet setupServlet() throws IOException {
    final Configuration config = new Configuration();
    config.setObjectWrapper(new DefaultObjectWrapper());
    config.setClassForTemplateLoading(this.getClass(), "/");

    final ViewExportedVariablesServlet servlet = new ViewExportedVariablesServlet();
    servlet.setVarTextTemplate(config.getTemplate("vars-text.ftl"));
    servlet.setVarHtmlTemplate(config.getTemplate("vars-html.ftl"));
    servlet.setBrowseNamespaceTemplate(config.getTemplate("browsens.ftl"));

    return servlet;
}
 
Example #23
Source File: TestWBFreeMarkerModuleDirective.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test_execute_catch_exception()
{
	Environment envMock = PowerMock.createMock(Environment.class);
	TemplateModel[] loopVars = null;
	TemplateDirectiveBody directiveBodyMock = null;
	
	Map params = new HashMap();
	String name = "testXYZ";
	StringModel nameModel = new StringModel(name, new DefaultObjectWrapper() );
	params.put("name", nameModel);

	try
	{
		
		WPBPageModule pageModuleMock = PowerMock.createMock(WPBPageModule.class);		
		WPBPageModulesCache pageModuleCacheMock = PowerMock.createMock(WPBPageModulesCache.class);
		EasyMock.expect(pageModuleCacheMock.getByExternalKey(name)).andThrow(new WPBIOException(""));
		
		EasyMock.expect(cacheInstancesMock.getPageModuleCache()).andReturn(pageModuleCacheMock);

		EasyMock.replay(cacheInstancesMock, templateEngineMock, envMock, pageModuleMock, pageModuleCacheMock);
		
		FreeMarkerModuleDirective templateDirective = new FreeMarkerModuleDirective();
		Whitebox.setInternalState(templateDirective, "templateEngine",templateEngineMock);
		Whitebox.setInternalState(templateDirective, "cacheInstances",cacheInstancesMock);
		PowerMock.suppressMethod(FreeMarkerModuleDirective.class, "copyParams");
		templateDirective.execute(envMock, params, loopVars, directiveBodyMock);
		
		assertTrue(false);		
	} catch (Exception e)
	{
		assertTrue(e instanceof TemplateModelException);
	}
}
 
Example #24
Source File: TestWBFreeMarkerModuleDirective.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test_execute_noPageModule()
{
	Environment envMock = PowerMock.createMock(Environment.class);
	TemplateModel[] loopVars = null;
	TemplateDirectiveBody directiveBodyMock = null;
	
	Map params = new HashMap();
	String name = "testXYZ";
	StringModel nameModel = new StringModel(name, new DefaultObjectWrapper() );
	params.put("name", nameModel);

	try
	{

		WPBPageModule pageModuleMock = PowerMock.createMock(WPBPageModule.class);		
		WPBPageModulesCache pageModuleCacheMock = PowerMock.createMock(WPBPageModulesCache.class);
		EasyMock.expect(pageModuleCacheMock.getByExternalKey(name)).andReturn(null);
		
		EasyMock.expect(cacheInstancesMock.getPageModuleCache()).andReturn(pageModuleCacheMock);

		EasyMock.replay(cacheInstancesMock, templateEngineMock, envMock, pageModuleMock, pageModuleCacheMock);
		
		FreeMarkerModuleDirective templateDirective = new FreeMarkerModuleDirective();
		Whitebox.setInternalState(templateDirective, "templateEngine",templateEngineMock);
		Whitebox.setInternalState(templateDirective, "cacheInstances",cacheInstancesMock);
		PowerMock.suppressMethod(FreeMarkerModuleDirective.class, "copyParams");
		templateDirective.execute(envMock, params, loopVars, directiveBodyMock);
	
		assertTrue(false);
		
	} catch (Exception e)
	{
		assertTrue(e instanceof TemplateModelException);
	}
}
 
Example #25
Source File: GetLogarithmicDistribution.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    if (arguments.size() < 2)
        throw new TemplateModelException(NAME + ": Expected 2 arguments, count and maximum count.");

    if (!(arguments.get(0) instanceof TemplateNumberModel))
        throw new TemplateModelException(NAME + ": Both arguments must be numbers, but the first was " + arguments.get(0).getClass().getName());
    if (!(arguments.get(1) instanceof TemplateNumberModel))
        throw new TemplateModelException(NAME + ": Both arguments must be numbers, but the second was " + arguments.get(1).getClass().getName());

    int count = ((TemplateNumberModel) arguments.get(0)).getAsNumber().intValue();
    if (count < 1)
        return new SimpleNumber(0);

    int maximum = ((TemplateNumberModel) arguments.get(1)).getAsNumber().intValue();
    if (maximum < 0)
        throw new TemplateModelException(NAME + "Maximum must be at least 0, " + maximum);

    if (count > maximum)
    {
        LOG.severe("Count " + count + " is larger than maximum " + maximum + ". Using the maximum as count.");
        count = maximum;
    }

    double ratio = ((double)count) / ((double)maximum + QUITE_A_LOT_FACTOR); //  <0..1>

    // Map it to scale 1..1000.
    double ratio2 = 1.0d + ratio * (998d * (1-FLATTENER));
    double log10 = Math.log10(ratio2) / 3D;    // 0..2.999  =>  0..0.999
    //LOG.info(String.format("count: %d, max: %d, ratio %f, ratio2 %f, log10 %f", count, maximum, ratio, ratio2, log10));
    return new NumberModel(Double.valueOf(log10), new DefaultObjectWrapper());
}
 
Example #26
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 #27
Source File: Templates.java    From live-chat-engine with Apache License 2.0 5 votes vote down vote up
public Templates(String dirPath) throws IOException {
	this.dirPath = dirPath;
	
	cfg = new Configuration();
	cfg.setLocalizedLookup(false);
       cfg.setDirectoryForTemplateLoading(new File(this.dirPath));
       cfg.setObjectWrapper(new DefaultObjectWrapper());
       cfg.setDefaultEncoding("UTF-8");
       cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
       cfg.setIncompatibleImprovements(new Version(2, 3, 20));
}
 
Example #28
Source File: MailService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Async
public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
    log.debug("sendMail() - to: " + to);
    MimeMessage message = mailSender.createMimeMessage();
    try {
        String stringDir = MailService.class.getResource("/templates/freemarker").getPath();
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDefaultEncoding("UTF-8");

        File dir = new File(stringDir);
        cfg.setDirectoryForTemplateLoading(dir);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));

        StringBuffer content = new StringBuffer();
        Template temp = cfg.getTemplate(template + ".ftl");
        content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters));

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\"");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        mailSender.send(message);

        log.info("Message has been sent to: " + to);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #29
Source File: FreeMarkertUtil.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 初始化模板配置
 * 
 * @param servletContext
 *            javax.servlet.ServletContext
 * @param templateDir
 *            模板位置
 */
public static void initConfig(ServletContext servletContext,
		String templateDir) {
	config.setLocale(Locale.CHINA);
	config.setDefaultEncoding("utf-8");
	config.setEncoding(Locale.CHINA, "utf-8");
	templateDir="WEB-INF/templates";
	config.setServletContextForTemplateLoading(servletContext, templateDir);
	config.setObjectWrapper(new DefaultObjectWrapper());
}
 
Example #30
Source File: ControllerGenerator.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
private static void genController(String className,
                                  String classComment,
                                  String urlStr,
                                  String resourcePath,
                                  GeneratorConfig generatorConfig) {
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("className", className);
    paramMap.put("classComment", classComment);
    paramMap.put("sysTime", new Date());
    paramMap.put("packageName", generatorConfig.getPackageName());
    paramMap.put("url", urlStr);
    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = ControllerGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "controller//";
        String savePath = filePath + className + "Controller.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("/controller.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}