Java Code Examples for freemarker.template.TemplateException

The following examples show how to use freemarker.template.TemplateException. These examples are extracted from open source projects. 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 Project: freeacs   Source File: UnitJobPage.java    License: MIT License 6 votes vote down vote up
private void getFailedUnitJobs(Job job, Output res, DataSource mainDataSource)
    throws SQLException, IOException, TemplateException {
  res.setTemplatePath("unit-job/failed");
  Map<String, Object> rootMap = new HashMap<>();
  UnitJobs unitJobs = new UnitJobs(mainDataSource);
  List<UnitJob> unitJobsList = unitJobs.readAllProcessed(job);
  //		List<UnitJob> list = new ArrayList<UnitJob>();
  //		if (limit != null) {
  //			for (int i = 0; i < limit && i <= unitJobsList.size() - 1; i++) {
  //				list.add(unitJobsList.get(i));
  //			}
  //			unitJobsList = list;
  //		}
  SessionCache.getSessionData(sessionId).setFailedUnitJobsList(null);
  if (!unitJobsList.isEmpty()) {
    rootMap.put("unitJobs", unitJobsList);
    SessionCache.getSessionData(sessionId).setFailedUnitJobsList(unitJobsList);
  }
  rootMap.put("job", job);
  rootMap.put("async", inputData.getAsync().getString());
  //		rootMap.put("limit", limit);
  res.getTemplateMap().putAll(rootMap);
}
 
Example 2
Source Project: google-cloud-eclipse   Source File: Templates.java    License: Apache License 2.0 6 votes vote down vote up
public static void createFileContent(
    String outputFileLocation, String templateName, Map<String, String> dataMap)
    throws CoreException {
  Preconditions.checkNotNull(outputFileLocation, "output file is null");
  Preconditions.checkNotNull(templateName, "template name is null");
  Preconditions.checkNotNull(dataMap, "data map is null");

  if (configuration == null) {
    configuration = createConfiguration();
  }
  Path outputFile = Paths.get(outputFileLocation);
  try (Writer writer =
      new OutputStreamWriter(Files.newOutputStream(outputFile), StandardCharsets.UTF_8)) {
    Template template = configuration.getTemplate(templateName);
    template.process(dataMap, writer);
  } catch (IOException | TemplateException ex) {
    throw new CoreException(StatusUtil.error(Templates.class, ex.getMessage()));
  }
}
 
Example 3
Source Project: estatio   Source File: DocFragmentService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Overload of {@link #render(Object, String)}, but allowing the atPath to be specified explicitly rather than inferred from the supplied domain object.
 *
 * @param domainObject provides the state for the interpolation into the fragment's {@link DocFragment#getTemplateText() template text}
 * @param name corresponds to the {@link DocFragment#getName() name} of the {@link DocFragment} to use to render.
 * @param atPath corrsponds to the {@link ApplicationTenancyService#atPathFor(Object) atPath} of the {@link DocFragment} to use to render
 *
 * @throws IOException
 * @throws TemplateException
 * @throws RenderException - if could not locate any {@link DocFragment}.
 */
@Programmatic
public String render(
            final Object domainObject,
            final String name,
            final String atPath)
        throws IOException, TemplateException, RenderException {
    final String objectType = objectTypeFor(domainObject);

    final DocFragment fragment = repo.findByObjectTypeAndNameAndApplicableToAtPath(objectType, name, atPath);

    if (fragment != null)
        return fragment.render(domainObject);
    else
        throw new RenderException(
                "No fragment found for objectType: %s, name: %s, atPath: %s",
                objectType, name, atPath);
}
 
Example 4
Source Project: Mario   Source File: TemplateFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateFactoryForService() throws IOException,
		TemplateException {
	TemplateFactory factory = TemplateFactory.getInstance();
	String path = "templates/Service.java.ftl";

	SqlTable table = new SqlTable(schema, tablename);
	Map<String, Object> data = new HashMap<String, Object>();
	data.put("sqlTable", table);
	Properties properties = ApplicationProperties.getProperties();
	data.put("prop", properties);

	String content = factory.process(path, data, "UTF-8");
	assertTrue(StringUtils.isNotBlank(content));

}
 
Example 5
Source Project: synopsys-detect   Source File: GenerateDocsTask.java    License: Apache License 2.0 6 votes vote down vote up
@TaskAction
public void generateDocs() throws IOException, TemplateException, IntegrationException {
    final Project project = getProject();
    final File file = new File("synopsys-detect-" + project.getVersion() + "-help.json");
    final Reader reader = new FileReader(file);
    final HelpJsonData helpJson = new Gson().fromJson(reader, HelpJsonData.class);

    final File outputDir = project.file("docs/generated");
    final File troubleshootingDir = new File(outputDir, "advanced/troubleshooting");

    FileUtils.deleteDirectory(outputDir);
    troubleshootingDir.mkdirs();

    final TemplateProvider templateProvider = new TemplateProvider(project.file("docs/templates"), project.getVersion().toString());

    createFromFreemarker(templateProvider, troubleshootingDir, "exit-codes", new ExitCodePage(helpJson.getExitCodes()));

    handleDetectors(templateProvider, outputDir, helpJson);
    handleProperties(templateProvider, outputDir, helpJson);
    handleContent(outputDir, templateProvider);
}
 
Example 6
Source Project: molgenis   Source File: ScriptUtils.java    License: 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 7
Source Project: allure2   Source File: ReportWebPlugin.java    License: Apache License 2.0 6 votes vote down vote up
protected void writeIndexHtml(final Configuration configuration,
                              final Path outputDirectory) throws IOException {
    final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
    final Path indexHtml = outputDirectory.resolve("index.html");
    final List<PluginConfiguration> pluginConfigurations = configuration.getPlugins().stream()
            .map(Plugin::getConfig)
            .collect(Collectors.toList());

    try (BufferedWriter writer = Files.newBufferedWriter(indexHtml)) {
        final Template template = context.getValue().getTemplate("index.html.ftl");
        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Constants.PLUGINS_DIR, pluginConfigurations);
        template.process(dataModel, writer);
    } catch (TemplateException e) {
        LOGGER.error("Could't write index file", e);
    }
}
 
Example 8
Source Project: generator   Source File: ControllerTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() throws IOException, TemplateException {
    // 生成Controller填充数据
    Map<String, String> controllerData = new HashMap<>();
    controllerData.put("BasePackageName", ConfigUtil.getConfiguration().getPackageName());
    controllerData.put("ControllerPackageName", ConfigUtil.getConfiguration().getPath().getController());
    if (StringUtil.isBlank(ConfigUtil.getConfiguration().getPath().getInterf())) {
        controllerData.put("ServicePackageName", ConfigUtil.getConfiguration().getPath().getService());
    } else {
        controllerData.put("ServicePackageName", ConfigUtil.getConfiguration().getPath().getInterf());
    }
    controllerData.put("EntityPackageName", ConfigUtil.getConfiguration().getPath().getEntity());
    controllerData.put("Author", ConfigUtil.getConfiguration().getAuthor());
    controllerData.put("Date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    controllerData.put("ClassName", className);
    controllerData.put("EntityName", StringUtil.firstToLowerCase(className));
    String filePath = FileUtil.getSourcePath() + StringUtil.package2Path(ConfigUtil.getConfiguration().getPackageName()) + StringUtil.package2Path(ConfigUtil.getConfiguration().getPath().getController());
    String fileName = className + "Controller.java";
    // 生成Controller文件
    FileUtil.generateToJava(FreemarketConfigUtil.TYPE_CONTROLLER, controllerData, filePath, fileName);
}
 
Example 9
Source Project: j-road   Source File: DatabaseGenerator.java    License: 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 10
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars,
		TemplateDirectiveBody body) throws TemplateException, IOException {
	Integer siteId = getSiteId(params);
	if (siteId == null) {
		siteId = FrontUtils.getSite(env).getId();
	}
	List<CmsFriendlinkCtg> list = cmsFriendlinkCtgMng.getList(siteId);

	Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(
			params);
	paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
	Map<String, TemplateModel> origMap = DirectiveUtils
			.addParamsToVariable(env, paramWrap);
	body.render(env.getOut());
	DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
}
 
Example 11
Source Project: camel-kafka-connector   Source File: MavenUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Document createCrateXmlDocumentFromTemplate(Template template, Map<String, String> props) throws IOException, TemplateException, ParserConfigurationException, SAXException {
    StringWriter sw = new StringWriter();
    template.process(props, sw);

    String xml = sw.toString();
    ByteArrayInputStream bin = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    return builder.parse(bin);
}
 
Example 12
Source Project: pacbot   Source File: GlobalConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
    FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
    factory.setTemplateLoaderPaths("classpath:templates", "src/main/resources/templates");
    factory.setDefaultEncoding("UTF-8");
    FreeMarkerConfigurer result = new FreeMarkerConfigurer();
    result.setConfiguration(factory.createConfiguration());
    return result;
}
 
Example 13
Source Project: scipio-erp   Source File: MacroMenuRenderer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void renderMenuOpen(Appendable writer, Map<String, Object> context, ModelMenu menu) throws IOException {
    contextHandler.registerContext(writer, context);
    Map<String, Object> parameters = new HashMap<>();
    if (ModelWidget.widgetBoundaryCommentsEnabled(context)) {
        StringBuilder sb = new StringBuilder("Begin Menu Widget ");
        sb.append(menu.getBoundaryCommentName());
        parameters.put("boundaryComment", sb.toString());
    }
    MenuRenderState renderState = MenuRenderState.retrieve(context); // SCIPIO
    parameters.put("id", menu.getId());
    parameters.put("style", menu.getMenuContainerStyle(context));
    parameters.put("title", menu.getTitle(context));
    // SCIPIO: new attribs
    parameters.put("titleStyle", menu.getTitleStyle(context));
    parameters.put("inlineEntries", renderState.isInlineEntries());
    parameters.put("menuCtxRole", renderState.getMenuCtxRoleOrEmpty());

    MenuAndItem selectedMenuAndItem = renderState.getSelectedMenuAndItem(context);
    ModelMenuItem selectedMenuItem = selectedMenuAndItem.getMenuItem();
    ModelSubMenu selectedSubMenu = selectedMenuAndItem.getSubMenu();

    boolean selected = selectedSubMenu == null && menu.isParentOf(selectedMenuItem);
    boolean selectedAncestor = !selected && (selectedSubMenu != null || (selectedMenuItem != null && !menu.isParentOf(selectedMenuItem)));
    parameters.put("selected", selected);
    parameters.put("selectedAncestor", selectedAncestor);

    // SCIPIO: 2017-02-17: new
    parameters.put("name", menu.getName());

    // SCIPIO: 2017-04-25: new
    parameters.put("sepMenuType", renderState.getSeparateMenuConfig().getType());
    // NOTE: sepMenuDef is added using special code further below

    try {
        executeMacro(writer, "renderMenuBegin", parameters);
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 14
Source Project: studio   Source File: UserServiceImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean forgotPassword(String username) throws ServiceLayerException, UserNotFoundException,
        UserExternallyManagedException {
    logger.debug("Getting user profile for " + username);
    User user = userServiceInternal.getUserByIdOrUsername(-1, username);
    boolean success = false;
    if (user == null) {
        logger.info("User profile not found for " + username);
        throw new UserNotFoundException();
    } else {
        if (user.isExternallyManaged()) {
            throw new UserExternallyManagedException();
        } else {
            if (user.getEmail() != null) {
                String email = user.getEmail();

                logger.debug("Creating security token for forgot password");
                long timestamp = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(
                        Long.parseLong(studioConfiguration .getProperty(SECURITY_FORGOT_PASSWORD_TOKEN_TIMEOUT)));
                String salt = studioConfiguration.getProperty(SECURITY_CIPHER_SALT);
                String studioId = instanceService.getInstanceId();
                String token = username + "|" + studioId + "|" + timestamp + "|" + salt;
                String hashedToken = encryptToken(token);
                logger.debug("Sending forgot password email to " + email);
                try {
                    sendForgotPasswordEmail(email, hashedToken);
                } catch (MessagingException | IOException | TemplateException e) {
                    throw new ServiceLayerException("Error while sending forgot password email", e);
                }
                success = true;
            } else {
                logger.info("User " + username + " does not have assigned email with account");
                throw new ServiceLayerException("User " + username + " does not have assigned email with account");
            }
        }
    }
    return success;
}
 
Example 15
Source Project: mblog   Source File: PrincipalTag.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
    String result = null;

    if (getSubject() != null) {
        // Get the principal to print out
        Object principal;

        if (getType(params) == null) {
            principal = getSubject().getPrincipal();
        } else {
            principal = getPrincipalFromClassName(params);
        }

        // Get the string value of the principal
        if (principal != null) {
            String property = getProperty(params);

            if (property == null) {
                result = principal.toString();
            } else {
                result = getPrincipalProperty(principal, property);
            }
        }
    }

    // Print out the principal value if not null
    if (result != null) {
        try {
            env.getOut().write(result);
        } catch (IOException ex) {
            throw new TemplateException("Error writing [" + result + "] to Freemarker.", ex, env);
        }
    }
}
 
Example 16
Source Project: mxjc   Source File: FreemarkerProcessor.java    License: MIT License 5 votes vote down vote up
/**
 * Get the template exception handler.  The default one prints the stack trace to <code>System.err</code>
 * rather than the writer because often Freemarker is printing to temp files.
 *
 * @return The template exception handler.
 */
private TemplateExceptionHandler getTemplateExceptionHandler() {
    return new TemplateExceptionHandler() {
      public void handleTemplateException(TemplateException templateException, Environment environment, Writer writer) throws TemplateException {
        templateException.printStackTrace(System.err);
        throw templateException;
      }
    };
}
 
Example 17
Source Project: maven-confluence-plugin   Source File: PreprocessorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<String> process(String input, Map<String, Object> variables) {
    
    final CompletableFuture<String> result = new CompletableFuture<>();
    try {
        Template t = new Template(UUID.randomUUID().toString(), new StringReader(input), cfg);
        StringWriter out = new StringWriter();
        t.process(getModel(variables), out);
        result.complete( out.toString() );
    } catch (IOException | TemplateException e) {          
        result.completeExceptionally( new IllegalArgumentException("Error while processing the template!", e));
    }
    
    return result;
}
 
Example 18
Source Project: mblog   Source File: UserTag.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
    if (getSubject() != null && getSubject().getPrincipal() != null) {
        log.debug("Subject has known identity (aka 'principal'). Tag body will be evaluated.");
        renderBody(env, body);
    } else {
        log.debug("Subject does not exist or have a known identity (aka 'principal'). Tag body will not be evaluated.");
    }
}
 
Example 19
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars,
		TemplateDirectiveBody body) throws TemplateException, IOException {
	CmsSite site = FrontUtils.getSite(env);
	List<ContentTag> list = contentTagMng.getListForTag(FrontUtils
			.getCount(params));

	Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(
			params);
	paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
	Map<String, TemplateModel> origMap = DirectiveUtils
			.addParamsToVariable(env, paramWrap);
	InvokeType type = DirectiveUtils.getInvokeType(params);
	String listStyle = DirectiveUtils.getString(PARAM_STYLE_LIST, params);
	if (InvokeType.sysDefined == type) {
		if (StringUtils.isBlank(listStyle)) {
			throw new ParamsRequiredException(PARAM_STYLE_LIST);
		}
		env.include(TPL_STYLE_LIST + listStyle + TPL_SUFFIX, UTF8, true);
	} else if (InvokeType.userDefined == type) {
		if (StringUtils.isBlank(listStyle)) {
			throw new ParamsRequiredException(PARAM_STYLE_LIST);
		}
		FrontUtils.includeTpl(TPL_STYLE_LIST, site, env);
	} else if (InvokeType.custom == type) {
		FrontUtils.includeTpl(TPL_NAME, site, params, env);
	} else if (InvokeType.body == type) {
		body.render(env.getOut());
	} else {
		throw new RuntimeException("invoke type not handled: " + type);
	}
	DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
}
 
Example 20
Source Project: allure2   Source File: MailPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void aggregate(final Configuration configuration,
                      final List<LaunchResults> launchesResults,
                      final Path outputDirectory) throws IOException {
    final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
    final Path exportFolder = Files.createDirectories(outputDirectory.resolve(Constants.EXPORT_DIR));
    final Path mailFile = exportFolder.resolve("mail.html");
    try (BufferedWriter writer = Files.newBufferedWriter(mailFile)) {
        final Template template = context.getValue().getTemplate("mail.html.ftl");
        template.process(new HashMap<>(), writer);
    } catch (TemplateException e) {
        LOGGER.error("Could't write mail file", e);
    }
}
 
Example 21
Source Project: scipio-erp   Source File: MacroScreenRenderer.java    License: Apache License 2.0 5 votes vote down vote up
public void renderScreenletSubWidget(Appendable writer, Map<String, Object> context, ModelScreenWidget subWidget, ModelScreenWidget.Screenlet screenlet) throws GeneralException, IOException {
    //if (!shouldOutput(writer, context)) return; // SCIPIO: 2017-05-04: optimization: avoid prep if unneeded // CANNOT due to .renderWidgetString logic done here
    if (subWidget.equals(screenlet.getNavigationForm())) {
        HttpServletRequest request = (HttpServletRequest) context.get("request");
        HttpServletResponse response = (HttpServletResponse) context.get("response");
        if (request != null && response != null) {
            Map<String, Object> globalCtx = UtilGenerics.checkMap(context.get("globalContext"));
            globalCtx.put("NO_PAGINATOR", true);
            FormStringRenderer savedRenderer = (FormStringRenderer) context.get("formStringRenderer");
            MacroFormRenderer renderer = null;
            try {
                // SCIPIO: FIXME: this is hardcoded to HTML because formrender variable always points to html render
                // this is wrong on many levels
                renderer = new MacroFormRenderer(formrendererName, formrenderer, request, response); // SCIPIO: modified for name
            } catch (TemplateException e) {
                Debug.logError("Not rendering content, error on MacroFormRenderer creation.", module);
                handleError(writer, e); // SCIPIO
            }
            renderer.setRenderPagination(false);
            context.put("formStringRenderer", renderer);
            subWidget.renderWidgetString(writer, context, this);
            context.put("formStringRenderer", savedRenderer);
        }
    } else {
        subWidget.renderWidgetString(writer, context, this);
    }
}
 
Example 22
Source Project: yuzhouwan   Source File: WelcomePage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取模板 & 合并模板和数据模型.
 *
 * @param cfg
 * @param root
 * @throws IOException
 * @throws TemplateException
 */
private void showUp(Configuration cfg, Map<String, Object> root, String ftlPath, String outPath)
        throws IOException, TemplateException {
    Template temp = cfg.getTemplate(ftlPath);
    Writer out = new OutputStreamWriter(System.out);
    temp.process(root, out);

    try (FileWriter fileWriter = new FileWriter(new File(outPath))) {
        temp.process(root, fileWriter);
    }
}
 
Example 23
Source Project: scipio-erp   Source File: MacroScreenRenderer.java    License: Apache License 2.0 5 votes vote down vote up
private void executeMacro(Appendable writer, String macro) throws IOException {
    if (!shouldOutput(writer)) return; // SCIPIO: 2017-05-04: new, here as a failsafe (NOTE: not most efficient location for check)

    try {
        Environment environment = getEnvironment(writer);
        Reader templateReader = new StringReader(macro);
        // FIXME: I am using a Date as an hack to provide a unique name for the template...
        Template template = new Template((new java.util.Date()).toString(), templateReader, FreeMarkerWorker.getDefaultOfbizConfig());
        templateReader.close();
        FreeMarkerWorker.includeTemplate(template, environment); // SCIPIO: use FreeMarkerWorker instead of Environment
    } catch (TemplateException | IOException e) {
        Debug.logError(e, "Error rendering screen macro [" + macro + "] thru ftl", module);
        handleError(writer, e); // SCIPIO
    }
}
 
Example 24
Source Project: tutorials   Source File: FreemarkerTransformerUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException, TemplateException {
    String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
      .getResource("/xmlhtml/notification.html")
      .toURI()))));
    StaxTransformer staxTransformer = new StaxTransformer("src/test/resources/xmlhtml/notification.xml");
    String templateFile = "freemarker.html";
    String templateDirectory = "src/test/resources/templates";
    FreemarkerTransformer transformer = new FreemarkerTransformer(staxTransformer, templateDirectory, templateFile);

    String result = transformer.html();

    assertThat(result).isEqualTo(expectedHtml);
}
 
Example 25
Source Project: cloudbreak   Source File: AwsNetworkCfTemplateProvider.java    License: Apache License 2.0 5 votes vote down vote up
public String provide(NetworkCreationRequest networkCreationRequest, List<SubnetRequest> subnets) {

        Map<String, Object> model = createModel(networkCreationRequest, subnets);
        try {
            String freeMarkerTemplate = freemarkerConfiguration.getTemplate(cloudFormationNetworkTemplatePath, "UTF-8").toString();
            Template template = new Template("aws-template", freeMarkerTemplate, freemarkerConfiguration);
            return freeMarkerTemplateUtils.processTemplateIntoString(template, model).replaceAll("\\t|\\n| [\\s]+", "");
        } catch (IOException | TemplateException e) {
            throw new CloudConnectorException("Failed to process CloudFormation freemarker template", e);
        }
    }
 
Example 26
Source Project: scipio-erp   Source File: MacroTreeRenderer.java    License: Apache License 2.0 5 votes vote down vote up
private Environment getEnvironment(Appendable writer) throws TemplateException, IOException {
    Environment environment = environments.get(writer);
    if (environment == null) {
        // SCIPIO: custom render context
        Map<String, Object> input = contextHandler.createRenderContext(writer, null, UtilMisc.toMap("key", null));
        environment = FreeMarkerWorker.renderTemplate(macroLibrary, input, writer, MacroScreenRenderer.AUTO_FLUSH_MACROS); // SCIPIO: Added auto-flush control
        environments.put(writer, environment);
    }
    return environment;
}
 
Example 27
Source Project: mblog   Source File: NotAuthenticatedTag.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
    if (getSubject() == null || !(getSubject().isAuthenticated() || getSubject().isRemembered())) {
        log.debug("Subject does not exist or is not authenticated.  Tag body will be evaluated.");
        renderBody(env, body);
    } else {
        log.debug("Subject exists and is authenticated.  Tag body will not be evaluated.");
    }
}
 
Example 28
Source Project: robozonky   Source File: AbstractListenerTest.java    License: Apache License 2.0 5 votes vote down vote up
private <T extends Event> void testHtmlProcessing(final AbstractListener<T> listener,
        final T event) throws IOException, TemplateException {
    final Map<String, Object> data = new HashMap<>(listener.getData(event, SESSION));
    data.put("subject", UUID.randomUUID()
        .toString());
    final String s = TemplateProcessor.INSTANCE.processHtml(listener.getTemplateFileName(),
            Collections.unmodifiableMap(data));
    logger.debug("HTML text was: {}.", s);
    assertThat(s).contains(Defaults.ROBOZONKY_URL);
    assertThat(s).contains("uživatel"); // check that UTF-8 is properly encoded
}
 
Example 29
Source Project: fun-generator   Source File: IndexController.java    License: MIT License 5 votes vote down vote up
@RequestMapping("/codeGenerate")
@ResponseBody
public CommonResult codeGenerate(String tableSql) {

    try {
        if (StringUtils.isBlank(tableSql)) {
            return CommonResult.failed("表结构信息不可为空");
        }

        // parse table
        GenTable genTable= CodeGeneratorTool.processTableIntoClassInfo(tableSql);

        // code genarete
        Map<String, Object> params = new HashMap<>();
        params.put("classInfo", genTable);

        // result
        Map<String, String> result = new HashMap<>();

        result.put("controller_code", freemarkerTool.processString("xxl-code-generator/controller.ftl", params));
        result.put("service_code", freemarkerTool.processString("xxl-code-generator/service.ftl", params));
        result.put("service_impl_code", freemarkerTool.processString("xxl-code-generator/service_impl.ftl", params));
        result.put("dao_code", freemarkerTool.processString("xxl-code-generator/mapper.ftl", params));
        result.put("mybatis_code", freemarkerTool.processString("xxl-code-generator/mybatis.ftl", params));
        result.put("model_code", freemarkerTool.processString("xxl-code-generator/entity.ftl", params));

        // 计算,生成代码行数
        int lineNum = 0;
        for (Map.Entry<String, String> item : result.entrySet()) {
            if (item.getValue() != null) {
                lineNum += StringUtils.countMatches(item.getValue(), "\n");
            }
        }
        logger.info("生成代码行数:{}", lineNum);
        return CommonResult.success(result);
    } catch (IOException | TemplateException e) {
        logger.error(e.getMessage(), e);
        return CommonResult.failed("表结构解析失败");
    }
}
 
Example 30
Source Project: JApiDocs   Source File: HtmlControllerDocBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String buildDoc(ControllerNode controllerNode) throws IOException {
    for (RequestNode requestNode : controllerNode.getRequestNodes()) {
        if (requestNode.getResponseNode() != null && !requestNode.getResponseNode().getChildNodes().isEmpty()) {
            JavaCodeGenerator javaCodeGenerator = new JavaCodeGenerator(requestNode.getResponseNode());
            final String javaSrcUrl = javaCodeGenerator.generateCode();
            requestNode.setAndroidCodePath(javaSrcUrl);
            ModelCodeGenerator iosCodeGenerator = new ModelCodeGenerator(requestNode.getResponseNode());
            final String iosSrcUrl = iosCodeGenerator.generateCode();
            requestNode.setIosCodePath(iosSrcUrl);
        }
    }

    final Template ctrlTemplate = getControllerTpl();
    final File docFile = new File(DocContext.getDocPath(), controllerNode.getDocFileName());
    FileWriter docFileWriter = new FileWriter(docFile);
    Map<String, Object> data = new HashMap<>();
    data.put("controllerNodeList", DocContext.getControllerNodeList());
    data.put("controller", controllerNode);
    data.put("currentApiVersion", DocContext.getCurrentApiVersion());
    data.put("apiVersionList", DocContext.getApiVersionList());
    data.put("projectName", DocContext.getDocsConfig().getProjectName());
    data.put("i18n", DocContext.getI18n());
    try {
        ctrlTemplate.process(data, docFileWriter);
    } catch (TemplateException ex) {
        ex.printStackTrace();
    } finally {
        Utils.closeSilently(docFileWriter);
    }
    return Utils.streamToString(new FileInputStream(docFile));
}